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
1,081,519
1,081,530
Why does C++ use pointers?
Why does C++ need and use pointers? I know they add power to the language but they make it a lot harder to understand for beginners. Languages like F#, Java, Ruby, Python, Lua, etc. get by just fine without them, and they're quite powerful.
All other languages you mention (and you forgot, at least, Java!!!), while each very useful and usable, don't let you get anywhere as close to the machine as C++ (and C) allow: simply put, all of those languages impose on you a higher level of abstraction... which may mostly be fine but will occasionally get in your wa...
1,081,764
1,082,515
tips to avoid synchronisation issues in multiplayer and replays using MVC pattern
just wondering what tips people have for avoiding game synchronisation issues in multiplayer games and replays recorded off of game logic using the model in a model view controller pattern so far im aware that its not a good idea to give non const access to the model anywhere outside of it, but apart from that im a li...
To achieve distributed synchronisation, you need a designated single master model, ideally on a separate game server. Control events go to that, get timestamped, the interactions of everything going on gets calculated, and timestamped update events get sent out. Replays can be done just by storing and replaying the upd...
1,081,811
1,081,821
c++ * vs & in function declaration
Possible Duplicate: Difference between pointer variable and reference variable in C++ When should I declare my variables as pointers vs objects passed-by-reference? They compile to the same thing in assembly (at least run-time asymptotically) so when should I use which? void foo(obj* param) void foo(obj& param)
My rule is simple: use * when you want to show that value is optional and thus can be 0. Excluding from the rule: all the _obj_s around are stored in containers and you don't want to make your code look ugly by using everywhere foo(*value); instead of foo(value); So then to show that value can't be 0 put assert(value);...
1,081,831
1,105,925
Windows std::ifstream::open() problem
I know there's been a handful of questions regarding std::ifstream::open(), but the answers didn't solve my problem. Most of them were specific to Win32, and I'm using SDL, not touching any OS-specific functionality (...that's not wrapped up into SDL). The problem is: std::ifstream::open() doesn't seem to work anymore ...
I have overseen the importance of the fact that the function in question has close()d the stream without checking if it is_open(). The fact that it will set the stream's fail_bit (causing it to evaluate to false) was entirely new to me (it's not that it's an excuse), and I still don't understand why did this code work ...
1,081,840
1,082,171
Handling COR dump issue with purify
I an instrumenting a C++application using IBM purify and I get the issue COR dump and my program aborts although when run from terminal it runs fine. Can anyone tell me what is this COR dump and how to handle with it? Platform: RHEL 64bit Thanx,
If the software you are using is licensed, please contact IBM.
1,081,843
1,082,416
Most beautiful open source software written in c++
I was told that to be a good developer, you should read a lot of other peoples source code. I think that sounds reasonable. So I ask you, what is the most beautifully written piece of open source software that is written in c++ out there? (Apply any definition of beautiful you like.)
You could look at the source code of MySQL GUI Tools. Its written using gtkmm, and the code does some interesting difficult-to-implement GUI things.
1,081,979
1,082,993
How to select an item in a listview which allows only 1 selected item at a time
I've been trying to select an item on an external listview but it seems to only work with listviews that accept multiple selected items: HANDLE process=OpenProcess(PROCESS_VM_OPERATION|PROCESS_VM_READ|PROCESS_VM_WRITE|PROCESS_QUERY_INFORMATION, FALSE, 0xC30); LVITEM lvi; LVITEM* _lvi=(LVITEM*)VirtualAllocEx(process,...
Your code looks valid, and should work, I've tested it internally within my own GUI application itself, so perhaps the issue is in your attempt to access from outside of the actual process. I notice that you have hard coded the HWND for the ListView. Also I would be careful with the fact that you immediately release th...
1,082,064
1,082,093
In C/C++ can anybody provide some thumb rules for writing small function using inline or macro?
Discussing with people, asking in interviews, or being asked in interviews, I do not know if I know exactly when to write a function as inline or write it as a macro. Apart from compile-time and run-time consideration, is there any suggestion from coding standard point of view. I think this is one of those question whe...
Macros should be used sparingly, in circumstances where a function will simply not do the job. An example, is error reporting. I use this macro for that purpose: #define ATHROW( msg ) \ { \ std::ostringst...
1,082,083
1,082,107
Are free functions implicitly inlined if defined without a previous declaration in C++?
Is the following free function implicitly inlined in C++, similar to how member functions are implicitly inlined if defined in the class definition? void func() { ... } Do template functions behave the same way?
No, it's not implicitly inlined. The compiler has no way of knowing if another module will use this function, so it has to generate code for it. This means, for instance, that if you define the function like that in a header and include the header twice, you will get linker errors about multiple definitions. Explicit i...
1,082,192
1,082,211
How to generate random variable names in C++ using macros?
I'm creating a macro in C++ that declares a variable and assigns some value to it. Depending on how the macro is used, the second occurrence of the macro can override the value of the first variable. For instance: #define MY_MACRO int my_variable_[random-number-here] = getCurrentTime(); The other motivation to use tha...
Add M4 to your build flow? This macro language has some stateful capabilities, and can successfully be intermingled with CPP macros. This is probably not a standard way to generate unique names in a C environment, though I've been able to sucessfully use it in such a manner. You probably do not not want random, BTW, ...
1,082,378
1,082,398
what is the basic use of aligned_storage?
What is the basic usage of std::tr1::aligned_storage ? Can it be used as auto memory for a data type Foo like the one below? struct Foo{...}; std::tr1::aligned_storage<sizeof(Foo) ,std::tr1::alignment_of<Foo>::value >::type buf; Foo* f = new (reinterpret_cast<void*>(&buf)) Foo(); f->~Foo(); If so, ...
Well, apart from your use of reinterpret_cast, it looks ok to me. (I'm not 100% sure on the second one). The problem with reinterpret_cast is that it makes no guarantees about the result of the cast, only that if you cast the result back to the original type, you get the original value. So there is no guarantee that th...
1,082,489
1,082,490
Passing data types from C++ to Java/Java to C++
What data types can be passed between c++ and java/java to c++? Also, are the data types equivalent in terms of size?
Using Java Native Interface you can pass just about anything between C++ and Java.
1,082,527
1,082,534
to insert() or to make new
I'm writing some code that has a lot of substitution. There's a list<char> productions which has a bunch of characters in it. I repeatedly need to replace every character in productions with the rules corresponding to it in a map<char,char*> productionRules. So every character in productions might be replaced by zero ...
It depends on how likely it is that each character would be replaced by zero or >2 characters. If it's unlikely that any such replacement will take place, then you'll probably win by iterating over it. But if it's likely that you will often perform that operation you should almost certainly just create a new list. You ...
1,082,552
1,082,563
A function pointer that points to a function that takes an object of a template class with said function pointer as template argument. Possible?
x__x I want to do something like this: typedef long (* fp)(BaseWindow< fp > & wnd, HWND hwnd, long wparam, long lparam); But I get a compile error: error C2065: 'fp' : undeclared identifier Is it possible to implement this somehow?
No it isn't, because the type of the template parameter would include itself. This would yield to an endless recursion in the type. If instead of the class template specialization, you accept a base-class of it, that's very possible struct TemplateBase { }; typedef long (*fpType)(TemplateBase&, HWND, long, long); t...
1,082,655
1,082,682
Conditional operator differences between C and C++
I read somewhere that the ?: operator in C is slightly different in C++, that there's some source code that works differently in both languages. Unfortunately, I can't find the text anywhere. Does anyone know what this difference is?
The conditional operator in C++ can return an lvalue, whereas C does not allow for similar functionality. Hence, the following is legal in C++: (true ? a : b) = 1; To replicate this in C, you would have to resort to if/else, or deal with references directly: *(true ? &a : &b) = 1; Also in C++, ?: and = operators hav...
1,082,867
1,082,941
is there a functor that derefences a (smart) pointer, upcasts it, and then calls a method on it?
I have class A: public B { ...} vector<A*> v; I want to do for_each(v.begin(), v.end(), mem_fun_deref(B::blah())); (Actually I have: vector<unique_ptr<A>> but it shouldn't matter) I need to upcast and call the member function.
boost::lambda can do it vector<A*> v; ... using boost::lambda::_1; using boost::lambda::bind; for_each(v.begin(), v.end(), bind(&B::blah, *_1)); No need to upcast. A member pointer to a base-class member can be applied to a derived class too. #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp>
1,082,901
1,082,935
Reading input from file prints strange symbols
I'm attempting to solve the Project Euler Problem 8 with C++, and the problem is to find the greatest product of 5 consecutive numbers in a 1000 digit number. So I'm trying to figure out how to use file io to read the numbers into a char array that I will later convert to integers. The read works except for the last th...
Two problems with your code. First, it looks like you're not accounting for newlines in your maxNum buffer size, so it stops reading either 19 or 38 characters before the end of the text file (depending on if you're using Unix-style or Windows-style line breaks). Either increase the value of maxNum accordingly, or rem...
1,083,252
1,083,309
CA2W gave me a "'AtlThrowLastWin32': identifier not found" error
I got a strange compilation error when I followed the MSDN document to use CA2W to convert big5 strings to unicode strings in Visual Studio 2005. This is the code I wrote: #include <string> #include <atldef.h> #include <atlconv.h> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { string chineseInBig5 ...
I finally solved this problem by adding 2 include headers: #include <atlbase.h> #include <atlstr.h> I don't know why the MSDN document doesn't mention that.
1,083,304
1,083,319
C/C++ counting the number of decimals?
Lets say that input from the user is a decimal number, ex. 5.2155 (having 4 decimal digits). It can be stored freely (int,double) etc. Is there any clever (or very simple) way to find out how many decimals the number has? (kinda like the question how do you find that a number is even or odd by masking last bit).
Two ways I know of, neither very clever unfortunately but this is more a limitation of the environment rather than me :-) The first is to sprintf the number to a big buffer with a "%.50f" format string, strip off the trailing zeros then count the characters after the decimal point. This will be limited by the printf fa...
1,083,959
1,083,980
Purpose of struct, typedef struct, in C++
In C++ it is possible to create a struct: struct MyStruct { ... } And also possible to do the following: typedef struct { ... } MyStruct; And yet as far as I can tell, no discernable difference between the two. Which is preferable? Why do both ways exist if there is no difference? Is one better than the other...
The typedef version is a special case of typedef foo bar; which defines a new "type" bar as an alias for foo. In your case, foo happens to be a struct. In C, this was the only way to introduce new "types" (in quotes, because they are not really equivalent to int, float and co). In C++, this is not so useful, because ...
1,084,039
1,084,041
C/C++ add input to stdin from the program?
Is that even possible ? Lets say that the code has a lot of scanf lines. Instead of manually running and adding values by hand when debugging, is it possible to "feed" stdin with data so that when the scanf starts reading, it will read the inputted data without any need to interact with the terminal.
Put the test lines into a file, and run the program like this: myprogram < mytestlines.txt Better than hacking your program to somehow do that itself. When you're debugging the code, you can set up the debugger to run it with that command line.
1,084,251
1,084,338
What are some effective methods for handling user keyboard input
I've been learning C++ for about a month now, and as I've written programs I've noticed that enabling the user to cancel their input (during a cin loop) is a pain. For example, a program that takes user input and stores it in a vector would have a cin loop like this. vector<int>reftest; int number; cout << ...
There are several ways to approach your problem. The easiest is probably to move out of a direct cin/cout loop and to use std::getline instead. Specifically, you could write something like: #include <iostream> #include <vector> #include <sstream> using namespace std; int main( int argc, char **argv ) { vector<int>...
1,084,844
1,084,849
Will reading a file be faster with a FILE* or an std::ifstream?
I was thinking about this when I ran into a problem using std::ofstream. My thinking is that since std::ifstream, it wouldn't support random access. Rather, it would just start at the beginning and stream by until you get to the part you want. Is this just quick so we don't notice? And I'm pretty sure FILE* supports ra...
ifstream supports random access with seekg. FILE* might be faster but you should measure it.
1,084,935
1,084,958
C++ or Python as a starting point into GUI programming?
I have neglected my programming skills since i left school and now i want to start a few things that are running around in my head. Qt would be the toolkit for me to use but i am undecided if i should use Python (looks to me like the easier to learn with a few general ideas about programming) or C++ (the thing to use w...
Being an expert in both C++ and Python, my mantra has long been "Python where I can, C++ where I must": Python is faster (in term of programmer productivity and development cycle) and easier, C++ can give that extra bit of power when I have to get close to the hardware or be extremely careful about every byte or machin...
1,084,960
1,085,033
Is it possible to treat macro's arguments as regular expressions?
Suppose I have a C++ macro CATCH to replace the catch statement and that macro receive as parameter a variable-declaration regular expression, like <type_name> [*] <var_name> or something like that. Is there a way to recognize those "fields" and use them in the macro definition? For instance: #define CATCH(var_declarat...
You can't do it with just macros, but you can be clever with some helper code. template<typename ExceptionObjectType> struct ExceptionObjectWrapper { ExceptionObjectType& m_unwrapped; ExceptionObjectWrapper(ExceptionObjectType& unwrapped) : m_unwrapped(unwrapped) {} template<typename CastType> operator CastTyp...
1,084,982
1,085,920
Building Boost without filename decorations?
The default naming convention for the Boost C++ libraries is: libboost_regex-vc71-mt-d-1_34.lib where all libraries are built into the same directory. I'd like to modify the build process so that the filename does not contain the target architecture or build type (versions are okay). I want the file to end up in a diff...
You can remove all decoration from the library filenames by passing "--layout=system". Your example above shows "vc71/release" paths -- there's no out-of-box way to get this layout. You can do that with a bit of hackign. In Jamroot, find the 'stage-proper' target, which specifies the location as: <location>$(stage-lo...
1,085,489
1,085,544
STL List to hold structure pointers
I have a structure called vertex and I created some pointers to them. What I want to do is add those pointers to a list. My code below, when it tries to insert the pointer into the list, creates a segmentation fault. Can someone please explain what is going on? #include <iostream> #include <list> #define NUM_VERTIC...
There are several things wrong here. First off, you aren't initializing the iterator, like other's have said: list<vertex*>::iterator it = r_list->begin(); Do this and your code will be fine. But your code is done in a bad manner. Why are you allocating the list from the heap? Look at your code: you have a memory leak...
1,085,490
1,085,547
How do C/C++ compilers work?
After over a decade of C/C++ coding, I've noticed the following pattern - very good programmers tend to have detailed knowledge of the innards of the compiler. I'm a reasonably good programmer, and I have an ad-hoc collection of compiler "superstitions", so I'd like to reboot my knowledge and start from the basics. Ca...
Start with the dragon book....(stress more on code optimization and code generation) Go onto write a toy compiler for an educational programming language like Decaf or Cool.., you may use parser generators (lex and yacc) for your front end(to make life easier and focus on more imp stuff).... Then read gcc internals boo...
1,085,617
1,085,755
How does the centripetal Catmull–Rom spline work?
From this site, which seems to have the most detailed information about Catmull-Rom splines, it seems that four points are needed to create the spline. However, it does not mention how the points p0 and p3 affect the values between p1 and p2. Another question I have is how would you create continuous splines? Would it ...
Take a look at equation 2 -- it describes how the control points affect the line. You can see points P0 and P3 go into the equation for plotting points along the curve from P1 to P2. You'll also see that the equation gives P1 when t == 0 and P2 when t == 1. This example equation can be generalized. If you have points...
1,085,873
1,086,115
DLL memory manager mixup
I wrote an application which allows people to contribute plugins to extend the functionality. Such plugins are deployed as DLL files, which the framework picks up during runtime. Each plugin features a factory function which is called multiple times during the lifetime of the application to create objects. So far, in o...
There are two solutions. Solution one is "share more" - you can move new/delete across DLL boundaries if both sides use the same CRT DLL (/MD or /MDd in MSVC). Solution two is "share less" - let each DLL have its own C++ heap, and do not split new/delete across DLL boundaries.
1,086,179
1,086,216
Tiny C++ cross-platform GUI toolkit
Which C++ cross-platform GUI toolkit gives smallest footprint with both static and dynamic builds? I don't need a very sophisticated GUI, just basic controls & widgets.
the smallest one I've heard of is fltk
1,086,254
1,086,268
Read data directly from file to RAM in C++
Is there a way to directly read a binary file into RAM? What I mean is, is there a way to tell the compiler, here's the file, here's the block of RAM, please put the file contents in the RAM, off you go, quickly as you can please. Currently I'm stepping through the file with ifstream loading it into RAM (an array) 64bi...
What prevents you from reading the file in one pass? Is it too big to fit in memory? You can also use mapped file, UNIX : mmap, Windows : CreateFileMapping
1,086,550
1,087,371
What are the concepts a vc++ developer should be familiar with?
I am a vc++ developer but I spend most of my time learning c++.What are all the things I should know as a vc developer.
I don't understand why people here post things about WinAPI, .NET, MFC and ATL. You really must know the language. Another benefit would be the cross platform libraries. C++ is not about GUI or Win32 programming. You can write Multi-Platform application with libraries like boost, QT, wxWidgets (may be some XML parser l...
1,086,632
1,086,687
PostMessage params from 32-bit C# to 64-bit C++
I am having problem with the contents of a pointer passed as the wParam from a 32-bit C# application is changing along the way to a 64-bit C++ process. There are two processes 32.exe (in C#) and 64.exe (in C++). 64.exe is started as a child process of 32.exe. 32.exe post window message for 64.exe, one of which has a wP...
Each of the two processes has an own address space, so that the pointer from process 32.exe is not valid in 64.exe. However, this has nothing to do with 32bit vs 64bit at all. You just have to use an interprocess communication technique of your choice to transfer the data between the two processes. For example, you cou...
1,086,786
1,087,344
C++ Dependencies manager
We have here a pretty big application that is taking a lot of time to compile and I am looking for a way to reduce this compile time. I thought a good way to do this would be to reduce the dependency between the include files. Do you know any good dependency/Includes manager that would be pretty cheap? Something that w...
You could use Source Navigator to analyze the source. Look at the section: Using the Include Browser in here. Or a better option would be to use cinclude2dot
1,086,798
1,088,080
Differences between different flavours of shared_ptr
Are there any differences between boost::shared_ptr, std::tr1::shared_ptr and the upcoming (in C++0x) std::shared_ptr? Will porting from one to another have any overhead or are they basically the same?
According to the Boost website, the boost::shared_ptr... ...conforms to the TR1 specification, with the only exception that it resides in namespace boost instead of std::tr1. According to the Wikipedia C++0x page The TR1 implementation lacked certain pointer features such as aliasing and pointer arithmetic, but the ...
1,087,042
1,087,066
C++ new int[0] -- will it allocate memory?
A simple test app: cout << new int[0] << endl; outputs: 0x876c0b8 So it looks like it works. What does the standard say about this? Is it always legal to "allocate" empty block of memory?
From 5.3.4/7 When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements. From 3.7.3.1/2 The effect of dereferencing a pointer returned as a request for zero size is undefined. Also Even if the size of the space requested [by new] is ...
1,087,088
1,087,106
Single quote issues with C++ find and replace function
Here is my code for finding a sequence in a string and replacing it with another: std::string find_and_replace( string &source, string find, string replace ) { size_t j; for ( ; (j = source.find( find )) != string::npos ; ) { source.replace( j, find.length(), replace ); } return source; } E...
You've got an infinite loop because your condition doesn't move forward. You're always running j = source.find( find ), but you're replacing ' with '', so you're always finding the first apostrophe every time and adding a new apostrophe to the string. You need to make sure you don't match the same apostrophe twice by ...
1,087,199
1,087,372
boost::asio: How do I use async_accept to accept incoming connections?
I'm using boost::asio, and I have code like this: void CServer::Start(int port) { tcp::acceptor acceptor(m_IoService, tcp::endpoint(tcp::v4(), port)); for ( ;; ) { shared_ptr<tcp::socket> pSocket(new tcp::socket(m_IoService)); acceptor.accept(*pSocket); HandleRequest(pSocket); ...
Ah, looks like to kick things off you need to run the IOService, e.g.: m_IoService.run();
1,087,514
1,087,729
std::vector visualizer doesn't work properly on std::vector<boost::variant>
The visual studio std::vector visualizer in the VS2008 autoexp.dat file doesn't seem to work if I have a std::vector<boost::variant<...>>. It does work on other types of vectors I have tried (e.g std::vector<int>, std::vector<boost::shared_ptr<..>>) Here is the visualizer code: std::vector<*>{ children ( #array ...
It seems to be a bug related to the size of the name of your type... boost::variant generates types with very long names. I've made some tests, and it seems that the limit is a struct with name size of 497 characters. The following code reproduces the error... take the last character of the struct name, and it works fi...
1,087,537
1,090,268
Remove border on activex ie control
For the application im building, i use an activex ie control. It works greate but i cant work out how to remove the border around it. I have tried overriding the invoke call and setting DISPID_BORDERSTYLE to zero but it looks like it never gets hit. Any ideas?
I think you need to implement IDocHostUIHandler on your host. then in GetHostInfo you can return the DOCHOSTUIFLAG_NO3DBORDER or DOCHOSTUIFLAG_NO3DOUTERBORDER flag.
1,087,580
1,088,910
Resource temporarily unavailable in Boost ASIO
I get the error message "Resource temporarily unavailable" when I use the method receive_from(), it's a member of ip::udp::socket located here. I pass to it: boost::asio::buffer, pointer to an endpoint object, flags (set to zero), and an error_code object. I create the endpoint with just new udp::endpoint() There ...
"Resource temporarily unavailable" is normally the text description for EAGAIN, indicating that the operation should be retried. In the case of UDP, it indicates that there isn't any data available at present, and you should try later. It's generally worth looking at the man page for the underlying libc function; which...
1,087,600
1,087,662
Pointers to virtual member functions. How does it work?
Consider the following C++ code: class A { public: virtual void f()=0; }; int main() { void (A::*f)()=&A::f; } If I'd have to guess, I'd say that &A::f in this context would mean "the address of A's implementation of f()", since there is no explicit seperation between pointers to regular member functions ...
Here is way too much information about member function pointers. There's some stuff about virtual functions under "The Well-Behaved Compilers", although IIRC when I read the article I was skimming that part, since the article is actually about implementing delegates in C++. http://www.codeproject.com/KB/cpp/FastDelega...
1,087,610
1,087,686
Working with imperial units
I'm toying with an application that is, roughly speaking, a sort of modeler application for the building industry. In the future I'd like it to be possible for the user to use both SI units and imperial. From what I understand, it's customary in the US building industry to use fractions of inches when specifying measur...
Take a look at Martin Fowler's Money pattern from Patterns of Enterprise Application Architecture - it is directly applicable to this situation. Recommended reading. Fowler has also posted a short writeup on his site of the Quantity pattern, a more generic version of Money.
1,087,627
1,093,087
How can I target a specific version of the C++ runtime?
We have a very large project mostly written in C# that has some small, but important, components written in C++. We target the RTM of .NET 2.0 as the minimum required version. So far, in order to meet this requirement we've made sure to have only the RTM of .NET 2.0 on our build box so that the C++ pieces link against ...
While I'm pretty sure that Christopher's answer and code sample (thank you, Christopher!) is part of a more elegant solution, we were under the gun to get this out the door and found a very similar, but different, solution. The first step is to create a manifest for the assembly: <assembly xmlns='urn:schemas-microsoft-...
1,087,771
1,087,782
Do I need to synchronize thread access to an int?
I've just written a method that is called by multiple threads simultaneously and I need to keep track of when all the threads have completed. The code uses this pattern: private void RunReport() { _reportsRunning++; try { //code to run the report } finally { _reportsRunning--; } } T...
A ++ operator is not atomic in C# (and I doubt it is guaranteed to be atomic in C++) so yes, your counting is subject to race conditions. Use Interlocked.Increment and .Decrement System.Threading.Interlocked.Increment(ref _reportsRunning); try { ... } finally { System.Threading.Interlocked.Decrement(ref _reports...
1,087,870
1,087,940
Drawing a full screen Quad?
What's wrong with this: pVertexBuffer[0].Position = D3DXVECTOR3(0.0f,0.0f,0.0f); pVertexBuffer[0].TexCoord = D3DXVECTOR2(0.0f,0.0f); pVertexBuffer[1].Position = D3DXVECTOR3(m_ScreenResolutionX,0.0f,0.0f); pVertexBuffer[1].TexCoord = D3DXVECTOR2(1.0f,0.0f); pVertexBuffer[2].Position = D3DXVECTOR3(0.0f,m_ScreenResoluti...
Vertex shaders output vertices in homogenous screenspace coordinates; they are usually screen resolution independent. In other words, you should output coordinates from (-1,-1,0) to (1, 1, 0).
1,087,927
1,088,019
Function that prints something to std::ostream and returns std::ostream?
I want to write a function that outputs something to a ostream that's passed in, and return the stream, like this: std::ostream& MyPrint(int val, std::ostream* out) { *out << val; return *out; } int main(int argc, char** argv){ std::cout << "Value: " << MyPrint(12, &std::cout) << std::endl; return 0; } It...
You can't fix the function. Nothing in the spec requires a compiler to evaluate a function call in an expression in any particular order with respect to some unrelated operator in the same expression. So without changing the calling code, you can't make MyPrint() evaluate after std::cout << "Value: " Left-to-right orde...
1,087,987
1,088,155
C++ operator new, object versions, and the allocation sizes
I have a question about different versions of an object, their sizes, and allocation. The platform is Solaris 8 (and higher). Let's say we have programs A, B, and C that all link to a shared library D. Some class is defined in the library D, let's call it 'classD', and assume the size is 100 bytes. Now, we want to add ...
You are correct the memory size is defined at compile time and applications B/C would be in danger of serious memory corruption problems. There is no way to handle this explicitly at the language level. You need to work with the OS to get the appropriate shared libraries to the application. You need to version your lib...
1,088,226
1,088,255
How do I *not* delete a member in a destructor?
I'd like the destructor of my class to delete the entire object except for one of the members, which is deleted elsewhere. First of all, is this totally unreasonable? Assuming it's not, how do I do this? I thought that created an destructor with an empty body would prevent all the members from being deleted (because...
Short answer: You don't. Longer answer: If the "member" is actually a pointer to some other allocation, you can arrange to not delete the other allocation. But usually, if you allocated the other block in the constructor, you want to delete it in the destructor. Anything else will require careful handling of the "owner...
1,088,290
1,088,295
#define statements within a namespace
If I have a #define statement within a namespace as such: namespace MyNamespace { #define SOME_VALUE 0xDEADBABE } Am I correct in saying that the #define statement is not restricted to the namespace? Is the following the "correct" thing to do? namespace MyNamespace { const unsigned int SOME_VALUE = 0xDEADBABE; } ...
Correct,#define's aren't bound by namespaces. #define is a preprocessor directive - it results in manipulation of the source file prior to being compiled via the compiler. Namespaces are used during the compilation step and the compiler has no insight into the #define's. You should try to avoid the preprocessor as mu...
1,088,520
1,088,722
Are there Windows API binaries for Subversion or do I have to build SVN to call the API from Windows C++?
I want to call a Subversion API from a Visual Studio 2003 C++ project. I know there are threads here, here, here, and here that tell how to get started with C#.NET on Windows (the consensus seems to be SharpSvn, which I've used easily and successfully on another project) but that's not what I want. I've read the chapte...
You need the dev (e.g. svn-win32-1.6.16_dev.zip) package from here. Probably download also the binaries (e.g. svn-win32-1.6.16.zip) of the tools (DLLs are there).
1,088,689
1,088,990
Boost::any and polymorphism
I am using boost::any to store pointers and was wondering if there was a way to extract a polymorphic data type. Here is a simple example of what ideally I'd like to do, but currently doesn't work. struct A {}; struct B : A {}; int main() { boost::any a; a = new B(); boost::any_cast< A* >(a); } This fai...
The other way is to store an A* in the boost::any and then dynamic_cast the output. Something like: int main() { boost::any a = (A*)new A; boost::any b = (A*)new B; A *anObj = boost::any_cast<A*>(a); B *anotherObj = dynamic_cast<B*>(anObj); // <- this is NULL anObj = boost::any_cast<A*>(b); ano...
1,088,821
1,089,200
Keeping C# and C++ classes in sync at runtime?
My application is built in two sections. A C# executable which is the front end UI and a C++ dll which is more the low-level stuff. My application creates and manages many instances of objects, where every C++ object instance has a corresponding C# object instance. What techniques or libraries can I use to ensure that ...
It's not quite clear whether it would solve the problem, but have you considered Managed C++? I have had pretty good success simply compiling my C++ code as Managed C++, then using the managed extensions to create .NET classes that use the underlying C++ data directly. That way, there's only one copy of the data. Proba...
1,089,176
1,089,181
is size_t always unsigned?
As title: is size_t always unsigned, i.e. for size_t x, is x always >= 0 ?
Yes. It's usually defined as something like the following (on 32-bit systems): typedef unsigned int size_t; Reference: C++ Standard Section 18.1 defines size_t is in <cstddef> which is described in C Standard as <stddef.h>. C Standard Section 4.1.5 defines size_t as an unsigned integral type of the result of the sizeo...
1,089,217
1,089,260
Functional programming in C++11, F# style
I've been looking at the new features in C++11 and it really looks like it will be possible to program in a very functional programming style using it. I've gotten use to using the types List, Seq, Array in F# and I see no reason why their members couldn't be ported into some sort of C++11 template. What problems or ...
The biggest problem with trying to program in a functional style in C++ is that it does not support tail recursion. In a functional language you don't have to worry about stack explosion when you tail recurse correctly, but in C++ you always have to worry about that. Therefore, many "functional" type algorithms will ...
1,089,296
2,036,855
Memory leak in Mixed Mode C++/CLR application
I'm having problems with a slow memory leak in my mixed mode C++/CLR .NET application. (It's C++ native static libraries linked into a VS2008 C++/CLR Windows Forms app with the "/clr" compiler setting) Typical behaviour: app starts using 30 MB (private memory). Then leaks memory slowish, say a MB every hour when runnin...
OK I finally found the problem. It was caused by an incorrect setting for /EH (Exception Handling). Basically, with mixed mode .NET apps, you need to make sure all statically linked libs are compiled with /EHa instead of the default /EHs. (The app itself must also be compiled with /EHa, but this is a given - the comp...
1,089,437
1,089,557
Learning C++ from scratch in Visual Studio?
I need to get up to speed with C++ quite quickly (I've never used it previously) - is learning through Visual Studio (i.e. Managed C++) going to be any use? Or will I end up learning the extensions and idiosyncracies of C++ in VS, rather then the language itself? If learning in VS is not recommended, what platform / ID...
Visual Studio (or the free version, Visual C++ Express) is a perfectly fine choice on Windows. On Linux, you'll probably end up using GCC. Both are fine compilers. Visual C++ supports both "real" native C++ and C++/CLI, the managed .NET version, so if you want to learn C++, simply create a regular C++ project. If you'r...
1,089,490
1,090,733
Eclipse CDT: How to reference 3rd party includes via a Relative path
I'm new to Eclipse-CDT, setting up a new project for the first time. I'm trying to reference Boost without hardcoding an absolute path. I've put boost in my workspace folder, e.g. /home/user/workspace/boost_1_39_0 I was then hoping to add an include directory pointing to that folder relative to the workspace, but Eclip...
When adding an include file path in the CDT project (Project Properties/C/C++ General/Paths and Symbols), there are 3 buttons to browse for a location: Variables... Workspace... File system... If you press the Workspace... button, the path will be relative to the workspace/project. If you select the Variables... but...
1,089,679
1,089,711
Designing a class architecture for network messages
I have client/server applications and a very simple protocol for communication. More precisely, it's a set of commands a server sends and a set of requests a client can make. The idea is as follows: When a command is made by the server, a client has to execute it. When a request is made, server checks permissions and i...
I think the problem in your design is that you tried to cram too many functionality into one class. For example, the part about constructing/parsing messages to contain numeric data or string (i.e. serialization) should be separate from the underlying connection logic. Check out Boost.Serialization if you are allowed ...
1,089,828
1,089,847
Same Header File for both DLL and Static Library
So the common (at least VS 2005 states) way to define exports/imports for a DLL is: #ifdef MY_EXPORTS #define MY_API __declspec(dllexport) #else #define MY_API __declspec(dllimport) #endif class MY_API MyClass { ... }; This works great if I'm just building my code as a DLL. However, I want to have the option of u...
Nothing. Leave it as #define MY_API and all instances of MY_API will simply vanish. You can add new build configurations, such as Debug - DLL and Release - DLL that mimic the others except they #define DLL_CONFIG. To clone a configuration, get to the configuration manager (like the drop down of the Debug/Release list b...
1,090,075
1,090,344
How do you farm out variables to persistent data?
Basically, I want to have my program retrieve various variables from the hard drive disk for use in the program. I guess, before asking for details, I should verify that is even possible. Is it? If it is, what is the best way? I've seen the use of .ini files, but I don't know how to retrieve data specifically from .ini...
The first questions you need to address are the who and the why. Your options on the how will follow from those. So who (or what) will be accessing the data? If it is just the program itself then you can store the data however you want - binary file, xml, database, ini file, whatever. However if the data needs to be...
1,090,261
1,090,295
Get the graphics card model?
I was wondering how I can get the graphics card model/brand from code particularly from DirectX 9.0c (from within C++ code).
At runtime, you can query the device model and vendor: In OpenGL, use the command glGetString(GL_VENDOR) or GL_RENDERER or GL_VERSION to get the information you're after. In DirectX 9, it appears the info is in the Microsoft config system, and is queried from the device database. It's section 3 of this document, wh...
1,090,406
1,130,846
Parameters to watch while running an application on linux?
I am running an application overnight on my Linux xscale device. I am looking for things,which would increase with the increase in the amount of time of running. One thing,is the memory. If you observe the memory on the xscale systems,the free memory would start decreasing,but you will see an increase in the cached mem...
If the application is developed by you, i would recommend the following heap profiler to use for getting more deeper details. http://code.google.com/p/google-perftools/wiki/GooglePerformanceTools
1,090,428
1,090,537
How to output array of doubles to hard drive?
I would like to know how to output an array of doubles to the hard drive. edit: for further clarification. I would like to output it to a file on the hard drive (I/O functions). Preferably in a file format that can be quickly translated back into an array of doubles in another program. It would also be nice if it was...
Hey... so you want to do it in a single write/read, well its not too hard, the following code should work fine, maybe need some extra error checking but the trial case was successful: #include <string> #include <fstream> #include <iostream> bool saveArray( const double* pdata, size_t length, const std::string& file_pa...
1,090,484
1,090,595
is this possible in C++?
to create an instance of another class from a class even if the class I want to have an instance of is declared next of the class I am creating an instance from. Just like in C# and Java. Thank you
Sure. You just need a forward declaration. Something like this works just fine: #include <iostream> class B; class A { public: void hello( B &b ); void meow(); }; class B { public: void hello( A &a ); void woof(); }; void A::hello( B &b ) { b.woof(); } void A::meow() { std::cout << "Meow!" << std:...
1,090,755
1,090,914
Using v-table thunks to chain procedure calls
I was reading some articles on net regarding Vtable thunks and I read somewhere that thunks can be used to hook /chain procedures calls. Is it achievable? Does anyone know how that works , also I am not able to find good resource explaining thunks. Any suggestions for that?
Implementing a raw thunk in the style of v-table thunks is a last resort. Whatever you need to accomplish can most likely be achieved with a wrapper function, and it will be much less painful. In general, a thunk does the following: Fix up the input parameters (e.g., convert to a different format) Call the real imple...
1,090,782
1,090,794
Different address with map indexes vs content of map index
In the code below, why it is that when I take the address of a map index (which contains a list) and I take the address of the list itself, they both have different values. See the code below for clarification. #include <iostream> #include <list> #include <map> using namespace std; int main() { list<char> listA; ...
You get different addresses because you create a copy of the original list and assing it to the map structure. Consider using pointers (map< int, list<char>* >).
1,090,819
1,090,850
Template class inside class template in c++
noob here still experimenting with templates. Trying to write a message processing class template template <typename T> class MessageProcessor { //constructor, destructor defined //Code using t_ and other functions foo( void ) { //More code in a perfectly fine method } private: T *t_ }; All defined in a hea...
Your member function 'foo' needs a return type and you need to use the keyword 'template' when you use member templates in dependent expressions (expressions whose meanings rely directly or indirectly on a generic template parameter) t_->template getMessageSender<MessageType>(); // ok t_->getMessageSender<MessageType>...
1,090,884
1,091,183
Get the size of jpeg from memory (converted using GDI++)
This is my first post here. I have a problem. I need to take a sceenshot of the desktop, convert it to jpeg, store it in a buffer and then manipulate it and send it over the internet. I have written the code for doing this with GetDC....and GDI+ for converting the HBITMAP to jpeg. The problem I am having now is that I ...
According to the CreateStreamOnHGlobal documentation, your use of it is incorrent. Quote: The current contents of the memory block are undisturbed by the creation of the new stream object. Thus, you can use this function to open an existing stream in memory. The initial size of the stream is the size of the memory ...
1,090,901
1,090,916
c++ array value matching variable
I would like to see if a value equals any of the values in an array. like this Beginning of function(here I give Val differnt values with for loops...) for (i=0;i<array_size;i++) if (Val==array[i]) do something else do something else if non of the above values matched val... ...
Use a flag to indicate whether the condition was satisfied at least once: bool hasMatch = false; for (i=0;i< array_size;i++) { if (Val==array[i]) { // do something hasMatch = true; } } if( !hasMatch ) { // do whatever else } This will invoke the "do something" for every ...
1,090,917
1,091,037
Does anyone know a good/easy/free/open 3d modeling program?
Does anyone know of an easy 3D modeling application like sketchup but is opensource? I don't have time for learning blender ( guess I never will ): and I'm a fan of having multiple small tools do their part of the job ( first cut the plank using the saw the nail it using the hammer :) ). Edit: I also might need to do ...
Blender is the only decent one I know, why not taking a look in Youtube/Vimeo on some tutorials? There are plenty and it's quite fast to scrap with Video tutorials.
1,090,956
1,090,982
What is CString::StringTraits? What is it for? There seems to be no documentation
Using Visual Studio 2005 As per the title; MSDN and google can't tell me, I'm hoping it'll let me know if the contained string contains Unicode characters or not - but that's a different problem!
I used traits for custom defined comparison function.eg Currently default comparison implementation of two CStrings is case insensitive. If you want to do case sensitive comparison between two strings then you can define that behavior in traits. I am not sure if there are any other use cases.
1,091,336
1,091,356
Date manipulation in C++
I am sure that this kind of questions must have been asked before, but failed to find anything by searching this site. My apologies in advance if I missed any similar questions. Is there anything in C++ that just does date manipulation at all? I am aware of SYSTEMTIME structure (it is the structure returned when you d...
You should check out Boost::DateTime. But to answer your question there is no date time 'handling' as such in C++
1,091,557
1,099,581
WndProc hook does not receive WM_COMMAND from menus
For tracking user activity, I am using a Windows Hook for the main application thread, and monitor (among others) WM_COMMAND messages. I receive them as expected from dialog buttons, toolbar buttons, accelerators and popup menus, but I do NOT receive them from the main menu. Strangely enough, Spy++ does show the main w...
Menu commands are posted, not sent (yes, the documentation is rather unclear on this - but Spy++ tells the truth). And WH_CALLWNDPROC hooks only catch sent messages. You should be able to use a WH_GETMESSAGE hook to intercept posted messages. You'll need both if you want to handle both forms of WM_COMMAND.
1,091,602
1,091,647
C++ Changing a class in a dll where a pointer to that class is returned to other dlls
Horrible title I know, horrible question too. I'm working with a bit of software where a dll returns a ptr to an internal class. Other dlls (calling dlls) then use this pointer to call methods of that class directly: //dll 1 internalclass m_class; internalclass* getInternalObject() { return &m_class; } //dll 2 int...
The client dll's 'learn' the actual address of the class' functions at load-time by looking at the export table of the serving dll. So as long as the export table stays compatible, no harm is done. Compatibility will be broken when your class has a virtual function table, and the functions in it change order. It will...
1,091,643
1,091,672
C++ operators and arguments
Let's say I have a class Point: class Point { int x, y; public: Point& operator+=(const Point &p) { x=p.x; y=p.y; return *this; } }; Why can I not call this as such: Point p1; p1 += Point(10,10); And is there any way to do this, while still having a reference as the argument?
Here's the code you need: class Point { int x,y; public: Point(int x=0,int y=0) : x(x), y(y) {} Point& operator+=(const Point&p) {x+=p.x;y+=p.y;return *this;} }; As Konrad pointed out, you need a constructor. Also you need to explicitly perform the additions inside your operator overload.
1,091,927
1,091,941
When does the space occupied by a variable get deallocated in c++?
Doesn't the space occupied by a variable get deallocated as soon as the control is returned from the function?? I thought it got deallocated. Here I have written a function which is working fine even after returning a local reference of an array from function CoinDenom,Using it to print the result of minimum number of ...
The contents of the memory taken by local variables is undefined after the function returns, but in practice it'll stay unchanged until something actively changes it. If you change your code to do some significant work between populating that memory and then using it, you'll see it fail.
1,092,045
1,092,069
WriteConsole() weird characters?
I use this snippet to create a console from inside a dll. That dll gets loaded in a game. CODE SNIPPET The console window creates fine. But when i write stuff to it, i just get stuff like "???D??". I know i have to use the printf() syntax. So i use wprintf("%s", "test"); Any pointers?
Try using: wprintf(L"%s", "test"); as wprintf takes an wide character string as input Edit: Based on the fact that the behaviour of %s and %S changes when used in wprintf what about: wprintf("%s", L"test"); The %s in wprintf expects a wide character string this L"test" is. I removed the "L" on the format parameter si...
1,092,331
1,092,384
Overloading += in c++
If I've overloaded operator+ and operator= do I still need to overload operator+= for something like this to work: MyClass mc1, mc2; mc1 += mc2;
operator+= is not a composite of + and =, therefore you do need to overload it explicitly, since compiler do not know to build puzzles for you. but still you do able to benefit from already defined/overloaded operators, by using them inside operator+=.
1,092,561
1,092,572
Is returning a std::list costly?
I was wondering if returning a list, instead of returning a pointer to one, was costly in term of performance because if I recall, a list doesn't have a lot of attributes (isn't it something like 3 pointers? One for the current position, one for the beginning and one for the end?).
If you return a std::list by value it won't just copy the list head, it will copy one list node per item in the list. So yes, for a large list it is costly. If the list is built in the function which is returning it, then you might be able to benefit from the named return value optimisation, to avoid an unnecessary cop...
1,092,714
1,092,724
conversion precedence in c++
I have the following code: Some functions: A::A(int i_a) {cout<<"int Ctor\n";} //conversion constructor void h(double d) {cout<<"double param\n";} //f1 void h(A a) {cout<<"A param\n";} //f2 In the main function: h(1); The function that h(1) calls is f1. My question is why does it choose to c...
When overload resolution is performed to select the best candidate out of all viable overloads - the compiler ranks all the conversion sequences for each argument for each candidate. For a function to win (be selected as the best candidate), its conversion ranks for each argument have to be better than or equal to eve...
1,092,777
1,093,004
How do I read the windows registry (Default) value using QSettings?
I want to read the registry to find the current PowerPoint version. However this just returns Zero: QSettings settings("HKEY_CLASSES_ROOT\\PowerPoint.Application\\CurrVer", QSettings::NativeFormat); QString sReturnedValue = settings.value("(Default)", "0").toString(); Any suggestions as to how I ge...
Ok, just figured it out. Whilst regedit shows it as (Default) you just read it as Default. QString sReturnedValue = settings.value( "Default", "0" ).toString();
1,092,972
1,092,982
casting producing const objects in c++
Would it be correct to say that whenever casting is used, the resulting object is a const object? ...And therefore can only be used as an argument to a function if that function accepts it as a const object? e.g. class C1 { public: C1(int i=7, double d = 2.5){}; }; void f(C1& c) {}; int main(){ f(8); ret...
Usually when an object of a certain type is converted to an object of another type (a non-reference type), a temporary object is created (not a const object). A temporary object (invisible, nameless, rvalue) can only bind (in C++98/03) to references that are const (except for the temporary known as the 'exception obje...
1,093,813
1,093,837
What is the most dangerous feature of C++?
I've heard lots of times that phrase of Bjarne Stroustrup "C++ makes it harder to shoot yourself in the foot; but when you do, it takes off the whole leg" and I don't really know if it is as terrible as it sounds. What's the worst thing that has ever happened to you (or more properly, to your software) while programmin...
delete [] array; can sometimes become delete array; in the hands of someone who doesn't know. Tracking that bug down can suck horribly, and doesn't happen when you're doing malloc and free.
1,093,857
1,093,945
AccessViolationException when string is too long (C++)
I asked a similar question a couple of days ago, but I'm looking for more insight. I'm getting an AccessViolationException when I add a string to my program: Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. a...
I assume these strings are global variables. Are you trying to access these strings from the constructor of another global variable (or from some method that is called before main is entered)? If this is the case you are suffering from the probelem that global variable initialization order is undefined across multipl...
1,093,883
1,099,673
Google Performance Tools (profiler) tutorial
I just downloaded and built the libraries/executables of Google Performance Tools. Before I run the CPU profiler on the application that I want to investigate, I want to learn how to use the tools properly perhaps on a sample application. What would be a good example to run the Google CPU profiler on? Thanks in advance...
The following paragraph appears in the README.windows file distributed with perftools 1.3: The heap-profiler has had a preliminary port to Windows. It has not been well tested, and probably does not work at all when Frame Pointer Optimization (FPO) is enabled -- that is, in release mode. The other features of perfto...
1,093,903
1,094,906
What is the destruction order of the View/Doc/Frame in a CMultiDocTemplate?
I'm working in an MDI application that has a pointer to a document's frame object. Other threads are calling PostMessage using the pointer. During shutdown, the threads continue trying to post messages to the frame while the frame is being destructed. Does anyone know the destruction order of the multiple documents in ...
If your threads are posting messages only to frame object you could notify these threads about frame's destruction by using CEvent in frame's WM_CLOSE handler. In that case I don't see why do you need to know destruction order?
1,094,039
1,094,081
When might multiple inheritance be the only reasonable solution?
To be clear, I'm not asking if/why multiple inheritance is good or bad. I've heard a lot of arguments from both sides of that debate. I'm wondering if there is any kind of design problem or scenario in C++ in which multiple inheritance is either the only way to accomplish something, or at least is the most optimal way ...
You can't do policy-based design without multiple inheritance. So if policy-based design is the most elegant way to solve your problem, than that means you need multiple inheritance to solve your problem, over all other options. Multiple-inheritance can be very useful if it's not misused (like everything, in any langua...
1,094,046
1,094,078
Using auto and decltype in C++11
I'm trying to learn the currently accepted features of c++11 and I'm having trouble with auto and decltype. As a learning exercise I'm extending the std class list with some generic functions. template<class _Ty, class _Ax = allocator<_Ty>> class FList : public std::list<_Ty, _Ax> { public: void iter(const functio...
Deriving from std::list or other std:: containers is discouraged. Write your operations as free functions so they can work on any standard container via iterators. Do you mean "define map without using a template function"? You should be able to use the result_type member type of std::function to get the type it return...
1,094,066
1,094,071
Static declarations are not considered for a function call if the function is not qualified
"painting/qpathclipper.cpp", line 1643.30: 1540-0274 (S) The name lookup for "fuzzyCompare" did not find a declaration. "painting/qpathclipper.cpp", line 1643.30: 1540-1292 (I) Static declarations are not considered for a function call if the function is not qualified. I'm trying to compile Qt 4.5.0 on xlC 9.0.0.4a, ...
The "static" keyword is in error here, fuzzyCompare should be declared just bool fuzzyCompare(qreal a, qreal b)
1,094,215
1,094,245
Faster to malloc multiple small times or few large times?
When using malloc to allocate memory, is it generally quicker to do multiple mallocs of smaller chunks of data or fewer mallocs of larger chunks of data? For example, say you are working with an image file that has black pixels and white pixels. You are iterating through the pixels and want to save the x and y positi...
It depends: Multiple small times means multiple times, which is slower There may be a special/fast implementation for small allocations. If I cared, I'd measure it! If I really cared a lot, and couldn't guess, then I might implement both, and measure at run-time on the target machine, and adapt accordingly. In genera...
1,094,276
1,094,382
Strange memory problem of Loki::Singleton, Loki::SmartPtr, and std::vector
I had encountered a problem while using Loki::Singleton, Loki::SmartPtr, and std::vector under VC express 2008. Following is my source. #include <iostream> #include <vector> #include <loki/Singleton.h> #include <loki/SmartPtr.h> class Foo { public: std::vector<Loki::SmartPtr<Foo>> children ; void add() { ...
As you're using VC, you should be able to run your code in debug mode, step by stp (F10,F11) to see where it breaks. Anyway, looking at the Loki singleton code, it seems that the error comes from the assert in SingletonHolder::DestroySingleton() : SingletonHolder<T, CreationPolicy, L, M, X>::DestroySingleton() 00837 ...
1,094,387
1,094,421
Why does removing const give me linker errors?
I have a global variable: const std::string whiteSpaceBeforeLeadingCmntOption = "WhiteSpaceBeforeLeadingComment"; When I remove the const on this variable declaration, I get many occurrences of the following linker error: error LNK2005: "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<c...
This works when you have const in the .h, since const implies static so you can have the same variable in multiple compilands. By removing const on a variable defined in a .h file, you are creating multiple instances with the same identifier within the same program. If you need to remove const, in the .h, you could do:...
1,094,532
1,094,560
Problem in overriding malloc
I am trying to override malloc by doing this. #define malloc(X) my_malloc((X)) void* my_malloc(size_t size) { void *p = malloc(size); printf ("Allocated = %s, %s, %s, %x\n",__FILE__, __LINE__, __FUNCTION__, p); return p; } However, this is indefinitely calling my_malloc recursively (because of malloc cal...
Problem solved: void* my_malloc(size_t size, const char *file, int line, const char *func) { void *p = malloc(size); printf ("Allocated = %s, %i, %s, %p[%li]\n", file, line, func, p, size); return p; } #define malloc(X) my_malloc( X, __FILE__, __LINE__, __FUNCTION__)
1,094,865
1,095,170
const std::map<boost::tuples::tuple, std::string>?
// BOOST Includes #include <boost/assign.hpp> // Boost::Assign #include <boost/assign/list_of.hpp> // Boost::Assign::List_Of #include <boost/assign/std/map.hpp> // Boost::Assign::Map_List_Of #include <boost/tuple/tuple.hpp> // Boost::Tuples // STD Includes #include <map> #include <vector> #in...
I tried this, and it fails because the keys of the map need to be comparable (with std::less, thus there needs to be an operator< defined). boost::tuple's comparison operators are defined in the header boost/tuple/tuple_comparison.hpp. Having included that, this code works fine: #include <boost/assign/list_of.hpp> #in...
1,094,918
1,096,211
Performance difference in for loop condition?
I have a simple question that I am posing mostly for my curiousity. What are the differences between these two lines of code? (in C++) for(int i = 0; i < N, N > 0; i++) for(int i = 0; i < N && N > 0; i++) The selection of the conditions is completely arbitrary, I'm just interested in the differences between , and &&....
Although it looks like it, for(int i = 0; i < N, N > 0; i++) and for(int i = 0; i < N && N > 0; i++) are not equivalent. Here is the proof. int main(int argc, char* argv[]) { int N = 10; int i = 5; int val = (N, i); cout << val << endl; } Result: 5 Which means that the when determining when the loop will...
1,095,225
1,095,233
Exception slicing - is this due to generated copy constructor?
I've just fixed a very subtle bug in our code, caused by slicing of an exception, and I now want to make sure I understand exactly what was happening. Here's our base exception class, a derived class, and relevant functions: class Exception { public: // construction Exception(int code, const char* format="", ...); ...
When you throw an object, you're actually throwing a copy of the object, not the original. Think about it - the original object is on the stack, but the stack is being unwound and invalidated. I believe this is part of the standard, but I don't have a copy to reference. The type of exception being thrown in the catch b...
1,095,298
1,095,321
GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'
I'm setting up a C++ project, on Ubuntu x64, using Eclipse-CDT. I'm basically doing a hello world and linking to a commerical 3rd party library. I've included the header files, linked to their libraries, but I still get linker errors. Are there some possible problems here other than the obvious (e.g. I am 99% sure I'...
Assuming those methods are in one of the libs it looks like an ordering problem. When linking libraries into an executable they are done in the order they are declared. Also the linker will only take the methods/functions required to resolve currently outstanding dependencies. If a subsequent library then uses methods/...
1,095,378
1,096,487
How do I destruct data associated with an object after the object no longer exists?
I'm creating a class (say, C) that associates data (say, D) with an object (say, O). When O is destructed, O will notify C that it soon will no longer exist :( ... Later, when C feels it is the right time, C will let go of what belonged to O, namely D. If D can be any type of object, what's the best way for C to be abl...
The question is rather vague on the requirements, so it's hard to give a good concrete answer. I hope the following helps. If you want the data to disappear immediately when its owner dies, have the owner delete it (and notify C if the C instances need to know). If you want C to do the deletion at its leisure, your s...