question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
3,656,354 | 3,656,410 | What's the principle of template in C++? | And which templating library should new beginner user?
Not sure if OS matter,I'm talking about windows if that matters.
| For beginner it is better to start from a good book. And the Standard Library (often also called STL) is the template library you should start from.
|
3,656,454 | 3,656,566 | C++ free encryption libraries | So far I've come across Botan and Crypto++ which both provide reversible (e.g AES) and non-reversible (e.g SHA) encryption. I wondered if anyone can recommend either, or something else?
| OpenSSL has all the functionality that you would expect and it is often already installed (at least on Linux).
It supports asymmetric/symmetric encryption, digital signatures and hashing algorithms. For example, you can use the high-level OpenSSL EVP API for symmetric encryption.
|
3,656,985 | 3,657,087 | Reboot on installation of .CAB WM | On a Windows Mobile 6 or CE 5 device, I need to install a CAB file and then initiate a reboot.
I am aware of custom actions. You need to create a setup.dll for the CAB file in native C++.
So I have the following code already made
codeINSTALL_EXIT Install_Exit(HWND hwndParent,
LPCTSTR pszIn... | From this thread I understand that one needs to inform the installing process that a reboot is required after installing the CAB package.
So instead of codeINSTALL_EXIT_DONE just return CONFIG_S_REBOOTREQUIRED (without SetSystemPowerState).
I usually restart windows with ExitWindowsEx instead of SetSystemPowerState.Exi... |
3,657,078 | 3,657,449 | Subtract images by using opencv | I want to subtract two images. My problem ist that the cvSub()-function saturates. What I want to do is:
1) Convert the original images to grayscale.
2) Take the grayscale-images (values from 0-255).
3) Subtract the images (values from -255 to 255) -> problem of rescaling using cvSub().
4) Rescale by multiplying with 0... | Using openCV you could do the following:
scale both source images (1 and 2) by factor 0.5. Both images are now in range [0..127]
shift image 1 by 128. It now is in the range [128..255]
subtract image 2 from image 1
This way, no range conversion is needed and the result is fully scaled to 8 bit. Use the cvConvertScale... |
3,657,268 | 3,657,458 | Convert built in types to vector<char> | My TcpClient class accepts vector<char> in its SendData method like this:
void CTcpClient::SendData(const vector<char>& dataToTransmit)
Therefore, in order to use the function, I have to convert any built in type (int, long, short, long long) to a vector<char>.
I tried several solutions using streams but always end ... | Ignoring endianess:
template< typename T >
char* begin_binary(const T& obj) {return reinterpret_cast<char*>(&obj);}
template< typename T >
char* end_binary (const T& obj) {return begin_binary(obj)+sizeof(obj);}
int num = 0x01234567;
vector<char> whatIWant( begin_binary(num), end_binary(num) );
However, I would use ... |
3,657,269 | 3,657,346 | deleting bytes from an ostringstream | how do i delete the first n bytes of an ostringstream?
I basically have to see howmany bytes went over a socket and if it did not go through fully...i have to delete whatever went through
| Just do what you said : remove the first n bytes ?
ostr.str(ostr.str().substr(n))
|
3,657,494 | 3,657,647 | Weird compiler error and template inheritance | Could someone explain me why this code:
class safe_bool_base
{ //13
protected:
typedef void (safe_bool_base::*bool_type)() const;
void this_type_does_not_support_comparisons() const {} //18
safe_bool_base() {}
safe_bool_base(const safe_bool_base&) {}
safe_bool_base& operat... | This should probably help (reproducible in a non template situation also)
struct A{
protected:
void f(){}
};
struct B : A{
void g(){&A::f;} // error, due to Standard rule quoted below
};
int main(){
}
VS gives "'A::f' : cannot access
protected member declared in class
'A'"
For the same code, Com... |
3,657,583 | 3,657,625 | shared memory across compilers? | I have to start off by saying I have very little idea on this topic so humor me if i seem ignorant.
Due to the problem of having to use a vc++ library in a g++ compiled program, I built a local server-client system where the server is compiled in vc++ and the client in g++ and they interact through sockets. A lot of da... | If they are on same PC then yes, shared memory is faster and it defenetly work across different programs.
If it's on different PCs then also yes, but it's not gonna be faster than sockets.
|
3,657,633 | 3,657,753 | why is that IXSLTemplate::putref_stylesheet compile when passed an IXMLDOMDocument argument | I am playing with XSLT with MSXML2 for the first time. And of course it doesn't work :-)
I have a bug which I cannot figure to solve.
So as to fix the bug, I try to understand everything around: and something shocks me.
void xsltProcessing(IXMLDOMDocument* pXmlDoc, IXMLDOMDocument * pXslDoc)
{
CComPtr<IXSLTemplate>... | IXMLDOMDocument is derived from IXMLDOMNode according to MSDN. Hence it is same as passing a derived class pointer to a class expecting a base class pointer. Hence it compiles.
|
3,657,935 | 3,736,572 | Compiling using gcc 3.2.3 on RHE 5.3 | Some work I'm doing for a client requires me to build using a very old version of gcc on Red Hat Enterprise. We recently shifted from 4.x to 5.3 and I'm hitting some compile errors when I try to build simple example:
#include <iostream>
int main()
{
std::cout << "Hello World" << std::endl;
return 0;
}
I get ... | What's your LD_LIBRARY_PATH set to? In particular gcc relies on libgcc* and libstdc++* (although if you've statically linked it that shouldn't be an issue). If it is an issue try setting your LD_LIBRARY_PATH to /opt/ext/gcc-3.2.3.34rh/lib:$LD_LIBRARY_PATH.
|
3,657,998 | 3,660,053 | For graphics drawing on WinCE platform, which language is faster: MFC VC++ or C# | I need to draw extensive realtime graphics on WinCE platform.
For that purpose, which language is better between VC++ and C# to get high performance?
Moreover, the graphics application that we would be developing should be linked to currently existing c++ modules. If writing intermediate layer involves lot of effort if... | You seem to be answering your own question. It is heavily loaded towards saying c++ is the preferred choice.
If you chose c# then yes you would have to write wrappers and look after allt he type conversions (along with all testing) prior to starting to extend your functionality.
why do you need such high graphics perfo... |
3,658,065 | 3,703,817 | Help with camera in OpenGL | Right now my application rotates on camera.rotationX, Y Z and does a -translation of camera.x,y,z on the modelview matrix. How could I equivocate this to a call to gluLookAt?
Thanks
basically how could I get this:
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//starts here
glRotatef(Camera.rotx,1,0,0);... | Well your eye position E will be (Camera.x, Camera.y + 4.5, Camera.z).
The default view vector V is (0, 0, -1) in OpenGL, if I remember correctly and
default up vector U is (0, 1, 0).
So you rotate these two vectors with your camera rotation.
See http://en.wikipedia.org/wiki/Rotation_matrix or http://en.wikipedia.org/w... |
3,658,420 | 3,658,993 | Pointer (trick): Memory Reference | A trick question about C pointer. Read code snippet below and try explain why the list value changed (this question was based on this code):
tail has the memory address of list.
How is possible list be changed below?
typedef struct _node {
struct _node *next;
int value;
}Node;
int main(){
Node *list, *node... | Let's look at what happens to the memory in your program. You start with 3 local variables, all of type Node*. At the moment they all point to garbage, as they have been declared but not initialised.
An ascii art diagram of the memory might be (The layout is implementation dependant)
list node tail
--------... |
3,658,429 | 3,658,514 | How to convert from BYTE* to QString? | I have a DATA_BLOB structure but I need to convert it to QString. How can I do this?
| You can use the QString constructor with a QByteArray parameter.
You can use too the constructor with the const char* parameter too
Hope that helps
|
3,658,631 | 3,658,666 | What is the byte alignment of the elements in a std::vector<char>? | I'm hoping that the elements are 1 byte aligned and similarly that a std::vector<int> is 4 byte aligned ( or whatever size int happens to be on a particular platform ).
Does anyone know how standard library containers get aligned?
| The elements of the container have at least the alignment required for them in that implementation: if int is 4-aligned in your implementation, then each element of a vector<int> is an int and therefore is 4-aligned. I say "if" because there's a difference between size and alignment requirements - just because int has ... |
3,658,682 | 3,659,358 | IXSLTemplate::putref_stylesheet returns E_INVALIDARG | Well, it's been several hours I'm lost...
IXSLTemplate::putref_stylesheet doesn't document any error except E_FAIL.
However in my case putref_stylesheet returns E_INVALIDARG. GetErrorInfo() is only redundant telling me that the "Argument is invalid". So I am not left with much information.
However my code is pretty clo... | Are you loading pXslDoc asynchronously perhaps?
The default behaviour for IXMLDOMDocument objects is to load asynchronously, so it is possible that the pXslDoc has not finished loading when you call putref_stylesheet().
Adding the following code before you load pXslDoc would fix this problem, if it is what you are suff... |
3,658,854 | 3,658,928 | Does it make sense to implement the copy-assignment operator in a class with all const data members? | Imagine I have a class used to represent some trivial numerical data, like a vector. I want this class to be immutable in terms of its members, but still support correct copy-assignment behaviour.
This is what the shell of this class might look like:
class Vector {
public:
Vector(float _x, float _y);
private:
... | When you type
Vector position;
in a class definition, you define an instance of a Vector class that will stay here forever. If that one is immutable, you're screwed.
In C#/Java, there is no way to do this. Instead you define references.
If you want to do the same thing in C++, you need pointers or auto_pointers
Vector... |
3,659,044 | 3,659,731 | Comparison of C++ STL collections and C# collections? | I'm still learning C# and was surprised to find out that a List<T> is much more like a std::vector than a std::list. Can someone describe all the C# collections in terms of the STL (or if STL comparisons are difficult, standard conceptual data types with Wikipedia links? I expect the reference would be widely useful.... | Here's what I've found (ignoring the old non-generic collections):
Array - C array, though the .NET Array can have a non-zero starting index.
List<T> - std::vector<T>
Dictionary<TKey, TValue> - unordered_map<Key, Data>
HashSet<T> - unordered_set<Key>
SortedDictionary<TKey, TValue> - std::map<Key, Data>
SortedList<TKe... |
3,659,070 | 3,744,985 | GCC Reducing Binary Bloat -- Strange Side Effect | The Weirdness
I have compiled Google Protocol Buffers using no extra parameters for a "bloat" compile, and compile with the following command ./configure CXXFLAGS="-ffunction-sections -fdata-sections". a du-h reveals:
120K ./bloat/bin
124K ./bloat/include/google/protobuf/io
8.0K ./bloat/include/google/protobuf/compiler... | I am afraid the gain has nothing to do with -ffunction-sections -fdata-sections: when you specified CXXFLAGS="-ffunction-sections -fdata-sections" on configure command line, you overwrote the default flags which were -O2 -g -DNDEBUG. As a consequence, your code was compiled with no optimizations.
You should redo your t... |
3,659,126 | 3,668,028 | How to interrupt select/pselect running in QThread | I have a QThread that reads from a socket and sends a signal (QT signal) when there are any data available.
This would be easy with blocking read(2), but i need to be able to stop the thread from outside without waiting for too long.
If I were using pthread I would use pselect and pthread_kill(thread_id, some_signal), ... | A not too elegant, but simple and working solution:
Create a pipe and let select wait for either the pipe or my socket. This way I can stop the wait anytime by writing something to the pipe.
|
3,659,285 | 3,659,377 | I don't seem to understand the output of this program regarding conversion of integer pointer to character pointer | In the program below i initiliaze i to 255
Thus in Binary we have:
0000 0000 1111 1111
That is in Hex:
0x 0 0 f f
So according to Little-Endian layout:
The Lower Order Byte - 0xff is stored first.
#include<cstdio>
int main()
{
int i=0x00ff; //I know 0xff works. Just tried to make it understable
char *cptr... | Where did you get the idea that 1111 1111 is -127? Apparently, you are assuming that the "sign bit" should be interpreted independently from the rest of the bits, i.e. setting the sign bit in binary representation of +127 should turn it into -127, right? Well, a representation that works that way does indeed exist: it ... |
3,659,296 | 3,659,356 | Any reason to use a run-time assert instead of compile-time assert? | While reviewing Visual C++ codebase I found a following strange thing. A run-time assert (which is check the condition and throw an exception if the condition is violated) was used in a case when the condition could be evaluated at compile time:
assert( sizeof( SomeType ) == sizeof( SomeOtherType ) );
clearly the comp... | There's no reason to prefer a run-time assert here. You should prefer compile-time errors over run-time errors so there's never a reason, given the option between the two, to choose a run-time assert.
However, if a static assert isn't an option (doesn't know the concept of a static assert, doesn't know how to make one ... |
3,659,336 | 3,659,535 | compare and swap vs test and set | Could someone explain to me the working and differences of above operations in multi-threading?
| test-and-set modifies the contents of a memory location and returns its old value as a single atomic operation.
compare-and-swap atomically compares the contents of a memory location to a given value and, only if they are the same, modifies the contents of that memory location to a given new value.
The difference mar... |
3,659,426 | 3,659,542 | Get Lua state from inside Lua so it can be passed back to C | I am able to load a DLL created from C source from within Lua. So what I want to be able to do is pass the current Lua state FROM Lua to the loaded DLL.
Basically I'm using a game engine that uses Lua. The scene editor of said game engine creates the Lua state and calls Lua scripts and I know for a fact that it uses 1... | I'm missing something obvious, I guess (which wouldn't surprise me - I'm far from a Lua expert).
But if you call package.loadlib, the function handle you get back IS going to be called with the state by Lua itself, isn't it? See the CFunction prototype
|
3,659,433 | 3,659,842 | How to use curlpp's InfoGetter? | I'm using curlpp in an application and need to get the URL I was redirected to. Apparently there are two ways: track the Location headers (ugly) or use curlpp::InfoGetter (the c++ counterpart of curl_easy_getinfo()).
But how do I use curlpp::InfoGetter? I cant't find any examples. Does anyone have a short snippet?
| Ok, just found it out by myself:
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Infos.hpp>
curlpp::Easy request;
request.setOpt(new curlpp::options::Url("http://www.example.com/"));
request.perform();
std::string effective_url = curlpp::infos::EffectiveUrl::get(request);
You may use any othe... |
3,659,448 | 3,659,493 | Extending enum in derived classes | I have a class hierarchy, and each class in it has an exception class, derived in a parallel hierarchy, thus...
class Base
{
};
class Derived : public Base
{
};
class BaseException : public std::exception
{
enum {THIS_REASON, THAT_REASON};
};
class DerivedException : public BaseException
{
// er...what?
};
I... | From the OO standpoint, it is not reasonable. Since you say that DerivedException is-a BaseException, its possible reasons must be a subset of that of BaseException, not a superset. Otherwise you ultimately break the Liskov Substitution Principle.
Moreover, since C++ enums are not classes, you can't extend or inherit t... |
3,659,528 | 3,659,605 | Recommendation on big integer calculation library | Could your recommend some good big integer calculation library in C/C++/Java and it is better to support logarithmetic.
Thanks.
|
For C/C++ I would recommend the GNU Multiple Precision Library.
For Java you might check the built-in math API. It provides by far less functionality than GMP, but depending on what you need, it might meet your requirements.
|
3,659,839 | 3,659,936 | Can I cause a compile error on "too few initializers"? | I am using an aggregate initializer to set up a block of static data for a unit test.
I would like to use the array size as the expected number of elements, but this can fail if too few initializers are provided:
my_struct_type expected[14] =
{
{ 1.234, 0, 'c' },
{ 3.141, 1, 'z' },
{ 2.718, 0, 'a' }
};
Thi... | First: There might be a warning for this. Have you tried compiling at the highest warning level?
Then: If you swap which value is calculated and which is literal, you could raise a compile-time error:
my_struct_type my_array[] = // <== note the empty []
{
{ 1.234, 0, 'c' },
{ 3.141, 1, 'z' },
{ 2.718, 0, '... |
3,659,946 | 3,660,149 | Creating dynamically sized objects | Removed the C tag, seeing as that was causing some confusion (it shouldn't have been there to begin with; sorry for any inconvenience there. C answer as still welcome though :)
In a few things I've done, I've found the need to create objects that have a dynamic size and a static size, where the static part is your basi... | I'd go for a compromise with the DynamicObject concept. Everything that doesn't depend on the size goes into the base class.
struct TextBase
{
uint_32 fFlags;
uint_16 nXpos;
uint_16 nYpos;
TextBase* pNext;
};
template <const size_t nSize> struct TextCache : public TextBase
{
char pBuffer[... |
3,660,137 | 3,660,184 | Generate Windows Compatible Binary from Xcode C++ Console Application | I am using XCode for developing a C++ Console Application. After compiling XCode generates the Unix Executable File, which run on Mac perfectly. But doesn't work on windows. I have tried changing the active architecture as well from x86_64 to i386 but no luck.
Is it possible anyway to generate executable like Borland C... | XCode does not generate Windows binaries. Processor architecture isn't the only thing that is different - executable format, names of import libraries, ABI, etc., etc.
Use a Windows compiler, like Visual C++ Express, to generate a Windeows binary.
|
3,660,368 | 3,660,427 | C++ - basic thread question | I have a simple threading question - how should the following be synchronized?
I have main thread and a secondary thread that does something only once and something - more that once.
Basically:
Secondary thread:
{
Do_Something_Once();
while (not_important_condition) {
Do_Something_Inside_Loop();
}
}
I ... | This is a job for condition variables.
Check out the Condition Variables section of the boost docs - the example there is almost exactly what you're doing.
Whatever you do, don't do a busy-wait loop with sleep
|
3,660,539 | 3,660,574 | Drawing a temporary 'select' rectangle on a drawing area | I have a complex drawing on a Gtk DrawingArea widget and I wish to provide the user with a way to select a rectangle on it to expand for a closer view. I have managed to get the necessary mouse button events sorted out so that the rectangle can be selected, but it would be desirable to have the actual rectangle drawn o... | You are looking for the Rubber Band technique.
|
3,660,593 | 3,660,677 | Advance tab position in C++? | I'm currently writing a program that has debug output strewn throughout it. This is all well and good, but I'd like to be able to advance the tab position for things in different scopes, for instance, this is what I have right now:
#ifndef NDEBUG
printf("Updating player\n");
#endif
player.Update();
#ifndef NDEBUG
print... | You could have a class that essentially maintained a "tab count" and had a print_line function: when called, it would output tab-count tabs, and then print the line. While you could have a increment_indent function, you could create a sister object TabIndent using RAII: When it is created, increment the tab, when it is... |
3,660,709 | 3,660,775 | How to set the area/rectangle in which the cursor is allowed to move? | E.g. when you hit the side of your monitor your cursor can't go any further, and more of an example is when in microsoft paint, and your choosing a colour from the RGB table, it won't allow your mouse to go outside of the rectangle while your mouse is down..
my question is how would you implement that in c++ with win32... | You can use the following function from Microsoft
BOOL WINAPI ClipCursor(
__in_opt const RECT *lpRect
);
See http://msdn.microsoft.com/en-us/library/ms648383(VS.85).aspx
|
3,660,814 | 3,660,853 | Can't specify a file path prefix in program | In my program I am trying to construct a filename with a path to point to a particular folder where my data is stored. I have something that looks like this:
string directoryPrefix = "C:\Input data\";
string baseFileName = "somefile.bin";
string fileName = directoryPrefix + index + " " + baseFileName;
However the comp... | \ is a special character
string directoryPrefix = "C:\Input data\";
you have special commands in the string \I and \" and so your string is not terminated
double up the \ to escape the escape character
string directoryPrefix = "C:\\Input data\\";
|
3,660,901 | 3,660,928 | A warning - comparison between signed and unsigned integer expressions | I am currently working through Accelerated C++ and have come across an issue in exercise 2-3.
A quick overview of the program - the program basically takes a name, then displays a greeting within a frame of asterisks - i.e. Hello ! surrounded framed by *'s.
The exercise - In the example program, the authors use const ... | It is usually a good idea to declare variables as unsigned or size_t if they will be compared to sizes, to avoid this issue. Whenever possible, use the exact type you will be comparing against (for example, use std::string::size_type when comparing with a std::string's length).
Compilers give warnings about comparing ... |
3,660,909 | 3,660,939 | Chat server design of the "main" loop | I am writing on a small tcp chat server, but I am encountering some problems I can´t figure out how to solve "elegantly".
Below is the code for my main loop: it does:
1.Initiates a vector with the basic event, which is flagged, when a new tcp connection is made.
2. gets this connection and pushes it back into a vector,... | Do not re-invent the wheel, use Boost.ASIO. It is well optimized utilizing kernel specific features of different operating systems, designed the way which makes client code architecture simple. There are a lot of examples and documentation, so you just cannot get it wrong.
|
3,661,041 | 3,661,245 | How To Receive Output From A Child Process' STDOUT Without Blocking or Poling | I have a long-running console-based application Sender that sends simple text to STDOUT using non-buffered output such as cout << "Message" << flush(). I want to create an MFC dialog-based application (named Receiver) that starts Sender and can read it's output. Receiver should also be able to detect when Sender has ... | You have 2 basic options. Option 1 you've already tried, doing asynchronous (aka nonblocking) IO to read/write from the child process. Option 2 is to create a separate thread in the Receiver process that does blocking reads/writes from/to the child process.
I'd recommend option 2, I find it much easier. You then, ... |
3,661,106 | 3,661,355 | Overlapped ReadFileEx on Child Process' Redirected STDOUT Never Fires | I have a long-running console-based application Sender that sends simple text to STDOUT using non-buffered output such as cout << "Message" << flush(). I want to create an MFC dialog-based application (named Receiver) that starts Sender and can read it's output. Receiver should also be able to detect when Sender has di... | I think you have a typo:
CreatePipe(&handles[h_Child_StdOut_Read], &handles[h_Child_StdOut_Write], &sa, 0);
SetHandleInformation(handles[h_Child_StdOut_Read], HANDLE_FLAG_INHERIT, 0);
CreatePipe(&handles[h_Child_StdIn_Read], &handles[h_Child_StdIn_Write], &sa, 0);
SetHandleInformation(handles[h_Child_StdIn_Read], HANDL... |
3,661,143 | 3,661,234 | char* or wchar_t* to textbox | char* cbuffer;
wchar_t* wbuffer;
cbuffer = _getcwd(NULL, 0);
wbuffer = _wgetcwd(NULL, 0);
Also, I have textbox1 and textbox2. How can I put cbuffer in textbox1 and wbuffer in textbox2. Thanks.
| You have to convert the C++ string to CTS (Common Type System) System.String used by .NET.
See this
|
3,661,285 | 3,661,438 | How to iterate through a fd_set | I'm wondering if there's an easy way to iterate through a fd_set? The reason I want to do this is to not having to loop through all connected sockets, since select() alters these fd_sets to only include the ones I'm interested about. I also know that using an implementation of a type that is not meant to be directly ac... | Select sets the bit corresponding to the file descriptor in the set, so, you need-not iterate through all the fds if you are interested in only a few (and can ignore others) just test only those file-descriptors for which you are interested.
if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) {
perror("select");... |
3,662,097 | 3,662,124 | Getting PTK Test Running | PTK is a 2d c++ framework for developing iphone apps on windows/mac. I followed the tutorial to set up a test app here: http://www.phelios.com/ptk/tuto1/
But I get the error
LNK1104: cannot open file 'dxguid.lib'
I am using Microsoft Visual C++ Express 2010
My Project Properties/Linker/Input/Additional Dependancies is ... | Check the library paths in project properties (Project Properties/Linker/General/Additional Library Directories). You probably miss the path that contains the dxguid.lib.
|
3,662,119 | 3,662,226 | C++ accessing variables from .CPP files | I'm a little fuzzy on how variable access between .cpp files works. For instance:
main.cpp
int main()
{
int a = i;
return 0;
}
main2.cpp
int i;
This generates a compiler error on main.cpp, telling me there is no in i in existence. What difference then, does the "static" keyword do in this context? (I tried Go... | In your first example, main2.cpp defines a global variable i, which could have been accessed by main.cpp if an extern declaration of i had appeared in that file. (Normally that extern declaration would come from a header file.) You got a compiler error because i had never been declared in main.cpp, which means the co... |
3,662,192 | 3,662,454 | Disable MessageBeep on Invalid Syskeypress | Simple problem, normally a program will produce a MessageBeep if the user presses Alt+Whatever and there's no hotkey associated with it. What API functions can I call to avoid this?
Handling WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN, and WM_SYSKEYUP all with return 0; on my main WndProc does not work.
| WM_MENUCHAR should be what your looking for. MSDN search is you friend (>message beep shortcut< or >message beep accelerator<).
http://msdn.microsoft.com/en-us/library/ms646349(VS.85).aspx
Edit: seems to be only for active menus.
Edit 2: works like a charm. note MSDN:
An application that processes this message shou... |
3,662,410 | 3,662,447 | create my own programming language |
Possible Duplicates:
References Needed for Implementing an Interpreter in C/C++
How to create a language these days?
Learning to write a compiler
I know some c++, VERY good at php, pro at css html, okay at javascript. So I was thinking of how was c++ created I mean how can computer understand what codes mean? How ca... | If you're interested in compiler design ("how can computer understand what codes mean"), I highly recommend Dragon Book. I used it while in college and went as far as to create programming language myself.
|
3,662,450 | 3,662,492 | C++, default parameter with no default constructor | what does standard say about such case:
template<class C>
struct A {
A(C c = C());
};
struct C {
C(int);
};
A<C> a(C(1));
btw, Comeau does not raise error.
| If you don't use the default argument (that is, you supply a value), then it is not instantiated at all.
14.7.1/2:
Unless a function template
specialization has been explicitly
instantiated or explicitly
specialized, the func- tion template
specialization is implicitly
instantiated when the specialization
... |
3,662,654 | 3,662,908 | conditional debug output class with templated operator<< | I'm trying to create a simple qDebug-like class I can use to output debug messages in debug mode, dependant on some debug level passed when calling the app. I liked the ease of use of the QDebug class (which could be used as a std::cerr and would disappear when compiling in release mode). I have this so far:
#ifdef DEB... | Your nullstream class has no integral constructor. This means that when you #define Debug nullstream, the compiler can't recognize Debug(0) - that makes no sense. Debug is not a macro that takes arguments, and if you substitute with nullstream, nullstream has no constructor that takes arguments. #define used this way i... |
3,662,899 | 3,662,918 | understanding the dangers of sprintf(...) | OWASP says:
"C library functions such as strcpy
(), strcat (), sprintf () and vsprintf
() operate on null terminated strings
and perform no bounds checking."
sprintf writes formatted data to string
int sprintf ( char * str, const char * format, ... );
Example:
sprintf(str, "%s", message); // assume declarat... | You're correct on both problems, though they're really both the same problem (which is accessing data beyond the boundaries of an array).
A solution to your first problem is to instead use std::snprintf, which accepts a buffer size as an argument.
A solution to your second problem is to give a maximum length argument t... |
3,663,004 | 3,663,102 | Optimizing SphereInFrustrum check | I have this SphereInFrustrum function here:
0.49% int FrustumG::sphereInFrustum(Vec3 &p, float radius) {
int result = INSIDE;
float distance;
2.40% for(int i=0; i < 6; i++) {
7.94% distance = pl[i].distance(p);
12.21% if (distance < -radius)
0.67% return OUTSIDE;
3.67% el... | I wanted to just leave a comment to ask a question but i only seem to be able to leave an answer, this is just an observation:
Does this code really do what you want to do?
int result = INSIDE;
float distance;
2.40% for(int i=0; i < 6; i++) {
7.94% distance = pl[i].distance(p);
12.21% if (... |
3,663,203 | 3,663,214 | How does this address (0x00000400) = 1024 | Im working in C++ and I have a #define VAL 0x00000400. when I set a variable equal to the define: int value = VAL; when I run through the debugger is shows the variable value = 1024. could someone explain how that turns into 1024? Maybe some links to memory address info, #define info, or something relevant.
| 0x00000400 is base 16 for 1024. Your debugger is showing you the integer value in base 10.
|
3,663,316 | 3,663,388 | Setting a nested array in c++ | I'm new to C++, and I have a question that should be easy, but it's making me crazy. I'm trying to set up a 2D array. The array is declared in Solver.h like so:
protected:
static const int gridSize = 9;
int theGrid[gridSize][gridSize]
int *boxes[gridSize][gridSize];
...
and I'm trying to initialize it in ... | The problem is that { ... } is not an expression, it is an initializer. Some compilers have an extension to allow expressions to be formed using {}, and C++0x adds several new meanings to the braces, but I'm going to keep this to standard C++.
I think the best general solution is to code a loop. You don't really want t... |
3,663,405 | 3,663,566 | Adding distant fog with OpenGL? | I'm using GL_FOG, but it only fogs up my geometry. I would like to find a way for the fog to feel like it encumbers an area, not just fog up my geometry, sort of like a box of fog...
Is there a way to do this? Or possibly another way to give a smooth draw distance transition?
| If you have a skybox/sphere you can apply the fog to that, the only downside is that it will be there if you look straight up as well.
Your best bet is to dive into shaders as Jerry mentioned. Don't worry though they aren't that bad to work with. If you apply the fog to the scene based on distance AND vertical posi... |
3,663,506 | 3,663,534 | Why is the copy constructor not called? | class MyClass
{
public:
~MyClass() {}
MyClass():x(0), y(0){} //default constructor
MyClass(int X, int Y):x(X), y(Y){} //user-defined constructor
MyClass(const MyClass& tempObj):x(tempObj.x), y(tempObj.y){} //copy constructor
private:
int x; int y;
};
int main()
{
MyClass MyObj(MyClass(1, 2)); //user-defin... | Whenever a temporary object is created for the sole purpose of being copied and subsequently destroyed, the compiler is allowed to remove the temporary object entirely and construct the result directly in the recipient (i.e. directly in the object that is supposed to receive the copy). In your case
MyClass MyObj(MyClas... |
3,663,599 | 3,663,634 | Making MSVC compiler GCC complient? | Is there a way to make the msvc compiler as strict as gcc? MSVC lets me do some pretty crazy things that result in hundreds of errors when I compile in linux.
Thanks
| To get started we'd need the version you are on (for MSVC), what sort of errors you hit (compile time, link time or run time) and so on.
Assuming you are on a relatively current version (MSVC 2008 SP1) and being bugged by compiler errors, I'd suggest the following:
Your program's entry point is called main and not _tm... |
3,663,709 | 3,663,761 | How to add a parameter to a formatted string function call via a #define function | I want to create macros that will insert a parameter into a function call. For example, I have function Action() declared below. Action takes as it's inputs an enum for the state number and a formatted string with optional args for the string.
I want to define macros so that instead of callingAction( ActionState1, "... | I believe that __VA_ARGS__ is what you're looking for:
#define State1(formattedString, ...) Action(1, (formattedString), __VA_ARGS__)
.
.
.
This is a C99 feature, and Wikipedia claims that they are not part of any official C++ standard (I note this because you use the C++ tag), but a fairly popular extension. There... |
3,663,711 | 3,664,435 | Help with this issue | Here is my issue. I'm rendering axis alligned cubes that are all the same size. I created an algorithm that rendered around the player like this:
******
******
***p**
******
******
While this does work, the player does not see this whole radius.
I know the player's rotation angle on the Y, so I was hoping to modify my... | After looking at your code again, maybe this is your problem:
PlayerPosition.x += 70.0f * float(sin(yrotrad));
PlayerPosition.y -= 20;
PlayerPosition.z += 70.0f * -(float(cos(yrotrad)));
and what types are the coordinates?
|
3,663,754 | 3,663,813 | How is compiling c++/c#/java different? | I'm trying to understand how these languages work under the hood. Unfortunately I only ever read very superficial things.
I'll summarize what I know already, I would be really happy if you could correct me, and most of all, help me enhance my little bits of half-knowledge.
C++:
The C++ compiler preprocesses all source... | The compilation of unmanaged C++ is very different from the compilation of managed C++, C# and Java.
Unmanaged C++
Unmanaged C++ (“traditional” C++) is compiled directly into machine code. The programmer invokes a compiler that targets a specific platform (processor and operating system), and the compiler outputs an ex... |
3,663,755 | 3,665,240 | How do I properly shut down an IOCP server? | I can find tonnes of article's about starting up an IOCP server, but none about properly shutting it down =/
What is the proper way to shut the server down when you are done? more specifically, I already use PostQueuedCompletionStatus() to tell the worker threads to quit, but don't I also need to cancel all the pending... | If you loop through all of the open connections and shut down all of the sockets then all of the pending I/O will complete on its own and the server will shut down. You can either close with a lingering close to allow any pending write data to complete or you can turn linger off on the sockets and cause pending write d... |
3,664,016 | 3,664,049 | What languages are good for writing a web crawler? | I have substantial PHP experience, although I realize that PHP probably isn't the best language for a large-scale web crawler because a process can't run indefinitely. What languages do people suggest?
| C++ - if you know what you're doing. You will not need a web server and a web application, because a web crawler is just a client, after all.
|
3,664,145 | 3,664,190 | Is there any need to assign null pointer to std::auto_ptr | Previous, I have the following code.
double* a[100];
for (int i = 0; i < 100; i++) {
// Initialize.
a[i] = 0;
}
The purpose of initialize array of a to 0 is that, when I iterative delete element of a, everything will work fine still even there are no memory allocated still for element of a.
for (int i = 0; i <... | The C++03 specifies the constructor of auto_ptr as follows:
explicit auto_ptr(X* p =0) throw(); // Note the default argument
Postconditions: *this holds the pointer p.
This means that the below is perfectly well-formed. There is no need to initialize
auto_ptr<int> a = auto_ptr<int>();
|
3,664,157 | 3,664,277 | Efficiency between select() and recv with MSG_PEEK. Asynchronous | I would like to know what would be most efficient when checking for incoming data (asynchronously). Let's say I have 500 connections. I have 3 scenarios (that I can think of):
Using select() to check FD_SETSIZE sockets at a time, then iterating over all of them to receive the data. (Wouldn't this require two calls to ... |
...most efficient when checking for
incoming data (asynchronously). Let's
say I have 500 connections. I have 3
scenarios (that I can think of):
Using select() to check FD_SETSIZE
sockets at a time, then iterating over
all of them to receive the data.
(Wouldn't this require two calls to
recv for each sock... |
3,664,272 | 3,664,349 | Is std::vector so much slower than plain arrays? | I've always thought it's the general wisdom that std::vector is "implemented as an array," blah blah blah. Today I went down and tested it, and it seems to be not so:
Here's some test results:
UseArray completed in 2.619 seconds
UseVector completed in 9.284 seconds
UseVectorPushBack completed in 14.669 seconds
The whol... | Using the following:
g++ -O3 Time.cpp -I <MyBoost>
./a.out
UseArray completed in 2.196 seconds
UseVector completed in 4.412 seconds
UseVectorPushBack completed in 8.017 seconds
The whole thing completed in 14.626 seconds
So array is twice as quick as vector.
But after looking at the code in more detail t... |
3,664,295 | 3,664,594 | Two questions on main | A. Is the following attempt valid to define the entry point 'main' of a C++ standalone program?
namespace{
extern int main(){return 0;}
}
As far as I understand, it satisifies all the criteria about 'main' in the C++ standard (external linkage, available in global namespace because of the implicit using directive).
S... |
A. Is the following attempt valid to define the entry point 'main' of a C++ standalone program?
No. The C++ standard says "A program shall contain a global function called main" (§3.6.1/1). In your program, the main function is not in the global namespace; it is in an unnamed namespace.
The implicit using directi... |
3,664,348 | 3,664,384 | Calling a function with variable number of arguments with an array in C++ (like python's * operator) | I'm trying to write a v8 module in C++; there, the functions receive a variable number of arguments in an array. I want to take that array and call a function like gettext and printf that receives a formatted string and it's necessary args. The thing is, how can one take an array and send the elements as arguments to o... | Here's one way:
void foo(const char *firstArg, ...) {
va_list argList;
va_start(argList, firstArg);
vprintf(firstArg, argList);
va_end(argList);
}
Assuming that you're trying to do a printf. Basically, va_list is the key, and you can use it to either examine the arguments, or pass them to other funct... |
3,664,411 | 3,664,540 | Make C++ call the right template method in an un-ugly way | I'm cooking up a vector library and have hit a snag. I want to allow recursive vectors (i.e. vec<H,vec<W,T> >) so I'd like my "min" and other functions to be recursive as well. Here's what I have:
template<typename T>
inline T min(const T& k1, const T& k2) {
return k1 < k2 ? k1 : k2;
}
template<int N, typename T, type... | template<typename T1, **typename T2**>
inline T1 min(const T1& k1, **const T2&** k2) {
return k1 < k2 ? k1 : k2;
}
...
template<int N, typename T>
struct vec {
typedef container<N,T,vec_array<N,T> > t;
};
...
vec<2,float>::t v1,v2;
min(v1,v2);
That's what I finally did to get it to work.
The ambiguity w... |
3,664,755 | 3,665,792 | Initializing static members of a templated class | I'm trying to figure out why this example doesn't compile. My understanding is that if a static variable is not explicitly set then it defaults to 0. In the five examples below four of them behave as I would expect, but the one that's commented out won't compile.
#include <iostream>
class Foo
{
public:
static int ... | Under the rules of the current C++ standard, the specialisation template <> int Bar<2>::i; is only a declaration and never a definition.
To become a definition, you must specify an initialiser. (See clause 14.7.3/15)
Apart from that, you were missing one very common case: the definition of a non-specialised static memb... |
3,665,103 | 3,671,632 | Inserting an 'image' datatype value through SQL Query/C++ | In the application I develop, the database table having a column of 'image' datatype. Now I want to insert the values into that table directly from my program, which is in VC++ 6.0, using a direct ExecuteQuery() of INSERT(due to performance considerations). The image column is been mapped to the structurre of the follo... | If you can construct a hex representation of a string, this insert statement seems to work okay:
create table #test
(
value image
)
insert #test (value)
values (0x48656C6C6F207468657265)
But there may be size limitations (on the size of the query).
It would be really really useful to be able to use managed code... |
3,665,310 | 3,665,610 | How to write overload operators for STL containers and alogrithm functions? | For example, I want to write overload functions for set_difference which compares the type std::set<point>
class myIter : public std::iterator<std::input_iterator_tag, int> {
public:
myIter(int n) : num(n){}
myIter(const myIter & n) : num(n.num){}
int & operator *(){return num;}
myIter & operator ++(){+... | Firstly, std::set<point> requires that point is less-than-comparable. You can either define operator< for point, or provide a separate function object that does the comparison as the second template parameter std::set<point,MyCompare>.
Once you actually have your elements in the set, you can use set_difference. It's wo... |
3,665,314 | 3,666,010 | How to get disk usage statistics for remote network share? | If I have a network share say \\myfileserver\documents, can I find out programmatically how much disk space it is using (used/free space) using any API of some sort?
Please note it could be hosted by samba or it could be on a san storage device which means I won't be able to install anything on that machine to check th... | GetDiskFreeSpaceEx() explicitly documents how you need to pass a UNC path: include the trailing backslash.
|
3,665,332 | 3,665,545 | how do i prevent screen-savers and sleeps during my program execution? | In a c++ program run on Win7, is there a way to fake a mouse movement or something like that, just to keep the screen saver from starting and the system from going to sleep? I'm looking for the minimal approach and I prefer not to use .NET.
Thanks,
-nuun
| Don't mess with the screensaver settings, use SetThreadExecutionState. This is the API for informing windows on the fact that your application is active:
Enables an application to inform the
system that it is in use, thereby
preventing the system from entering
sleep or turning off the display while
the applica... |
3,665,390 | 3,665,476 | Question about C++ folder structure for header file | I'm quite new in C++ after few years in Java and eclipse, I got little bit confusing using code::blocks, no autogenerate setter/getter and also implement interface :D.
I wanna ask about code structure in code::blocks, I create new console application, my header will be put to Headers/include folder called Employee.h, t... | You need to add your include directory to your compiler's include path. This is going to be compiler-specific. e.g., if your structure is:
code
code/src
code/include
and you're running g++ from a terminal in the 'code' directory, you'd need to run (assuming your .cpp is Employee.cpp):
g++ -Iinclude src/Employee.cpp
... |
3,665,537 | 3,672,331 | How to find out cl.exe's built-in macros | Does anyone know how could I find out which are cl.exe's builtin/predefined macros?
For example for gcc the following command line will list all the compiler's builtin macros
gcc -dM -E - </dev/null
EDIT: I'm interested in a way similar to gcc's that is "ask the actual compiler".
Thanks
| This method does amount to asking the compiler for the list of predefined macros, but it uses undocumented features and provides only a partial list. I include it here for completeness.
The Microsoft C/C++ compiler allows an alternative compiler front-end to be invoked using the /B1 and /Bx command line switches for .c... |
3,665,574 | 3,665,592 | Only one evaluation guaranteed for std::min/std::max | Does the C++ standard guarantee that the call
c = std::min(f(x), g(x));
evaluates the functions f and g only once?
| Yes. Since std::min is a function, f(x) and g(x) will be evaluated only once. And returned values won't be copied. See the prototype of the function :
template<typename T>
const T& min ( const T& a, const T& b );
It is a clear difference with preprocessor-genuinely-defined min macro :
#define MIN(A,B) ((A)<(B))?(... |
3,665,722 | 3,665,890 | How to adjust \listing package width in Latex Editor (LEd) | I am trying to use the \listing package to include some .cpp files into my article.
I add:
\usepackage{listings}
And then I use \lstinputlisting[language=c++]{File.cpp}
The problem is that the width is not adjusted, so the code is cutted.
Which is the solution?
| You'll be looking for the setting breaklines set in \lstset like so:
\documentclass{article}
\usepackage{listings}
\begin{document}
\lstset{breaklines=true}
\lstinputlisting[language=c++]{File.cpp}
\end{document}
Now listings will try and break the lines neatly.
For more information about what can be set with \lstset,... |
3,665,736 | 3,665,994 | Regsvr32 crashes on Windows 7 | I have an x64 (64-bit) COM dll. When trying to register it with Regsvr32 on Windows 7 - Regsvr32 crashes.
Regsvr32 is run under cmd with administrative priviliges ("run as administrator"), I tried both 32 and 64bit cmd.exe and regsvr.exe, even two different PCs and it is always the same.
Debugging the crashed Regsvr32 ... | Most likely the implementation of DllRegisterServer() in that DLL crashes when compiled for 64 bit.
If you have the source code for the DLL your best bet is to debug the implementation code as it executes and resolve the root cause of the problem. This can be any error typically occurring when code is not written in bi... |
3,665,908 | 3,665,934 | what should i use with a c++ class, with or without "new"? | When should i use the pointer and when not?
Whats the better Way?
Must i delete the cat object of the pointer at the end of the programm?
Example:
cat piki;
piki.miao();
cat *piki2 = new cat();
piki2->miao();
| The piki object will be autodeleted when the current scope is closed.
piki2 must be explicitly deleted.
delete piki2;
|
3,666,004 | 3,666,932 | How can I extract double pairs from an std::string with Boost Spirit? | I want to parse a string with a sequence of double pairs into an std::map
with Boost Spirit.
I adapted the example from
http://svn.boost.org/svn/boost/trunk/libs/spirit/example/qi/key_value_sequence.cpp
but I have a problem with difining a proper qi::rule for key and value:
template <typename Iterator>
struct keys_and... | I am not sure why you can't use double() key and value when your output requirement is
map<double, double>.
As i understand the problem the below code should solve it.
template <typename Iterator>
struct keys_and_values : qi::grammar<Iterator, std::map<double, double>() >
{
keys_and_values()
: keys_... |
3,666,105 | 3,666,226 | How to find out where all a closed source application is writing to? | I have an application (the source for which I don't have), which can be invoked from command line like this
$ ./notmyapp
I want to know all the locations where the application is writing to. It outputs some files in the directory it is being called from, but I need to make sure that those are the only files that are c... | strace, ktrace/kdump, truss, dtruss, or whatever other program your platform provides for tracing system calls is probably what you're looking for.
Expect lots of output from any of those. To figure out what files the application is reading and writing to, you might want to limit the output to just a few syscalls. stra... |
3,666,199 | 3,666,265 | How do I correctly use a std::queue as a element in a template class? | I am reasonably new to C++ and have limited experience of templates. At the moment I am trying to implement a concurrent queue based on the example provided here. I am having problems compiling it and keep getting an error stating that "ISO C++ forbids declaration of ‘queue’ with no type" even after I stripped down the... | You are missing #include <queue> and #include<string> at the beginning of the file.
|
3,666,221 | 3,666,254 | Fibonacci extension in c++ segfaulting | I'm trying to add the extension to the Fibonacci numbers to take into account negative indexes.
The extension is Fib(-n) = (-n)^(n+1) * Fib(n)
I have attempted to implement this in c++ but I'm running into a problem and I'm not sure how to get around it.
#include <iostream>
#include <math.h>
int fib(int n) {
if (... | I guess that when u call fib(-2) it calls fib(2)
fib(2) calls fib(1) and fib(0)
fib(1) calls fib(0) and fib(-1)
fib(-1) calls fib(1) and this is never-ending loop
|
3,666,320 | 3,666,920 | In WinCE, CreateFile function: File open failed | I need to do file operations in WinCE in a Windows mobile 6 project in visual studio 2008.
For opening a file i did like below.
HANDLE hFile = CreateFile(__TEXT("\\1.txt"), GENERIC_READ ,
FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
But hFile is coming as 0xffffff... | My guess is that your file is not there.
In order to share a folder from your harddisk with the emulator, go to your emulator menu:
"File -> Configure ... -> General -> Shared folder:". This folder will be seen as "Storage Card".
Lets say you map d:\wm, then you put 1.txt in d:\wm, afterwards the file path for ::Create... |
3,666,387 | 3,666,949 | C++ priority_queue underlying vector container capacity resize | I'm using priority_queue with a vector as an underlying container. However I expect the size of the heap to be very large. I'm aware of problems with dynamic vector capacity resize. So I'm looking for ways to initially allocate enough space for the underlying vector in my priority_queue. Are there any suggestions out t... | stdlib container adaptors provide a "back door" to access the underlying container: the container is a protected member called c.
Therefore you can inherit from the adapter to gain access to the container:
#include <queue>
#include <iostream>
template <class T>
class reservable_priority_queue: public std::priority_que... |
3,666,394 | 3,667,116 | Image processing in languages other than c and matlab | It seems like most image processing apps are done using matlab or OpenCV using C++.
Are there any other languages providing good image processing libraries?? How do they compare to matlab and opencv?
When I say languages I mean something like Java , python or even perl!
| Image libraries exist for many languages
Lisp:
ch-image
http://cyrusharmon.org/static/projects/ch-image/doc/ch-image.xhtml
Java:
ImageJ
http://rsbweb.nih.gov/ij/
OpenCV Java
http://ubaa.net/shared/processing/opencv/
Python:
Python Imaging Library
http://www.pythonware.com/products/pil/
ImageMagick offers binding for... |
3,666,428 | 3,666,513 | C++ template "deferred instantiation" | What is meant with "deferred instantiation" in C++ templates?
| Deferred instantiation is when the template is not instantiated until the corresponding entity is used for the first time. For example, you have a templated function:
template<int Size>
void YourFunction()
{
//does something
}
parameter Size can have any possible value that int can have. Do you automatically have ... |
3,667,144 | 3,667,210 | Getting Access Denied While Accessing the Named Pipe from Another System | I have a Named Pipe and It Works Fine While I access it using a Client which runs on My System
The Client tries to open the File using following code:
LPTSTR lpszPipename = TEXT("\\\\smyServerName\\pipe\\iPipe01");
hPipe = CreateFile(
lpszPipename, // pipe name
GENERIC_READ | // read and... | First things first - check your permissions and firewall. Almost always, when something works locally but not on the network, it's permissions.
(Had this problem more times than I can count!)
|
3,667,317 | 3,667,738 | Best way to keep the user-interface up-to-date? | This question is a refinement of my question Different ways of observing data changes.
I still have a lot of classes in my C++ application, which are updated (or could be updated) frequently in complex mathematical routines and in complex pieces of business logic.
If I go for the 'observer' approach, and send out notif... | An approach I used was with a large windows app a few years back was to use WM_KICKIDLE. All things that are update-able utilise a abstract base class called IdleTarget. An IdleTargetManager then intercepts the KICKIDLE messages and calls the update on a list of registered clients. In your instance you could create ... |
3,667,339 | 3,667,418 | Qt Phonon MediaObject conversion error | I want to play some WAV files, but I have error C2664 in Visual Studio:
error C2664: 'Phonon::MediaObject::setCurrentSource' : conversion error from'const char [24]' to 'const Phonon::MediaSource &'
This is the code:
Phonon::MediaObject *media_object_;
media_object_ = new Phonon::MediaObject(this);
media_object_->set... | The setCurrentSource() function takes a MediaSource object by const-reference. There is no constructor for MediaSource that takes a const char * (a null terminated byte string). You will probably need to create a temporary object of QString with your path and pass it to a MediaSource (possibly temporary) and use it to ... |
3,667,580 | 3,667,616 | Can I detach a std::vector<char> from the data it contains? | I'm working with a function which yields some data as a std::vector<char> and another function (think of legacy APIs) which processes data and takes a const char *, size_t len. Is there any way to detach the data from the vector so that the vector can go out of scope before calling the processing function without copyi... | void f() {
char *buf = 0;
size_t len = 0;
std::vector<char> mybuffer; // exists if and only if there are buf and len exist
{
std::vector<char> data = generateSomeData();
mybuffer.swap(data); // swap without copy
buf = &mybuffer[0];
len = mybuffer.size();
}
// How can I ensu... |
3,667,659 | 3,690,517 | Compilation of large class hierarchy consumes lots of memory after adding boost::serialization | We needed serialization of quite large C++ class hierarchy with lots of inheritance, contraction, shared pointers, etc. I decided to use boost::serialization library.
My problem is that while compilation of this library on VS 2008 cl takes over 1 GB of RAM memory. I suppose this is caused by template-based serializatio... | I encountered the same problem when using boost::serialization. Probably the only workaround is to split up the huge class in more encapsulated pieces. For some classes in my code, I also wrote a layer between my application classes and the serializer. This layer simplified the structur of the data to be saved. It even... |
3,667,879 | 3,678,640 | Cost much memory when creating several vertex and index buffer | I met a very weird issue. When I create some very simple VertexBuffer and IndexBuffer in D3D, the memory consumption reported from TaskManager is huge.
I created 60000 index buffer via D3D CreateIndexBuffer method. Each index buffer contains 6 index (int) which represents two triangles. So, one index buffer will occupy... | 60000 index buffers? Why not just create 1 big index buffer? Switching all those index buffers will be slow as hell in itself.
On to the reason: There will be an overhead associated with every index buffer you create (Various bit of tracking information and bits of info the driver will use to optimise it) and 5K of... |
3,668,016 | 3,719,746 | Imap not downloading emails after certain date | I am working on Email client application.
I have written one sample program for downloading emails from Gmail account using IMAP client library, It downloads emails from AllMail folder.
Here I am facing very different problem. my sample application won’t download emails after certain date.
Actually I have created... | This may not actually be a date limitation but a mailbox size limitation. Double-check that your GMail IMAP settings for Folder Size Limits is set to "Do not limit...".
Also, above the IMAP settings, check the POP settings to see what date it has set for its limit (if any). I don't know if the two are tied together or ... |
3,668,070 | 3,668,466 | Drawing a cube with GlDrawElements()? | Is there a way to draw a cube like this and as a result, only upload 8 verticies and 24 indicies to the graphics card? If so how could this be done?
Thanks
I currently do it like this:
boxdims.x = w;
boxdims.y = h;
boxdims.z = d;
center = c;
GLfloat vboverticies[72];
GLfloat vbonormals[18];
Ver... | The answer is no.
If you need normals, you'll have to have 24 vertices, as no face shares normals. Note that the example provided by shk does not handle normals.
|
3,668,132 | 3,668,269 | Is there a style checker for c++? | I have worked with java for a while now, and I found checkstyle to be very useful. I am starting to work with c++ and I was wondering if there is a style checker with similar functionality. I am mainly looking for the ability to write customized checks.
| What about Vera++ ?
Vera++ is a programmable tool for verification, analysis and transformation of C++ source code.
Vera++ is mainly an engine that parses C++ source files and presents the result of this parsing to scripts in the form of various collections - the scripts are actually performing the requested tasks.
C... |
3,668,454 | 3,668,598 | Optimizing C++ code for performance | Can you think of some way to optimize this piece of code? It's meant to execute in an ARMv7 processor (Iphone 3GS):
4.0% inline float BoxIntegral(IplImage *img, int row, int col, int rows, int cols)
{
0.7% float *data = (float *) img->imageData;
1.4% int step = img->widthStep/sizeof(float);
// Th... | Specialize for the edges so that you don't need to check for them in every row and column. I assume that this call is in a nested loop and is called a lot. This function would become:
inline float BoxIntegralNonEdge(IplImage *img, int row, int col, int rows, int cols)
{
float *data = (float *) img->imageData;
in... |
3,668,481 | 3,668,493 | Parse this Expression ! | Can anyone parse this following expression for me
#define Mask(x) (*((int *)&(x)))
I applied the popular right-left rule to solve but cant.. :(
Thanks a bunch ahead :)
| This defines a macro Mask that interprets its argument as an int.
&(x) - address of x...
(int *)&(x) - ...interpreted as a pointer to int
*((int *)&(x)) - the value at that pointer
|
3,668,963 | 3,668,987 | C++ namespace inclusion in .cc files | I have declared a class X in X.h as follows:
namespace Foo {
class X{
....
};
}
In X.cc I would like to define the constructors, methods for X.
Do I need to enclose all my definitions inside namespace Foo {...}
or prefix X as Foo::X:: for every method ?
It seems that sometimes I can just say (using namespace Foo) an... | Any of the three approaches you suggest will work. Given:
namespace N {
struct S {
int F();
};
}
You can put the definition in a namespace block:
namespace N {
int S::f() { return 42; }
}
You can qualify the member name with the namespace name:
int N::S::f() { return 42; }
Or you can use a using... |
3,668,967 | 3,669,087 | C++ - function that returns object | // Assume class definition for Cat is here.
Cat makeCat() {
Cat lady = new Cat("fluffy");
return lady;
}
int main (...) {
Cat molly = makeCat();
molly->eatFood();
return 0;
}
Will there be a "use after free" error on molly->eatFood()?
| Corrected your program and created an example implementation of class Cat:
#include <iostream>
#include <string>
class Cat {
public:
Cat(const std::string& name_ = "Kitty")
: name(name_)
{
std::cout << "Cat " << name << " created." << std::endl;
}
~Cat(){
... |
3,669,034 | 3,669,101 | STL: convoluting two unary_function arguments | Working on Windows with VS2005 and struggling to understand the error messages I'm getting. If this question has been asked before, I'm sorry. I couldn't find it.
Class I'm testing:
#include <functional>
using std::unary_function;
template<typename F, typename G>
struct UnaryConvolution : unary_function<typename G::... | UnaryConvolution is a class template, not a class. You need to specify the template arguments with which to instantiate the template. For example,
UnaryConvolution<
function<bool(bool)>,
function<bool(int)>
> obj(bind2nd( equal_to<bool>(), true ), bind2nd( less<int>(), 5 ));
(I've used function, which you c... |
3,669,192 | 3,669,425 | Phonon audible output fail | This is my code:
media_object_ = new Phonon::MediaObject(this);
fileName="./DemoEN2.wav";
media_object_->setCurrentSource(fileName);
media_object_->play();
I have the includes:
#include <Phonon/MediaObject>
#include <Phonon/MediaSource>
#include <phonon>
And:
Phonon::MediaObject *media_object_;
QString fileName;
Whe... | You need to connect the media source to media output:
Phonon::MediaObject *media_object_;
Phonon::AudioOutput *audio_output_;
...
media_object_ = new Phonon::MediaObject(this);
fileName="./DemoEN2.wav";
media_object_->setCurrentSource(fileName);
audio_output_ = new Phonon::AudioOutput(Phonon::MusicCategory, this);
Ph... |
3,669,315 | 3,669,353 | Is there some ninja trick to make a variable constant after its declaration? | I know the answer is 99.99% no, but I figured it was worth a try, you never know.
void SomeFunction(int a)
{
// Here some processing happens on a, for example:
a *= 50;
a %= 10;
if(example())
a = 0;
// From this point on I want to make "a" const; I don't want to allow
// any code past thi... | One solution would be to factor all of the mutation code into a lambda expression. Do all of the mutation in the lambda expression and assign the result out to a const int in the method scope. For example
void SomeFunction(const int p1) {
auto calcA = [&]() {
int a = p1;
a *= 50;
a %= 10;
if(exampl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.