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
2,369,676
2,369,700
C++ program gets undefined reference to a dynamic C library during linking
I've created a dynamic networking library in C. When I try to link it in my C++ program I get an undefined reference the first time I call one of my functions in the library. What I can't understand is that I created a little test program in C that uses the library and it links just fine. Could someone help with my pro...
C library functions must have en extern "C" definition in order to call them from C++ to turn of name-mangeling. extern "C" { int test(); } With the extern , the the Microsoft C++ compiler will look for the symbol "_test", otherwise it will look for "?test@@YAHXZ" (The C++ name-mangeled version of int test() )
2,369,761
2,369,835
find the position of a string in another string
Possible Duplicate: substring algorithm Given two strings, A and B, how to find the first position of B in A? For instance, A = " ab123cdefgcde"; B= "cde" Then the first position of B in A is 5. Is there any trick to solve this problem or just search A from the start?
The problem that you are solving is the "exact string matching" problem. The naive solution runs in O(n^2) time, but you can do much better than that. Some linear-time algorithms to solve this problem are Knuth-Morris-Pratt (KMP), Boyer-Moore, and Apostolico-Giancarlo. Another way to solve it is by constructing a finit...
2,369,802
2,370,154
How do I include bitmaps on items I've added to the end of a context menu?
I'm currently writing a Windows Explorer Shell Extension. Everything is ok so far but I'm having trouble to insert menu items WITH MenuItemBitmaps at the end of the context menu. Here is the code I used without the bitmaps: HRESULT CSimpleShlExt::QueryContextMenu(HMENU hmenu, UINT /*uMenuIndex*/, UINT uidFirstCmd, UINT...
The documentation for SetMenuItemBitmaps says nothing about accepting -1 as a valid position like InsertMenu does. You know the command IDs of the items you've added, and you know they're unique, so add the bitmaps by command instead of by position. InsertMenu(hmenu, -1, MF_STRING | MF_BYPOSITION, uidFirstCmd, _T("Simp...
2,369,806
2,420,366
Simulating mouse clicks on Mac OS X does not work for some applications
I'm writing an application for Mac OS X 10.6 and later in C++. One part of the application needs to simulate mouse movement and mouse clicks. I do this currently by posting CGEvent objects using CGEventPost(kCGHIDEventTap, event);. This works, for the most part - I can simulate mouse movement and clicks just fine, but ...
What you need to do to convince these applications that you have in fact generated a click is to explicitly set the value of the "click state" field on the mouse up event to 1 (it defaults to 0). The following code will do it: CGEventSetIntegerValueField(event, kCGMouseEventClickState, 1); It also has to be set to 1 f...
2,369,976
2,504,035
is it safe to to destroy a socket object while an asyn_read might be going on in boost.ASIO?
In the following code: tcp::socket socket(io_service); tcp::endpoint ep(boost::asio::ip::address::from_string(addr), i); socket.async_connect(ep, &connect_handler); socket.close(); is it correct to close the socket object, or should I close it only in the connect_handler(), resort to shared_ptr to prolong the life...
Closing the socket isn't much of an issue, but the socket being destructed and deallocated is. One way to deal with it is to just make sure the socket outlives the io_service where work is being done. In other words, you just make sure to not delete it until after the io_service has exited. Obviously this won't work...
2,370,090
2,370,428
Protobuf-net - serializing .NET GUID - how to read this in C++?
I have serialized an object using Protobuf-net , in my .NET application, with relative ease. I also get the .proto file that protobuf-net generated, using GetProto() command. In the .NET generated .proto file, my GUID fields get a type of "bcl.guid". Now I wish to compile the .proto file in C++ so I can deserialize the...
protobuf-net encodes this as a pair of fixed-length 64 bit values at fields 1 and 2. I haven't tried it for interop purposes, but you could try importing the (bespoke) bcl.proto (I think this is in the deployment folder; if not let me know and I'll add it; otherwise it is in the trunk). But conceptually it is just: mes...
2,370,132
2,370,167
filling an array with random number
I'm trying to fill an array of 20 ints with numbers from 1-20 in random sequence. here's my code: int lookup[20]={0}; int array[20]={0}; srand(time(NULL)); for(int i=0;i<20;++i){ bool done=false; while(!done){ int n=rand()%20; if(lookup[n]==0){ array[i]=n; lookup[n]=1; ...
You could fill the array in sequence and then shuffle it. That would prevent having to ever do more than 20 random number generations. Fisher-Yates shuffle: can be done in O(n) time. From wikipedia: Properly implemented, the Fisher–Yates shuffle is unbiased, so that every permutation is equally likely. The modern vers...
2,370,513
2,370,578
How to get instance of nested class in C++
I have the following code: class outer { struct inner { int var1; int var2; inner() { var1 = 1; var2 = 2; } }; inner inner_instance; public: const inner *get_inner() { return &inner_instance; } }; int main(int argc, char *argv[]) { // 1 outer outer_instance; co...
Put the struct inner definition in the public if you want to use it outside outer class. class outer { public: struct inner { int var1; int var2; inner() { var1 = 1; var2 = 2; } }; private: inner inner_instance; public: const inner *get_inner() { return &inner_instance; } }; ...
2,370,557
2,371,708
How to hide completely a QGridLayout?
I have a button followed by a QGridLayout full of widgets. I want to show/hide QGridLayout at every button click, but reading documentation of QGridLayout I see there's no show()/hide() implementation, also no setVisible() method available. How do I achieve this?
You didn't mention which version of Qt you're using. (I'm looking at the 4.4 documentation.) I haven't tried this, but here are two ideas: QGridLayout inherits the function QLayoutItem::widget(). If your layout is a widget, this will return a QWidget* on which you can call show() or hide(). If your QGridLayout is no...
2,370,611
2,370,739
Does splitting C++ code into multiple translation units introduce overhead on the executable size?
I have some code shared among multiple projects in a static library. Even with function-level linking I get more object code than I'd like to in the output - see another question about that. Surely the most straightforward solution to decreasing the amount of object code linked into the final executable would be to sp...
Things which are more likely to affect your final EXE size (not exhaustive list): Whether you static or dynamically link to libraries (dynamic link is smaller since the library code is not inside your EXE) It's possible use of many template classes eg. vector<A>, vector<B>, vector<C> will cause code bloat, since each ...
2,370,986
2,371,023
What does returning zero by convention mean?
This is likely a stupid question but I always find myself wondering which is the standard. In most (not to say all) C++ first examples you may see the main function returning 0 value. This means the operation went ok or not? 0 --> OK 1 --> No OK. Other --> ? Which is the standard way of doing it? By the way, is it ...
0 or EXIT_SUCCESS means success. EXIT_FAILURE means failure. Any other value is implementation defined, and is not guaranteed to be supported. In particular, std::exit(1) or return 1; are not actually guaranteed to indicate failure, although on most common systems they will. EXIT_SUCCESS and EXIT_FAILURE are defined in...
2,371,123
2,387,752
Get output of CMD line program from C++ (specifically netstat)
I want to be able to run "netstat -n" and grab the output somehow so I can then write it out to another file. How can I do this in C++ on Windows CE Thankyou Chris
I solved this by essentially calling netstat from the cmd prompt, piping the output to a file, and then using it from there. I believe Kerido's answer to be right but this is how I got it working. This code then launches cmd.exe and telling it to run netstat -n. Note that the /c is required else cmd.exe will not laun...
2,371,176
2,371,324
C++ private virtual inheritance problem
In the following code, it seems class C does not have access to A's constructor, which is required because of the virtual inheritance. Yet, the code still compiles and runs. Why does it work? class A {}; class B: private virtual A {}; class C: public B {}; int main() { C c; return 0; } Moreover, if I remove t...
According to C++ Core Issue #7 class with a virtual private base can't be derived from. This is a bug in compiler.
2,371,433
2,371,535
How to get the pointer to a shared_ptr?
I am now hacking an old C code, try to make it more C++/Boost style: there is a resource allocation function looks like: my_src_type* src; my_src_create(&src, ctx, topic, handle_src_event, NULL, NULL); i try to wrap src by a shared_ptr: shared_ptr<my_src_type> pSrc; I forgot to mention just now. I need to do this as ...
No. Basically, you have to do it the old C way and then convert the result to a shared_pointer somehow. You can do it by simply initializing the shared_pointer my_src_type* pSrc; my_src_create(&src, ctx, topic, handle_src_event, NULL, NULL); shared_ptr<my_src_type> sp(pSrc); but beware, this will fail if the my_src_cr...
2,371,560
2,371,613
What is the easiest way to insert Data into a mysql DB with C++?
Do i need external libraries ? is there any minimalistic example ?
The easiest way is to use the C API which is usually installed along with the MySQL Server. On Windows, for example, it's in "C:\Program Files\MySQL\MySQL Server 5.0" (see "include" and "lib" directory). If you are looking for examples that demonstrate how to use the C API, take a look at these clients. You can find t...
2,371,668
2,371,698
Is returning a string literal address from a function safe and portable?
I need a function to return a string that will only be accessed read-only. The string contents is known at compile time so that I will use a string literal anyway. I can return something like std::string: std::string myFunction() { return "string"; } or return const char*: const char* myFunction() { return "stri...
Is the second alternative safe and portable in this scenario? Yes! The storage allocation of string literals is static and they persist for the lifetime of the application.
2,371,833
2,371,916
binary_search, find_if and <functional>
std::find_if takes a predicate in one of it's overloaded function. Binders make it possible to write EqualityComparators for user-defined types and use them either for dynamic comparison or static comparison. In contrast the binary search functions of the standard library take a comparator and a const T& to the value t...
A single-argument predicate version of std::binary_search wouldn't be able to complete in O(log n) time. Consider the old game "guess the letter I'm thinking of". You could ask: "Is it A?" "Is it B?".. and so on until you reached the letter. That's a linear, or O(n), algorithm. But smarter would be to ask "Is it before...
2,371,897
2,371,915
Weird problem porting application. Undefined reference errors in standard libraries
I've recently been trying to port a C++ application. I believe I have all of it's dependencies and such and it all compiles. But then, when it goes to link it I get a lot of weird undefined reference errors. /usr/local/lib/libglibmm-2.4.so.7.0: undefined reference to `std::basic_istream<char, std::char_traits<char> >:...
Use g++ to link C++ applications, that add C++ standard libraries to the link phase.
2,372,014
2,387,003
llvm clang 2.6: "not using the clang compiler for C++ inputs "
LLVM 2.6 + clang. Trying to compile C++ file and got: clang: warning: not using the clang compiler for C++ inputs How can I start clang in C++ mode?
I would get the trunk code. C++ support has been much improved since 2.6. The clang driver Makefile in tools/clang/tools/driver uses the CLANG_IS_PRODUCTION define to control whether C++ is on or off. CLANG_IS_PRODUCTION means C++ off. The default for a trunk build is no CLANG_IS_PRODUCTION (i.e. a development build).
2,372,027
2,372,071
Compiler complains about BOOST_CHECK_THROW on constructor
The following does not compile: class Foo { public: Foo( boost::shared_ptr< Bar > arg ); }; // in test-case boost::shared_ptr< Bar > bar; BOOST_CHECK_THROW( Foo( bar ), std::logic_error ); // compiler error here The implementation of Bar does not matter. The compiler complains, that Foo does not have an appropr...
This occurs because BOOST_CHECK_THROW is a macro, and Foo(bar) is being expanded to a statement. The compiler sees this statement and interprets it as a variable declaration Foo bar; which requires a default constructor. The solution is to give the variable a name: BOOST_CHECK_THROW( Foo temp( bar ), std::logic_error )...
2,372,272
2,381,671
Qt4: Locking the mouse cursor in place while manipulating QGraphicsItem
I'm writing a little GUI utility in Qt4 which uses a QGraphicsScene. One of the items tracks the mouse in the horizontal plane as you move it around, and holding down a modifier key allows you to change the item's rotation. When rotating items I'd like the mouse cursor to change to a curvy arrow (or something) and lo...
How about using an event filter to catch QMouseEvents, while this is going on?
2,372,291
2,372,354
how failed constructor roll over to destroy the completed objects?
I know that when a constructor fails, the completed member objects will be destroyed. There is no memory leak. My question is that how does compiler do that? How can compiler know what member is constructed? Does it make any record of it? Does the compiler really destroy everything in this case? How does it guarantee t...
How the compiler does that is up to the compiler. But yes, you are guaranteed that any constructed objects will be destructed (in the reverse order they were constructed). §15.2/2: An object that is partially constructed or partially destroyed will have destructors executed for all of its fully constructed subobjects,...
2,372,315
2,372,368
How to implement strlen as fast as possible
Assume that you're working a x86 32-bits system. Your task is to implement the strlen as fast as possible. There're two problems you've to take care: 1. address alignment. 2. read memory with machine word length(4 bytes). It's not hard to find the first alignment address in the given string. Then we can read memory on...
First CRT's one is written directly in assembler. you can see it's source code here C:\Program Files\Microsoft Visual Studio 9.0\VC\crt\src\intel\strlen.asm (this is for VS 2008)
2,372,339
2,372,367
Why do we follow opposite conventions while returning from main()?
I have gone through this and this, but the question I am asking here is that why is 0 considered a Success? We always associate 0 with false, don't we?
Because there are more fail cases than success cases. Usually, there is only one reason we succeed (because we're successful :)), but there are a whole lot of reasons why we could fail. So 0 means success, and everything else means failure, and the value could be used to report the reason. For functions in your code,...
2,372,459
2,372,540
Checking return value of a C++ executable through shell script
I am running a shell script on windows with cygwin in which I execute a program multiple times with different arguments each time. Sometimes, the program generates segmentation fault for some input arguments. I want to generate a text file in which the shell script can write for which of the inputs, the program failed....
You can test the return value using shell's if command: if program; then echo Success else echo Fail fi or by using "and" or "or" lists to do extra commands only if yours succeeds or failed: program && echo Success program || echo Fail Note that the test succeeds if the program returns 0 for success, which is...
2,372,468
2,372,638
Triple checked locking?
So in the meanwhile we know that double-checked-locking as is does not work in C++, at least not in a portable manner. I just realised I have a fragile implementation in a lazy-quadtree that I use for a terrain ray tracer. So I tried to find a way to still use lazy initialization in a safe manner, as I wouldn't like to...
It seems that your pattern is not correct. Consider the case when thread #1 executes till after the first #pragma flush. Then the control switches to the thread #2, which goes on and creates a c, the control is taken back just before second #pragma flush. Now the first thread wakes up, and creates the child anew. Edit:...
2,372,491
2,372,504
insert object into a set
I want to insert a vector into a set like this: set<vector<prmEdge> > cammini; vector<prmEdge> vecEdge; cammini.insert(vecEdge); I have a compilation error like this: prmPlanner.cpp:1285: instantiated from here /usr/include/c++/4.2/bits/stl_algobase.h:853: error: no match for ‘operator<’ in ‘__first1.__gnu_cxx::__no...
It doesn't know how to compare vectors. You should supply operator< for vector<prmEdge> (or for prmEdge to automatically use std::lexicographical_compare for vectors) or use unordered_set if you don't actually need sorted set of vectors.
2,372,529
2,373,143
What causes name collision in an IDL file?
We have an idl file with multiple interfaces defined, two of which have someting like this: [ object, uuid(79E24BAA-DC12-4caf-91DD-2A4D47FED30A), helpstring("ISomeInterface Interface"), pointer_default(unique) ] interface ISomeInterface: IUnknown { [propget, id(2)] HRESULT SOMEMethod([out,...
Psychic debugging powerz tells me that you are using the type library in a managed project. The .NET type library importer (Tlbimp.exe) has an obscure bug, it improperly capitalizes a method or property name if it appears more than once in the library. It uses the capitalization of the first one it encounters. The fi...
2,372,543
2,372,570
Determining the correct size for a C++ array
I need to be able to set the size of an array based on the number of bytes in a file. For example, I want to do this: // Obtain the file size. fseek (fp, 0, SEEK_END); size_t file_size = ftell(fp); rewind(fp); // Create the buffer to hold the file contents. char buff[file_size]; However, I get a compi...
Use a vector. std::vector<char> buff(file_size); The entire vector is filled with '\0' first, automatically. But the performance "lost" might not be noticable. It's certainly safer and more comfortable. Then access it like a usual array. You may even pass the pointer to the data to legacy C functions legacy(&buff[0])...
2,372,644
2,372,737
How much can this c/c++ loop be optimized?
I am a newbie on optimization. I have been reading some reference on how to optimize c++ code but I have a hard time applying it to real code. Therefore I just want to gather some real world optimization technique on how to squeeze as much juice from the CPU/Memory as possible from the loop below double sum = 0, *array...
Since sum depends on its previous values in a non-trivial way, it is impossible to parallelize the code (so OpenMP and MPI are out). Memory alignment and SSE should be enforced/used automatically with appropriate compiler settings. Besides inlining fun and unrolling the loop (by compiling in -O3) there is not much we c...
2,372,671
2,372,781
How would I import a function template using PInvoke?
In my C# code, I need to call a function from a C++ Dll that I wrote.The function is generic. So , should I just import it like this: [DllImport("myDll.dll")] private static extern TypeName functionName<TypeName>( int arg1, int arg2 ); Is this correct syntax? Thanks.
This cannot work, there is no main-stream C++ compiler that makes templates exportable. Furthermore, templates are instantiated by the C++ compiler through type erasure, similar to the way Java generics works. In other words, the concrete callable functions have to be embedded in the DLL by the C++ compiler. They ar...
2,372,714
2,372,730
local variables of static member functions
Today we came accross a problem concerning static member functions in an multithreaded environment. The question we asked ourselves and couldn't find a satisfying answer is: are local varialbes of static member functions static as well? // header class A { static int test(); } // implementation int A::test() { in...
No. The stack frames are independent for each thread's invocation of the function, and each gets its own locals. (You do need to be careful if you're accessing actual shared data e.g. static members in the class.)
2,372,780
2,372,820
Memory Freeing Inqury
Additional thanks extend to Daniel Newby for answering my memory usage question (and Martin York for explaining it a bit more). It is definitely the answer I was looking for, but more of my other questions were answered by others. Thanks everyone for clearing up all of my concerns. Very pleased to see things running ho...
There's rarely a reason to use malloc() and free() in a C++ program. Stick with new and delete. Note that unlike languages with garbage collection, setting a pointer to NULL or 0 in C++ has nothing to do with deallocating the memory.
2,372,926
2,373,040
Locating what lib is linking to the debug CRT
We link our app with numerous different static libs, the problem is that one of these libs is in turn linking with the VC90.DebugCRT even in release. Some libs we don't even have the source to, so it would be nice if there's a way to locate what lib is the actual culprit. I've toyed around some with dumpbin, but am una...
The linker's /verbose:lib can help. Recompile your entire solution with this option set under Project>Properties>Linker>Command Line and look through the log to see who links with who.
2,372,962
2,373,103
Storing vector in a struct C++
Why can't I do this: struct sName { vector<int> x; }; It takes only three pointers to store a vector, so I should be able to do this?
You mentioned this failed in a switch statement. You'll need to wrap it up in an extra pair of braces: int type = UNKNOWN; switch(type) { case UNKNOWN: cout << "try again" << endl; break; case KNOWN: { // Note the extra braces here... struct sName { vector<int> x; } myVector; } // a...
2,373,094
2,373,162
Loading large multi-sample audio files into memory for playback - how to avoid temporary freezing
I am writing an application needs to use large audio multi-samples, usually around 50 mb in size. One file contains approximately 80 individual short sound recordings, which can get played back by my application at any time. For this reason all the audio data gets loaded into memory for quick access. However, when load...
I like solution 1 as a first attempt -- simple & to the point. If you are under Windows, you can do asynchronous file operations -- what they call OVERLAPPED -- to tell the OS to load a file & let you know when it's ready.
2,373,183
2,373,256
is there a new equalivant of _malloca
I am a big fan of the _malloca but I can't use it with classes. Is there a stack based dynamic allocation method for classes. Is this a bad idea, another vestige of c which should ideologically be opposed or just continue to use it for limited purposes.
You can use _malloca with classes by allocating the memory (with _malloca) then constructing the class using placement new. void* stackMemory = _malloca(sizeof(MyClass)); if( stackMemory ) { MyClass* myClass = new(stackMemory) MyClass(args); myClass->~MyClass(); } Whether you should do this is another matter...
2,373,207
2,373,299
Am I using delete correctly here?
I've just started combining my knowledge of C++ classes and dynamic arrays. I was given the advice that "any time I use the new operator" I should delete. I also know how destructors work, so I think this code is correct: main.cpp ... int main() { PicLib *lib = new PicLib; beginStorage(lib); return 0; } ...
There are a couple of problems: int main() { PicLib *lib = new PicLib; beginStorage(lib); return 0; } It is best to allocate and delete memory in the same scope so that it is easy to spot. But in this case just declare it locally (and pass by reference): int main() { PicLib lib; beginStorage(lib...
2,373,476
2,373,925
Heap corruption issues
Inside my template function I have the following code: TypeName myFunction() { TypeName result; void * storage = malloc( sizeof( TypeName ) ); /*Magic code that stores a value in the space pointed to by storage*/ result = *(TypeName *)storage; free( storage ); return result; } This caus...
What about: TypeName myFunction() { TypeName result; void* storage = &result; /*Magic code that stores a value in the space pointed to by storage*/ return result; } Here, all your variables will be stored on the stack so you shouldn't encounter heap-related problems (depending on what exactly your "m...
2,373,526
2,373,834
problem with memcpy'ing from shared memory in boost.interprocess
This is driving me wild with frustration. I am just trying to create a shared memory buffer class that uses in shared memory created through Boost.Interprocess where I can read/store data. I wrote the following to test the functionality #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess...
data isn't being set to point at anything. (Make sure the program is being compiled with all warnings enabled.) It looks like it shouldn't be a pointer anyway. The second loop should perhaps be: int* read_ptr = start_ptr; int data; for( int i= 0; i<10; i++ ) { memcpy( &data, read_ptr, sizeof(int) ); cout << "Re...
2,373,540
2,373,591
fast java/python/C++ ipc
I notice this thread: Fastish Python/Jython IPC, and I have a similar problem, but in different language. I have a Java front-end and a C++ back-end, which I am thinking about rewrite it in Python in some near future. What will be the best IPC? I prefer socket to HTTP, as I am trying to avoid the HTTP overhead. And XML...
For the C++ backend you can use xmlrpc++ (LGPL'ed) - I'm planning to use it myself. It has very clean code so you can modify it easily if you need to. As for the frontends in Java/Python, you could make use of Apache XML-RPC (don't know anything about it) or Python's xmlrpclib (very easy to use). XML-RPC should be cros...
2,373,767
2,373,799
limit the creation of object on heap and stack in C++
I have a question about how to limit the creation of object on heap or stack? For example, how to make sure an object not living on heap? how to make sure an object not living on stack? Thanks!
To prevent accidental creation of an object on the heap, give it private operators new. For example: class X { private: void *operator new(size_t); void *operator new[](size_t); }; To prevent accidental creation on the stack, make all constructors private, and/or make the destructor private, and provide friend...
2,373,859
2,373,895
C++ static const and initialization (is there a fiasco)
I am returning to C++ after a long absence and I am stumbling a little over my understanding of the fairly well known static initialization problem. Let's say I have a simple class Vector2 as given below (note that I am aware that x and y should be private with getters and setters, these have just been omitted for bre...
All of them, except possibility 3, suffer from the static initialization order fiasco. This is because your class is not a POD. In C++0x, this problem can be solved by marking the constructor constexpr, but in C++03 there is no such solution. You can remove the constructor to solve the problem in C++03, and initialize...
2,373,861
2,374,282
Is C++ still actively used for general purpose development?
Possible Duplicate: Which sector of software industry uses C++? C++ was for many years the holy grail of mission critical high performance development. However, it seems that for the past 10 years like much of the development world has moved to Java and C#. My quesiton is this, is C++ effectively relegated to embe...
First of all, I doubt anybody can give a definitive answer -- there's just no way to tell exactly how much any particular language is really used. Nearly anything you can measure is a secondary measurement, such as how many people are advertising jobs using that language. The problem is that this tends to show relative...
2,374,009
2,374,051
Calling this->get/this->set methods versus directly accesing member variables in C++
Suppose I have a class Foo, with a private variable bar_ containing some state for Foo. If necessary, I may write public get/set methods for bar_. Naturally, I avoid this as much as possible to maintain encapsulation. Assuming I have these get/set methods, whenever I have to access or modify bar_ within a method belong...
I have no justification other than concerns regarding the speed of directly accessing the variable versus calling the methods, but I suspect that if the get/set methods are defined inline (which they are) it shouldn't make a difference. Does it make a difference? Does constness play a role in this? The inline keyword...
2,374,065
2,374,138
Some questions about default values in C++
I have some questions about the default values in a function parameter list Is the default value a part of the signature? What about parameter type of the default parameters? Where are the default value stored? In the stack or or global heap or in the constant data segment?
No, default argument is not a part of signature and is not a part of the function type. Parameter type is a part of signature. But default argument type has no effect of parameter type, i.e default argument type has no effect on signature. Default arguments are not "stored" anywhere specifically. Default arguments are ...
2,374,073
2,375,847
Memory management for collections of widgets in Qt
Sorry for the dumb question, but I'm working with Qt and C++ for the first time, and working through the tutorial and some samples. One thing that was mentioned was that Qt stuff doesn't need to be explicitly deleted. So, main question, does this also apply to collections of Qt stuff? Like say I want a dynamic number o...
Qt has an interesting object model for sure. When I first started it made me uneasy that there were so many new Foo calls and no deletes. http://qt.nokia.com/doc/4.6/object.html Is a good place to start reading up on the object model. Things of interest: QObject subclasses have their assignment and copy-ctor methods d...
2,374,227
2,378,083
Any tips for structuring C++ code using win32?
I am trying to improve my coding skills by making my code more structured and readable. I code the GUI (thanks edit). I have been reading through Firefox's open source code to improve but it uses GTK+ and not much Win32. Where can I find an open source (professional) program that is coded in Win32? One more thing: When...
Try this : http://www.relisoft.com/win32/index.htm This guy rebuild classes against the win32 raw api. He gives a good application structure overview, while keeping the layer and abstraction thin.
2,374,341
2,374,444
LinkedList copy constructor implementation details
I'm starting to learn C++ and as an exercise decide to implement a simple LinkedList class (Below there is part of the code). I have a question regarding the way the copy constructor should be implemented and the best way the data on the original LinkedList should be accessed. template <typename T> class Linked...
I assume append will properly handle the initial head/tail details, yes? If so, what you have now is great and simple: Go through the other list, and take its item and add a copy to my list. Perfect. Well, almost. Use an initializer list to initialize member variables: template<typename T> LinkedList<T>::LinkedList(con...
2,374,506
2,386,898
Preprocessor variable when using Adobe Alchemy
I'm porting a cross-platform lib I use to Alchemy. One particular file has a block of code similar to this : #if defined(WIN32) // Do some Windows-specific stuff #elif defined(__linux__) // Do some linux-specific stuff #endif I now need to add Flash-specific code (NOP in some cases), but so far I've been unabl...
Nevermind. I ended up adding -DFLASH to my makefiles.
2,374,719
2,374,739
why weak_ptr can break cyclic reference?
I learnt a lot about weak_ptr working with share_ptr to break cyclic reference. How does it work? How to use that? Can any body give me an example? I am totally lost here. One more question, what's a strong pointer?
It is not included in the reference count, so the resource can be freed even when weak pointers exist. When using a weak_ptr, you acquire a shared_ptr from it, temporarily increasing the reference count. If the resource has already been freed, acquiring the shared_ptr will fail. Q2: shared_ptr is a strong pointer. As l...
2,374,847
2,375,046
Passing member function pointer to member object in c++
I have a problem with using a pointer to function in C++. Here is my example: #include <iostream> using namespace std; class bar { public: void (*funcP)(); }; class foo { public: bar myBar; void hello(){cout << "hello" << endl;}; }; void byebye() { cout << "bye" << endl; } int main() { foo tes...
Taking everyone's suggestions together, your final solution will look like: #include <iostream> using std::cout; usind std::endl; class foo; // tell the compiler there's a foo out there. class bar { public: // If you want to store a pointer to each type of function you'll // need two different pointers he...
2,374,944
2,374,961
Running batch script as windows service
We have a java application which run as server running on a remote windows system which is started though a batch script which includes some initialization configurations. To avoid login into the system every time and starting / stopping the service I planned to add that batch script as a "Windows Service" and use it ...
this may help you a little bit Link here ... it's quite a common problem.
2,375,065
2,375,144
Visual Studio: What exactly are lib files (used for)?
I'm learning C++ and came across those *.lib files that are obviously used by the linker. I had to set some additional dependencies for OpenGL. What exactly are library files in this context used for? What are their contents? How are they generated? Is there anything else worth knowing about them? Or are they just no...
In simple terms, yes - .lib files are just a collection of .obj files. There is a slight complication on Windows that you can have two classes of lib files. Static lib files essentially contain a collection of .obj and are linked with your program to provide all the functions inside the .lib. They are mainly a conveni...
2,375,132
2,375,468
ReleaseSemaphore does not release the semaphore
(In short: main()'s WaitForSingleObject hangs in the program below). I'm trying to write a piece of code that dispatches threads and waits for them to finish before it resumes. Instead of creating the threads every time, which is costly, I put them to sleep. The main thread creates X threads in CREATE_SUSPENDED state. ...
the problem happens in the following case: the main thread resumes the worker threads: for (int i=0 ; i<numCPU ; i++) { if (WaitForSingleObject(semaphore,1) == WAIT_TIMEOUT) printf("Timed out !!!\n"); ResumeThread(ids[i]); } the worker threads do their work and release the semaphore: for (int i=1 ;...
2,375,442
2,375,453
_T("x") not acting as it should
I am running into lots of problems with Unicode at the moment. As I understand it, TCHAR is defined to be either a wchar_t or a char depending on whether _UNICODE is defined somewhere, and there are various other functions to help with this. Apparently _T("x") should evaulate 'x' to either a wchar_t or a char depending...
That should be a TCHAR*, not a TCHAR.
2,375,533
2,375,555
C++ wrapper with overloaded = operator
I'm trying to develop a pretty simple (for now) wrapper class around int, and was hoping to overload the = operator to achieve something like the following: class IntWrapper { ... private: int val; } int main ( ) { IntWrapper a; int b; a = 5; // uses overloaded = to implement setter b ...
You don't need a cast to invoke the conversion function. A plain b = a; will invoke it too. That way, i can see how that's more convenient to use than a getVal function. Although i generally don't use conversion functions. I would prefer an explicit getVal function. In particular consider this one struct W { W(int);...
2,375,622
2,375,680
Performance of Calling Unmanaged .dll from C#
How long is the typical overhead added by calling a .dll written in C++ from a C# application using the following syntax? [DllImport("abc.dll", EntryPoint = "xcFoo", CallingConvention = CallingConvention.Cdecl)] public extern static Result Foo(out IntPtr session, [MarshalAs(UnmanagedType.FunctionPtr)]Ob...
Check out this article on how to improve interop performance. What to do and what best to avoid. http://msdn.microsoft.com/en-us/library/ms998551.aspx
2,375,640
2,375,662
what errors will report if I overload operators incorrectly?
I know that we can't overload operator with other meaning, we can't create new operators, and we can't overload without user-defined class. If I overload operators incorrectly? what errors will report? compiler errors or runtime error? If I overload **, what would happen?
You can overload only existing operators. There is no operator ** in C++. If you try, the compiler would complain. Operator overloads are checked at the compile time. If it compiles, it's just a kind of function, so the possible runtime errors are the same as for any other function.
2,375,682
2,375,693
Which pointer to delete?
I'm trying to multithread something and i have my program set up such that i have a structure/class of variables that will be passed into each thread for processing. In this class, there are variables that hold pointers to arrays some threads have common arrays from which they read data off of, instead of duplicating t...
If you delete an array which other thread is still using, you get undefined behaviour, mist probably a crash. For your case I would recommend to clean up in the main thread, after all the worker threads are finished. Another possibility would be to use a shared pointer, which would automatically free the resources as s...
2,375,784
2,375,838
How to check whether my custom hashing is good in hash_map?
I've written a custom hashing for my custom key in stdext::hash_map and would like to check whether the hasher is good. I'm using STL supplied with VS 2008. A typical check, as I know, is to check the uniformity of distribution among buckets. How should I organize such a check correctly? A solution that comes to my mi...
I'd run one (large) dataset through stl::hash_map. Once done, I'd collect the results for all buckets using the following method From hash_map: size_type elems_in_bucket (size_type __n) const; Finally, I would do compute the standard deviation (SD) of the elem-to-bucket distribution. I'd do the above for different h...
2,375,872
2,377,260
Real life use for Qt (outside of Nokia)
Is Qt an interesting platform for business apps development, outside of Nokia phones ? Why ? Strong points ? Thanks
I like Qt because: Very well-designed framework, e.g. signal-slot, model-view, graphics view/scene/item/proxy, painter/paint device/paint engine..., too many to be listed here! Excellent documentation! Cross platform language/API, as well as tools like UI designer, creator, and so on. Rich features, e.g. graphics fram...
2,375,882
2,375,957
How to call a pointer to method from another method
I had this problem some time ago and I gave up but lately it returned. #include <iostream> class element2D; class node2D { public: void (element2D::*FunctionPtr)(); void otherMethod() { std::cout << "hello" << std::endl; ((this)->*(this->FunctionPtr))(); //ERROR<------------------- } }; clas...
"this" is a pointer to node2D but FunctionPtr refers to a member of element2D -- that is the error. #if 0 // broken version void otherMethod() { std::cout << "hello" << std::endl; ((this)->*(this->FunctionPtr))(); //ERROR<------------------- } #else // fixed version void otherMethod( element2D * that ) { std::cout...
2,375,891
2,375,960
IPhone compilation of ported code problems: sub class of template parameter base class inaccessible
check this out: template <class T> class Test: public T { public: void TestFunc() { T::SubClass bob; } }; this fails when compiling for iPhone (expected ';' before 'bob'). works on other platforms this is a simplified example of what we are actually trying to do, which is inherit from an std::map<...
Very often encountered issue. Put typename: template <class T> class Test: public T { public: void TestFunc() { typename T::SubClass bob; } }; T::SubClass is a dependent name. While parsing the template, the compiler doesn't know yet whether it will be a type. For still being able to parse it (and...
2,375,969
2,415,249
IPhone compilation of ported code problems: variable given same name as typedef'd type failing
check this out: this compiles fine on iPhone: typedef int ATYPE; void AFunc() { ATYPE ATYPE; ATYPE = 1337; } this compiles fine on iPhone: typedef int ATYPE; typedef ATYPE _ATYPE; struct AStruct { _ATYPE ATYPE; }; void AFunc() { AStruct bob; bob.ATYPE = 1337; } but this does NOT: typedef int AT...
Well, if you don't like my previous answer, here's the alternate one. The online Comeau C++ compiler at http://www.comeaucomputing.com/tryitout/ compiles your third example without error. Given that that's typically considered a gold standard among C++ compilers, this suggests that this may well be a bug in the G++ c...
2,376,130
2,376,141
Adding to a Memory Address Error
This doesn't compile in VSC++ 2008. void* toSendMemory2 = toSendMemory + 4; I am at a loss at why, though I am sure it's very stupid of me. :P
When you add N to a T* the pointer will be incremented by sizeof(T) * N bytes. sizeof(void) is nonsensical, so pointer arithmetic over void* is not allowed.
2,376,193
2,376,300
How to write an object to file in C++
I have an object with several text strings as members. I want to write this object to the file all at once, instead of writing each string to file. How can I do that?
You can override operator>> and operator<< to read/write to stream. Example Entry struct with some values: struct Entry2 { string original; string currency; Entry2() {} Entry2(string& in); Entry2(string& original, string& currency) : original(original), currency(currency) {} }; istrea...
2,376,334
2,376,580
C++: How do I pass a container of derived classes to a function expecting a container of their base classes?
HI! Anyone know how I can make the line "chug(derlist);" in the code below work? #include <iostream> #include <list> using namespace std; class Base { public: virtual void chug() { cout << "Base chug\n"; } }; class Derived : public Base { public: virtual void chug() { cout << "Derived chug\n"; } void fo...
Your question is odd; the subject asks "how do I put items in a container without losing polymorphism" - but that is begging the question; items in containers do not lose polymorphism. You just have a container of the base type and everything works. From your sample, it looks what you're asking is "how do I convert a c...
2,376,446
2,376,599
C++ stream operator question
I suppose this might be simple question for all the gurus here but I somehow couldn't figure out the answer. I want to be able to write csv cells to stream as simple as this: stream << 1 << 2 << "Tom" << std::endl; which would create output like 1,2,Tom. How can I achieve that? I figured that I need to create custom s...
Getting something like 98% of the way there isn't terribly difficult: #include <iostream> class add_comma { std::ostream &os; bool begin; typedef add_comma &ref; public: add_comma(std::ostream &o) : os(o), begin(true) {} template <class T> ref operator<<(T const &t) { if (!begin) ...
2,376,448
2,376,456
The written versions of the logical operators
This is the only place I've ever seen and, or and not listed as actual operators in C++. When I wrote up a test program in NetBeans, I got the red underlining as if there was a syntax error and figured the website was wrong, but it is NetBeans which is wrong because it compiled and ran as expected. I can see ! being fa...
They originated in C in the header <iso646.h>. At the time there were keyboards that couldn't type the required symbols for && (for example), so the header contained #define's that would assist them in doing so, by (in our example) defining and to be &&. Of course, as time went by this became less used. In C++, they be...
2,376,468
2,376,567
Visual Studio 2005 and Tinyxml - xml file location
For some reason my Tinyxml file which is created via visual studio 2005 (c++) is saved on my desktop instead of the debug folder or in the program's root folder. if anyone knows about some way to tell vs2005 to save the tinyxml create file somewhere else? I tried that with eclipse and it saved the file in the program's...
You normally shouldn't aspire to write data files to your program directory. Rather than leaving the output directory to chance, you should explicitly tell TinyXml where you want the file created by passing in the whole path when you call SaveFile.
2,376,824
2,376,908
libcurl HTTP request to save respond into variable - c++
I'm trying to save the returned data from HTTP request into a variable. The code below will automatically print the respond of the request, but I need it to save the respond to a char or string. int main(void) { char * result; CURL *curl; CURLcode res; curl = curl_easy_init(); if...
I think you will have to write a function to pass as a write callback via CURLOPT_WRITEFUNCTION (see this). Alternatively you could create a temporary file and pass its file descriptor via CURLOPT_WRITEDATA (the next option listed on that page). Then you would read back the data from the temporary file into a string. N...
2,376,835
2,381,113
Qt: Background thread refreshing UI thread
I have a background thread and the thread calls some methods that update the UI (in order to show progress bars and show additional info in text areas). If I modify some UI widget values, a "Cannot send events to objects owned by a different thread" assertion error is raised. Looking at forums, I read that I could use ...
I haven't used invokeMethod() myself, but to do this, I usually just use signals and slots. For instance, you could create a signal as a member of class B that is connected to the slot in class A that updates the progress: class B : public QObject { Q_OBJECT A* a; signals: void update_signal(bool, int); ...
2,376,862
2,376,881
How to do compare and increment atomically?
In my attempt to develope a thread-safe C++ weak pointer template class, I need to check a flag that indicating the object is still alive, if yes then increment the object's reference count and I need to do the both steps atomically. I know the existance of intrinsics functions provided by the compiler, for instance _I...
Suppose that value is your flag variable. It should be declared volatile. long curvalue; long newvalue; do { curvalue = value; newvalue = curvalue + 1; } while( _InterlockedCompareExchange( &value, newvalue, curvalue ) != curvalue ); As you see you can generalize this to whatever kind of arithmetic you need b...
2,376,899
2,376,907
Understanding the memory content of a union
Suppose I define a union like this: #include <stdio.h> int main() { union u { int i; float f; }; union u tst; tst.f = 23.45; printf("%d\n", tst.i); return 0; } Can somebody tell me what the memory where tst is stored will look like? I am trying to understand the output 110281...
It depends on the implementation (compiler, OS, etc.) but you can use the debugger to actually see the memory contents if you want. For example, in my MSVC 2008: 0x00415748 9a 99 bb 41 is the memory contents. Read from LSB on the left side (Intel, little-endian machine), this is 0x41bb999a or indeed 1102813594. Gener...
2,376,915
2,376,988
How to print out the memory contents of a variable in C?
Suppose I do a double d = 234.5; I want to see the memory contents of d [the whole 8 bytes] How do I do that?
double d = 234.5; /* 1. use a union */ union u { double d; unsigned char c[sizeof(double)]; }; union u tmp; size_t i; tmp.d = d; for (i=0; i < sizeof(double); ++i) printf("%02x\n", tmp.c[i]); /* 2. memcpy */ unsigned char data[sizeof d]; size_t i; memcpy(data, &d, sizeof d); for (i=0; i < sizeof d; ++i) ...
2,376,954
2,376,986
problem with iterator manipulation
i have a std::map and i am using iterator to find a certain key,value pair. After finding it i am unable to get the position of the key,value pair from the iterator. By doing another find i can get it, but i want a work around for this. //mycode is this std::map<std::string,myclass*> mymap; size_t myfind(const std::s...
If you want to return the "position" of the result: #include <iterator> // ... std::map<std::string,myclass*> mymap; size_t myfind(const std::string &s) { std::map<std:string,myclass*>::iterator i=mymap.find(s); if((i==mymap.end())||((*i).second==0)) { std::cout<<"some error\n"; } else ...
2,377,043
2,425,451
VS 2008 C++ build output?
Why when I watch the build output from a VC++ project in VS do I see: 1>Compiling... 1>a.cpp 1>b.cpp 1>c.cpp 1>d.cpp 1>e.cpp [etc...] 1>Generating code... 1>x.cpp 1>y.cpp [etc...] The output looks as though several compilation units are being handled before any code is generated. Is this really g...
Compiler architecture The compiler is not generating code from the source directly, it first compiles it into an intermediate form (see compiler front-end) and then generates the code from the intermediate form, including any optimizations (see compiler back-end). Visual Studio compiler process spawning In a Visual Stu...
2,377,062
2,383,315
Visual C++ BigInt and SecureRandom? Is there a BigInt library with modPow?
I have to port some crypto code to visual c++ from java which (visual c++) I am not very familiar with. I found a library at http://sourceforge.net/projects/cpp-bigint/ that I can use for big integers. However it does not have an equivalent to javas SecureRandom class. I did find a project in c++ called beecrypt but...
The modPow function can be evaluated efficiently with a "square and multiply" algorithm. In Java it would look like this (if Java's BigInteger did not already have it): /* Compute x^n mod m. */ static BigInteger modPow(BigInteger x, BigInteger n, BigInteger m) { if (n.signum() < 0) throw new IllegalArgument...
2,377,286
2,377,389
C++/C/Java: Anagrams - from original string to target;
I'm trying to solve this problem : http://uva.onlinejudge.org/external/7/732.html. For the given example, they give us the original word, for example TRIT and the target "anagramed" string, TIRT. Objective: We have to output all the valid sequences of 'i' and 'o' (push and pop's, respectively) which produce the target ...
This first iteration solution is instructive. It's not the most efficient since it uses String all over the place, but it's a good place to start. import java.util.*; public class StackAnagram { static void anagram(String s1, String s2, String stack, String instr) { if (s2.isEmpty()) { if (s1....
2,377,296
2,377,308
Modifying a window's textbox control's text
Case in point : I've got a handle to a window (for instance, using the getForegroundWindow() API function). This window's got a textbox (possibly a richtext control). Would it be possible to modify the textbox's text through an Windows API call ? More specifically, I'd like to replace its text with some of my own.
Once you have the handle to the parent window, you need to get the handle to the editcontrol. If the editcontrol has a known, consistent identifier, use GetDlgItem to get its HWND. Otherwise you will need to resort to FindWindowEx. Once you have the HWND of the editcontrol, you can use SendMessage to send a WM_SETTE...
2,377,327
2,377,437
Creating a Trapezoid using a character inputted by the user. (Console App)
I am trying to create a trapezoid using user inputted options. I know my code may not be the best way but so far it works! My problem is i need the base of the trapezoid to be touching the left side of the output window. What am i doing wrong? #include <iostream> #include <iomanip> #include <cmath> using namespace std...
setw sets the width for the next operation, not the entire line. So, the width of a single cout << fill is set to the value. This is giving you the padding, but you need to set setw to 0 for the final row. also, there seems to be some redundant code try: int main() { int topw, height, width, rowCount = 0, temp; c...
2,377,392
2,416,667
Javascript Refuses to Call ActiveX Method, Agrees to Call Another
I have an ActiveX object which extends some functions. I have a web page that loads the ActiveX object and calls its methods in Javascript. The ActiveX object has two method; the problem is that Javascript can successfully call one of them but fails to call the other; citing Object doesn't support this property or meth...
The answer was pretty simple. In the IDL file the function was declared as a property (propget) without taking any input arguments. In the Javascript code, I was calling actvx3obj.ATR(); when in fact I should have been calling actvx3obj.ATR; because it is a property get method that takes no argument. I'm posting this i...
2,377,443
2,377,451
Can I make the following assumption when map key is not found?
std::map<std::string, int> m; // Can I make assumption that m["NoSuchKey"] will return 0? std::cout << m["NoSuchKey"] << std::endl;
Yes. When an item is accessed through operator[] that does not exist, it is created with a default-constructed value, and returned. For numeric types, default-constructed means 0.
2,377,515
2,381,142
MSVC: Embedding Data in Program
I'm hoping someone has run into this sort of problem before, and can give me a hint to solve it. With Microsoft Visual C++ 2005, I have this code in a program: DWORD locator[FOURXFLAGCOUNT+1]={ 0x58585858, 0x58585858, 0x58585858, 0x58585858, 0x58585858, 0x58585858, 0x58585858, 0x58585858, 0x58585858, 0x58585858...
I haven't been able to find any acceptable solution to this problem. The linker is just too aggressive about what it trims... maybe a bug, maybe deliberate, though for the life of me, I can't imagine a case where you would want to eliminate the initialization of a variable while keeping the variable itself. For now, I'...
2,377,570
2,379,685
A GUI which creates and uses a database and installes easily
I want to create a GUI with C++ (QT4). The GUI should work on Windows and should be able to create a database use the database created by it (I should use an existing DBMS, in order not to worry for queries) database should be specific to the GUI, other software should not be able to use that database (the database m...
You could try looking into SQLite. The library can be used with C++. It will not need an external DBMS. SQLite is embedded into your application, and you can access you database through it. Also, the database files it produces can be encoded, so it will be accessible to your application only.
2,377,617
2,377,649
How to use COM dll in my C++ program
I wish to use a COM dll in my C++ library. The way I figured going about it, is to #import the dll's .tlb file, which I did : #import "mycom.tlb" no_namespace The problem is , I don't quite know where to place this declaration. should it be inside the H file or the CPP file? or maybe the stdafx.h file? I tried placin...
The problem is that when the compiler parses the .h file it has not seen the #import yet. Since your project is small your best bet is to put #import into stdafx.h. When you press F12 Visual Studio uses Intellisence database information that is formed parsing all the sources in order that might be different from the co...
2,377,619
2,378,090
Fast way to determine right most nth bit set in a 64 bit
I try to determine the right most nth bit set if (value & (1 << 0)) { return 0; } if (value & (1 << 1)) { return 1; } if (value & (1 << 2)) { return 2; } ... if (value & (1 << 63)) { return 63; } if comparison needs to be done 64 times. Is there any faster way?
Works for Visual C++ 6 int toErrorCodeBit(__int64 value) { const int low_double_word = value; int result = 0; __asm { bsf eax, low_double_word jz low_double_value_0 mov result, eax } return result; low_double_value_0: const int upper_double_word = value >> 32; ...
2,377,733
2,377,772
How does this program work?
#include <stdio.h> int main() { float a = 1234.5f; printf("%d\n", a); return 0; } It displays a 0!! How is that possible? What is the reasoning? I have deliberately put a %d in the printf statement to study the behaviour of printf.
That's because %d expects an int but you've provided a float. Use %e/%f/%g to print the float. On why 0 is printed: The floating point number is converted to double before sending to printf. The number 1234.5 in double representation in little endian is 00 00 00 00 00 4A 93 40 A %d consumes a 32-bit integer, so a ze...
2,377,985
2,453,626
Doxygen C++ comment string parser in python?
Does anybody know of a python module to parse a doxygen style C++ comment string? I mean a string like this (simple example): /** * A constructor. * A more elaborate description of the constructor. * @param param1 test1 * @param param2 test2 */ and I would like to extract the brief, the long descripti...
You might be able to set something up using the SimpleParse module, but this does require creating an EBNF grammar which might be more investment than you are interested in. The Sphinx/Doxygen bridge (Breathe) uses the xml output of Doxygen and acts on that instead. Perhaps a similar approach could work here - run Dox...
2,378,072
2,378,105
How to disable that an MFC application exits on pressing ESC or ALTF+F4?
I have an MFC application, which i don't want to be closed during the running. I have disabled the "X" icon in the right upper corner, but now if i press the ESC key, or ALT+F4 it still closes. How can i disable this, so it won't close, if someone press those keys? After the program has finished running i want to reen...
If you handle the WM_CLOSE message and throw it away. (i.e. Don't call DefWindowProc), then the window won't close. You could also register the window class with the CS_NOCLOSE style, to disable all of the normal ways of closing the window.
2,378,080
2,378,154
asm/atomic.h compile error
I have an old C++ project and I'm having problem building it. For a certain file I receive the following kind of errors: error: ‘atomic_t’ was not declared in this scope And others for other identifiers like atomic_read, atomic_inc, etc. The file has an include for asm/atomic.h, but I cannot find the header file on m...
These are meant to be kernel headers, not really for applications to use. They are the prototypes for some atomic test and set, increment, decrement etc that are implemented in assembler. so even if you find the header files, you will still need the .o from the asm or the .asm sources. These are not the files you are ...
2,378,106
2,378,131
Pointer to pointer memory allocation, why is this wrong?
I am just trying to get my head around various pointer concepts and I have the following code: char** a = new char*; // assign first pointer to point to a char pointer char b[10] = "bla bla"; *a = new char; //assign second pointer a block of memory. -> This looks wrong to me!! (**a) = b[2]; So what is...
*a = new char; means that you create a single char variable using its default constructor. It's equivalent to *a = new char(); And you assign the address of the just created variable to the pointer a
2,378,150
2,378,207
C++ scope of inline functions
i am getting the compile error: Error 7 error C2084: function 'Boolean IsPointInRect(...)' already has a body on my inline function, which is declared like this in a cpp file: inline Boolean IsPointInRect(...) { ... } i have exactly the same function in another cpp file. might this be causing the problem? how c...
As litb and AndreyT point out, this answer doesn't address the actual problem - see litbs answer for details. While static, as Ofir said, gives you internal linkage, the "C++ way" is to use unnamed namespaces: namespace { inline Boolean IsPointInRect(/*...*/) { /*...*/ } } §7.3.1.1/1: An unnamed-namespace-defin...
2,378,179
2,379,960
Does std::vector call the swap function when growing? Always or only for some types?
As far as I know I can use a vector of vectors (std::vector< std::vector<int> >) and this will be quite efficient, because internally the elements will not be copied, but swapped, which is much faster, because does not include copying of the memory buffers. Am I right? When does std::vector exactly make use of the swap...
I have no links to back up this claims, but as far as I know, the STL implementation distributed with Microsoft C++ uses some internal non-standard magic annotations to mark vector (and other STL collections) as having-performant-swap so vector<vector<>> won't copy the inner vectors but swap them. Up to VC9 that is, in...
2,378,416
2,378,433
How do I link a static library in a cpp source file?
There's a #pragma command to link in a library from the source file rather than from the project settings. I just can't seem to remember it. Can anyone here remind me? Thanks
#pragma comment(lib, "library") http://msdn.microsoft.com/en-us/library/7f0aews7(VS.80).aspx
2,378,492
2,380,367
Date/time conversion problem if moment is exactly at end of wintertime (non-DST)
In my application I need to calculate shifts using a pattern described in a file. Recently, at one of my customers the application was hanging because of the following reason: If you fill in a 'struct tm' with the exact moment at the end of the wintertime (non-DST) _mktime seems to return an incorrect result. The code ...
I guess it simply doesn't know how to correctly handle the invalid time you pass in. And it is certainly invalid for your time zone - you're thinking of it as '1 minute after 1:59 in the winter' implying that you wanted it to return '3:00' with DST back in operation, which sounds reasonable. However it could equally we...
2,379,129
2,379,297
How to order my objects in a C++ class correctly
I have been coding regurlarly in C++ in the past months. I am getting used to it step by step... but there are things that confuse me about formatting. I know there is a lot of legacy from C that I supousee mixes with C++. This time I have doubts about how to order properly my members and functions within in a class. A...
My humble opinion, after having read many style guides all over the 'net: Public first, because that is the interface of your class, which people want to see first. From the same reasoning, private goes last. If you have any private functions, place them before private members. (Again, same reasoning. Your members ar...
2,379,208
2,380,167
How can I display a bitmap/icon on an XP style button
I have a small (6x9) graphic that I want to draw on a CButton. I have managed to get this to work using ::LoadImage and CButton::SetBitmap. The problem is that when I put the bitmap on the button it is no-longer drawn as an 'XP style' button. I.e. it does not have rounded corners. How can I draw a bitmap (or an icon) o...
Don't do it with owner draw. Use CMFCButton which has much better support for bitmapped buttons, even with transparency.
2,379,401
2,379,955
Pointer to a class member
I am using Boost Spirit parser, and as the parser is parsing, semantic actions are reflected to an instance of the class ParserActions. Here is the code for the parser (the relevant part) struct urdf_grammar : public grammar<urdf_grammar> { template <typename ScannerT> struct definition { definition(urdf_...
In order to call a member function of an object you need to provide two things: the address of the member function, as said before you can get that by writing &my_class::my_member the pointer (or a reference) to the instance of the object you want the member function be invoked for Spirit semantic actions expect you ...