question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
3,516,401
3,517,328
Should a C++ embedded application use a common header with typedefs for built-in C++ types?
It's common practice where I work to avoid directly using built-in types and instead include a standardtypes.h that has items like: // \Common\standardtypes.h typedef double Float64_T; typedef int SInt32_T; Almost all components and source files become dependent on this header, but some peop...
The biggest problem with this approach is that so many developers do it that if you use a third-party library you are likely to end up with a symbol name conflict, or multiple names for the same types. It would be wise where necessary to stick to the standard implementation provided by C99's stdint.h. If your compiler...
3,516,746
3,516,803
Why I'm allowed to assign a new address to a vector containing constant pointers?
I think the title is clear on explaining my problem.... consider the following snippet: class Critter { int m_Age; }; int main() { vector<Critter* const> critters; for(int i = 0; i < 10; ++i) critters.push_back(new Critter()); critters[2] = new Critter(); return 0; } Shouldn't the line c...
Actually this line should be illegal (even given #include <vector> and using std::vector;): vector<Critter* const> critters; Because it is a requirement for a type to be used in a container to be assignable and anything that is const clearly isn't.
3,516,889
3,517,039
[C++]Covariant return types
I have a VectorN class, and a Vector3 class inherited from VectorN (which can handle cross products for example). I have trouble determining the return types of the different operators. Example: class VectorN { public: VectorN(){}; virtual VectorN operator*(const double& d) {.....}; std::vector<double> coords;...
You need a re-design. First, prefer free-functions over member-functions. The only member functions you should have are the ones that need access to privates. Start with this combo: class VectorN { public: virtual VectorN& operator*=(double d) { /* ... */ return *this; }; }; class Vector3 ...
3,516,909
3,517,798
How to get a float from a char* in C++?
I am relatively new to C++, coming from the happy-go-lucky world of Python. I decided to write a set of functions to find the mean, median, mode, and range of a set of numbers. To aid in the calculation of the median, I decided to make l2g (least to greatest) and g2l (greatest to least). I understand I will only be usi...
If you lift your restriction on using libraries, both tasks are very simple. Converting char* to float is easy with Boost.lexical_cast (See http://www.boost.org/doc/libs/1_43_0/libs/conversion/lexical_cast.htm). It provides type-safe conversions between any two types, so long as they define the "stream" operators (<< ...
3,516,953
3,516,997
Variadic Macro with 3 terms
I am trying to understand a C++ code that reads a dll explicitly. Does any one know how the line #define LFE_API(name) LFE_##name name below actually works? I understand #define LFE_API(name) LFE_##name but get confused about the last "name". struct Interface { # ifdef LFE_API # error You can't defi...
Since the first part of the macro (LFE_##name) just concatenates both parts, a call to LFE_API is creating a variable named name with the type LFE##name, such as: LFE_API(Init) expands to LFE_Init Init;
3,516,989
3,517,067
Question about libc_write()
I'm trying to determine what libc_write does exactly. I'm executing a binary on a processor simulator I designed in c++ and the program being run has jumped to the function call libc_write(). Now, there are 2 different types of write functions - write() which writes one large buffer to a stream, possibly comprised of...
libc_write is the LIBC's internal alias for write(3). Since writev(3) boils down to a separate syscall, you'd see libc_writev if you were calling it. A side note - make Google Code Search your friend :) Edit: (3) means section 3 of the manual: 1. General Commands 2. System Calls 3. Subroutines 4. Special Files 5. File...
3,517,068
3,517,582
Windows Vista+ Memory Problem with IFileOpenDialog and large stack
I have experienced a strange problem in windows vista and above. When I use the IFileOpenDialog with a large stack, the amount of memory remaining after showing the dialog drops by about a gigabyte. #include <windows.h> #include <Shobjidl.h> #include <iostream> void memGrab(char *); int main(int argc, char **argv){ ...
I don't know exactly what's going on in your scenario. But I have seen the File Open Dialog cause other memory trouble before. When that dialog is invoked, a lot of things may get loaded into your process. In particular, shell extensions that appear in Windows Explorer also get loaded in with the File Open Dialog. That...
3,517,174
3,521,647
How to check if a datatype is "defined" with typedef
I faced this problem today and just wondering how to check if a new type defined with typedef is really defined somewhere. To give an example, I started using Xerces-c3 library that I built from source code and wrote a xml2text converter. But I couldnt find Xerces-c3 port on fbsd so installed Xerces-c2 library. When I...
There is no way to directly recognise whether a typedef is defined. The most popular workaround is to check if the file that defines the typedef also defines a macro. e.g. The type "struct tm" is defined in time.h. If you look at your copy of time.h, there will be a macro defined at the top. In the VC2010 version...
3,517,726
3,517,746
What is wrong with using goto?
Possible Duplicates: Why is it bad to use goto? GOTO still considered harmful? I was ramdomming through xkcd and saw this one (if also read some negative texts about them some years ago): What is actually wrong with it? Why are goto's even possible in C++ then? Why should I not use them?
Because they lead to spaghetti code. In the past, programming languages didn't have while loops, if statements, etc., and programmers used goto to make up the logic of their programs. It lead to an unmaintainable mess. That's why the CS gods created methods, conditionals and loops. Structured programming was a revoluti...
3,517,795
3,517,880
Is there a C++ container with reasonable random access that never calls the element type's copy constructor?
I need a container that implements the following API (and need not implement anything else): class C<T> { C(); T& operator[](int); // must have reasonably sane time constant // expand the container by default constructing elements in place. void resize(int); // only way anything is added. void clear(); ...
I'm pretty sure that the answer here is a rather emphatic "No". By your definition, resize() should allocate new storage and initialize with the default constructor if I am reading this correctly. Then you would manipulate the objects by indexing into the collection and manipulating the reference instead of "insertin...
3,517,975
3,518,046
c++ use new to Image gdi+
im using gdi+ to output my images. i tried to use the keyword new but it didn't work. shot(L"image name") = new Image; that didn't work any other ideas how to make it work
Something like this seems a lot more likely: Image *image_object = new Image(L"Image Name"); Except that there's a pretty decent chance you don't want to allocate the Image object dynamically at all -- unless you really do, you generally want to just define an object with automatic storage duration: Image image_object...
3,517,991
3,518,204
Why do STL containers use copying to populate in resize?
All the STL containers that implement resize use copies to populate the new elements even if the source of the copy is a default constructed object? Why is it done this way? I see no advantage and some cost. As context, I ran across this while looking for a random access container for elements that can't be copied.
It saves on complexity. We certainly need the copy-construction case, and default-construction can be modeled as replicating a default-constructed object. The performance penalty is negligible. Writing zeroes is about the same speed as copying zeroes. The compatibility penalty is nil since all containers require copyab...
3,518,214
3,518,234
c++ special variable name
When I create variable I just put the a name for it, but can I create the name of the variable like this: int var+1= 1; So basically that should be: int var1=1; I know I can't use the + sign to do that but is there way to do it? EDIT int g=1; string hello+g = "sdljfsdl"; // So hello+g will be hello1 So it is like ...
You can do this with macros, but you really shouldn't need dynamic variable names. It sounds like this sort of problem can be solved with an array: int vars[5]; vars[0] = 3; vars[1] = 4; // etc.
3,518,433
3,518,458
c++ display more than one image gid+
im trying to display image when left mouse button is down. i can display the image but if the left mouse button is down again than the older image would be deleted. here is my code display image function { Graphics graphics(hdc); POINT pt; GetCursorPos(&pt); ScreenToClient(hWnd, &pt); Image shot(L"...
You need to store a collection (array / vector etc.) of coordinates that is added to each time the mouse button is pressed - and then when rendering in WM_PAINT, draw an image at each of these locations.
3,518,542
3,518,553
What is the difference between this.value and this->value?
I just started studying C++, and I met this new guy: ->. I was wondering if it means something different than (.) or not, and if it does, what it is. Can you answer that? I looked for it a bit, but I didn´t find anything to answer my question.
If you start with a pointer to an object, use ->. If you start with a reference or direct value of class type, use .. If you use the wrong one, the compiler should give a pretty clear error message. a->b is defined to be synonymous with (*a).b. Except in the case of operator overloading, in which case -> and * must be ...
3,518,605
3,518,790
What's the difference between pipe and socket?
Both can be used for communicating between different processes, what's the difference?
Windows has two kinds of pipes: anonymous pipes and named pipes. Anonymous pipes correspond (fairly) closely to Unix pipes -- typical usage is for a parent process to set them up to be inherited by a child process, often connected to the standard input, output and/or error streams of the child. At one time, anonymous p...
3,518,703
3,518,771
Why do thread creation methods take an argument?
All thread create methods like pthread_create() or CreateThread() in Windows expect the caller to provide a pointer to the arg for the thread. Isn't this inherently unsafe? This can work 'safely' only if the arg is in the heap, and then again creating a heap variable adds to the overhead of cleaning the allocated mem...
Context. Many C APIs provide an extra void * argument so that you can pass context through third party APIs. Typically you might pack some information into a struct and point this variable at the struct, so that when the thread initializes and begins executing it has more information than the particular function that i...
3,518,809
3,518,837
About using CreateFile to open a pipe in windows:
Quoted here: hPipe = CreateFile( lpszPipename, // pipe name GENERIC_READ | // read and write access GENERIC_WRITE, 0, // no sharing NULL, // default security attributes OPEN_EXISTING, // opens existing pipe 0, /...
A pipe name must start with \\.\pipe\ (or more generally, \\servername\pipe\). A file on a hard drive never will have that prefix, so you just need to ensure that the name has that prefix. Alternatively, you can use CallNamedPipe, which (I'm pretty sure) will fail if passed a name of something other than a named pipe. ...
3,518,853
3,531,349
What are use cases for booster::noncopyable?
First: is it boost::noncopyable or booster::noncopyable. I have seen both in different places. Why would one want to make a class noncopyable? Can you give some sample use cases?
I find it useful whenever you have a class that has a pointer as a member variable which that class owns (ie is responsible for destroying). Unless you're using shared_ptr<> or some other reference-counted smart pointer, you can't safely copy or assign the class, because in the destructor you will want to delete the p...
3,518,929
3,518,940
How to Convert int to char*(string) in C++?
SOCKET lhSocket; int iResult; lhSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); char *sendbuf = "this is a test"; iResult = send(lhSocket, sendbuf, (int)strlen(sendbuf), 0 ); printf("Bytes Sent: %ld\n", iResult); I have client and Server program using sockets in C++ now i send a buffer it is received...
sendbuf is the string which you are sending. Print sendbuf instead: printf("Bytes Sent: %s\n", sendbuf);
3,519,282
3,525,172
Why is this ambiguity here?
Consider I have the following minimal code: #include <boost/type_traits.hpp> template<typename ptr_t> struct TData { typedef typename boost::remove_extent<ptr_t>::type value_type; ptr_t data; value_type & operator [] ( size_t id ) { return data[id]; } operator ptr_t & () { return data; } }; int main(...
It's actually quite straight forward. For t[1], overload resolution has these candidates: Candidate 1 (builtin: 13.6/13) (T being some arbitrary object type): Parameter list: (T*, ptrdiff_t) Candidate 2 (your operator) Parameter list: (TData<float[100][100]>&, something unsigned) The argument list is given by 13.3....
3,519,330
3,519,454
What's the fastest C++ linker for Windows platform?
Apparently the speed of the C++ linker in Visual Studio 2010 hasn't improved that much (about 25% in our case). This means that we're still stuck with linking times between 30 seconds and two minutes. Surely there are linkers out there that perform better? Does anyone have experience with switching to another linker or...
You may well find a faster linker but, unless it's ten times as fast and I'm linking thirty times an hour, I think I'd prefer to use the tools that Microsoft has tested with. I would rather have relatively slow link times than potentially unstable software. And you kids are spoilt nowadays. In my day, we had to submit ...
3,519,798
3,519,866
get weird cursor position
Ok so I'm working with vectors today yaya! well im also working with getcursorpos() and i get weird results. here is the code: VOID fRegularShot(HDC hdc, HWND hWnd) { Graphics graphics(hdc); Image shot(L"RegularShots.png"); long index=0; while(index<=(long)pRegularShots.size()) { index+=2; ...
GetCursorPos returns cursor position in screen coordinates. Use ScreenToClient(hWnd, ...) to convert it to window client coordinates. GetCursorPos(&pt); ScreenToClient(hWnd, &pt); You can work also without GetCursorPos function. When WM_LBUTTONDOWN notification is received, lParam contains window client mouse coordin...
3,519,853
3,519,878
runtime type comparison
I need to find the type of object pointed by pointer. Code is as below. //pWindow is pointer to either base Window object or derived Window objects like //Window_Derived. const char* windowName = typeid(*pWindow).name(); if(strcmp(windowName, typeid(Window).name()) == 0) { // ... } else if(strcmp(windowName, typeid(...
First of all use a higher level construct for strings like std::string. Second, if you need to check the type of the window your design is wrong. Use the Liskov substitution principle to design correctly. It basically means that any of the derived Window objects can be replaced with it's super class. This can only happ...
3,520,153
3,520,410
Templated Matrix Class Not Generating Functions Correctly
Basically, I have a matrix class like this (with a lot of operator overloads and other functions removed): template < uint32 TRows, uint32 TCols > struct Matrix { float values[TRows][TCols]; inline explicit Matrix() { } inline Matrix<TRows - 1, TCols - 1> minor(const uint32 col, const uint...
Matrix::minor(0, j) returns a matrix of size (N-1, N-1). Calling for its determinant makes the process recursive, which means you are generating a minor (and determinant method) for all p integers, starting from N down to ... -infinity ? Have you added a specialization for the case where N==1 or N==0 ? You have to make...
3,520,205
3,520,701
should you be able to define a friend within a class?
the following code compiles fine under gcc: class vec3 { private: float data[3]; public: vec3(float x, float y, float z) { data[0] = x; data[1] = y; data[2] = z; } void operator =(const vec3 &v) { data[0] = v.data[0]; data[1] = v.data[1]; data[2] = v.data[2]; } friend vec3 ...
Yes.. According to the standard docs, 11.4 Friends - 6 A function can be defined in a friend declaration of a class if and only if the class is a non-local class (9.8), the function name is unqualified, and the function has namespace scope. Example: class M { friend void f() { } // definition of global f, a friend of...
3,520,931
3,521,011
Receiving assert failure on Reference Call
(Disclaimer: I have removed the Qt tag in case the problem is in my syntax / understanding of the references involved here) I have a foreach loop with an object Member. When I enumerate through the list and try to access a member field, the debugger stops and I get a message: Stopped: 'signal-received' - The assert fai...
If mem is not null it could still be the case that the pointer is dangling i.e. the Member it was pointing to has been deleted. If Member inherits from QObject then you could temporarily change your QList<Member*> that is stored in ml (assuming that's what's stored in ml) into a QList< QPointer<Member> >. If you then g...
3,521,006
3,521,059
how to know the existance of NAN value in a double variable?
i have issue with comparing NAN value in C++, Visualstudio. I need to handle Division by Zero in my code. if i get division by zero, i want to assign NAN to the result. Check at later point of time, whether result has NAN. But NAN comparision is failing at later point of time, even though i assign quiet_Nan() as below....
I don't think the current standard library provides any is_nan implementation you will need to use a 3rd party lib or roll your own floating point values can be compared for equality, it is just rarely useful, but this is a one of those places where it is useful, what you want is something like: template <T> bool is_na...
3,521,054
3,521,068
Is it possible to get the pointer the continous memory fragment in a std::vector<char> in C++?
I moved my code to use std::vector<char> instead of char *mem = malloc(...) but now I am facing a problem that I can only access the vector data through operator [] but not via a pointer. I can't write stuff like: std::vector<char> data; fill_data(data); char *ptr = data; Before I could do this: char *data = malloc(10...
The standard way to access the vector data is to use &data[0]
3,521,145
3,521,200
C++ template arguments in constructor
Why doesn't this code compile? template <class T> class A { public: A(T t) : t_(t) {} private: T t_; }; int main() { A a(5.5); // A<double> a(5.5); // that's what i don't want to do } I want template arguments to be implicit. Like in this example: template<class T> T Foo(T t)...
Since you have to name the type of a variable (C++03 can't infer the type of a variable), you can only do: A<double> a(5.5); // that's what i don't want to do The situation is a little easier when you needn't make a variable of the type, but want to pass it to some other function. In this case, you define an auxiliary...
3,521,352
3,521,494
Difference between partition() and remove() functions in C++
What is the difference between the partition() and remove() functions in C++? The remove doesn't actually remove any elements of the containers but puts the 'removed' elements at the beginning of the sequence of elements and partition does the same thing as well.
remove [...] puts the 'removed' elements at the beginning of the sequence What? No. Both remove_if and partition put the "good" elements first. partition puts the "bad" elements after that, whereas remove_if does not specify what comes after it -- it might be the bad elements, but it might also be copies of any (eith...
3,521,608
3,523,560
Templating boost::bind to automatically handle multiple arguments for member function
I have a class with an "Attach" function that accepts a function object and stores it into a collection. The class itself is templated on the function signature. Something like this: template<class Signature> class Event { public: void Attach(boost::function<Signature> signature) { MySignatures.push_back(signatu...
Overload Attach for different numbers of parameters in the member function: template<typename R,typename T,typename U> void Attach(R (T::*pmf)(),U* p)) { Attach(boost::bind(pmf,p)); } template<typename R,typename T,typename U,typename A1> void Attach(R (T::*pmf)(A1),U* p)) { Attach(boost::bind(pmf,p,_1)); } t...
3,521,695
3,521,799
why would I forbid allocation in the heap?
I recently read a lot about "preventing heap allocation for a class" (see this question). I was able to understand "how", but now I can't figure out "why" someone would like to do that. I guess there must be legitimate reasons for this, but I just can't figure them out. In short: "Why may I want to forbid users from cr...
Some classes make sense only if the objects are instantiated on the stack. For example, Boost scoped_ptr, or lock_guard.
3,521,914
3,521,972
Why compiler doesn't allow std::string inside union?
i want to use string inside Union. if i write as below union U { int i; float f; string s; }; Compiler gives error saying U::S has copy constructor. I read some other post for alternate ways for solving this issue. But i want to know why compiler doesn't allow this in the first place? EDIT: @KennyTM: In an...
Think about it. How does the compiler know what type is in the union? It doesn't. The fundamental operation of a union is essentially a bitwise cast. Operations on values contained within unions are only safe when each type can essentially be filled with garbage. std::string can't, because that would result in memory c...
3,521,979
3,522,285
Best lookup match between const char * and const char (& p)[T_Size]
I have two functions : void foo(const char * p) and template<size_t T_Size> void foo(const char (& p)[T_Size]) ; Given the call: int main(int argc, char* argv[]) { char a[21] ; // typeid : A21_c sprintf(a, "a[21] : Hello World") ; const char * b = "b : Hello World" ; // typeid : PK...
Table 9 in Chapter 13(Overload Resolution) of the Standards, ranks "Array to pointer" conversion (for non-template) to be of the same rank (EXACT MATCH) as "no Conversion Required" (for the template version). Everything else being the same, the non-template version is preferred over the template version.
3,522,093
3,522,580
Why there are so many ways to get the filter graph manager in directshow?
Way 1: HRESULT hr = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&pGraph)); Way 2: hr = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void **)&pGraph); What's the difference, why ?
IID_PPV_ARGS Macro Used to retrieve an interface pointer, supplying the IID value of the requested interface automatically based on the type of the interface pointer used. This avoids a common coding error by checking the type of the value passed at compile time. MSDN link
3,522,952
3,538,452
OpenGL render transmission in real time
I'm experimenting with developing a tool for remote OpenGL rendering, in C++. The basic idea is: The client issues OpenGL commands like it's a normal app Those commands are actually sent over the network to an external server The server performs the rendering using some off-screen technique Once done, the server tra...
You have two solutions. Solution 1 Run the app remotely Intercept the openGL calls Forward them on the network Issue the openGL calls localy -> complicated, especially when dealing with buffers and textures; the real openGL code is executed locally, which may not be what's wanted, but it's up to you. What's more, it'...
3,522,955
3,523,005
what are the other equivalent librarys of C++ qt
What are the other equivalent libraries of C++ Qt ? If anybody has used please share your experience with this community. If anybody knows altrenative please let us know yourr experience with these libraries
wxWidgets is a GUI library that is similar to Qt. http://www.wxwidgets.org/
3,523,050
3,523,116
Does GCC C++ compiler take into account __restrict - statements?
I've have investigating the effect of __restricting certain pointers in a C++-code, when compiling it via the GCC-compiler. It turned that not only the run-time remains quite the same, but the executable doesn't seem to have changed, the size in bytes is exactly the same as before. My GCC-version is gcc version 4.3.2 [...
restrict qualifiers are basically a way for the user to help the compiler to perform certain aliasing-related optimizations. They will only have an effect if these optimization opportunities are already present in the code, so using restrict simply enables them in situations when the compiler previously had to use a "s...
3,523,198
3,523,259
Global non static variable in unnamed namespace
I can't find a good explanation about global non static variables in unnamed namespace. I avoid global variables as much as I can. In this particular case I'm interested about behaviour just from pure theoretic side. Suppose the following code: In a.h namespace ai { class Widget { void DoSomething(int param); }...
Yes, there is just one variable x. Yes, there is just one variable x. Yes, there is just one variable x. On startup & on shutdown. I'm not following the question. I believe 1-4 above are in the Standard. It is exactly the same as if you had defined it as static : Global inside the file, but hidden outside of it. stat...
3,523,571
3,523,621
Is it possible to take a type as an argument in a function?
I'm trying to write a function for a database class that is basically just a wrapper around a hash_map of objects (say shapes) indexed by ID numbers that will look up an ID and cast it to the appropriate pointer type. e.g. I'd like to be able to do something like this: Circle* shapeToLookup = NULL; int idNum = 12; data...
You can do it with a template. Edit: new implementation based on the extra information. If mymap is a std::map<int, Shape*>: template <typename T> void lookup(int idNum, T* &ptr) { auto it = mymap.find(idNum); if (it == mymap.end()) { ptr = 0; } else { ptr = dynamic_cast<T*>(*it); // Shape m...
3,523,622
3,523,714
Qt: Qt classes vs. standard C++
A large amount of functionality is duplicated between standard c++ and Qt. At some point it seems logical but many times it looks foolish. Like I feel like doing a new programming language, learning things which I already know. e.g. using QFile. Also if I do it all Qt way and suppose now I want to move out of Qt framew...
As there is no GUI in C++ you should abstract the GUI code from the rest of the real code. Then within your QT implementation of your GUI abstraction feel free to use QT code. You will also then be able to write Wx/Quartz GUI abstraction without affecting the real code. In the real code (were the work is done) stick to...
3,523,638
3,523,729
Stop a Method taking to long
I'm sure I've seen this somewhere but can't remember where and it might have been in C# anyway. I have a bunch of game-objects that get looped through each being updated. Is it possible to break an update method if its taking to long? For instance if a programmer adds a bunch of code that takes to longer to do during 1...
If you control the interface of the update, you could pass it the permitted time, and have the game object terminate itself. Kind of like cooperative multithreading. This could be your best bet if you have very many objects, since you cut the overhead of real threads.
3,523,716
3,523,892
Is there a function to convert EXCEPTION_POINTERS struct to a string?
Does anybody know of a function to convert the EXCEPTION_POINTERS structure returned from GetExceptionInformation() into a string that I can log? I don't want to roll my own if it's already been done. EDIT: Basically, I've added the __try{} __except(){} blocks to help the app fail gracefully on a critical error. While...
There is no such function, since you'll need private symbols to write anything meaningful. The dbghelp.dll helps with some of this (specifically the StackWalk function and its 64-bit variant) What do you want to get out of the exception record to put into the log? Just the exception code? The register context? The sta...
3,523,743
3,524,165
How can I access a dynamic variable created in C++ from Javascript? (bound via V8)
Google was nice enough to explain how to wrap C++ class methods with accessors that can be used from the V8 Javascript engine. However, they don't mention how to determine the name of the JavaScript object that will have these accessor properties available. How do I tell V8 Javascript what the name of the C++ class ins...
OK, I found the missing piece of the puzzle: context->Global()->Set(String::New("p"), obj); This line exposes the object wrapper obj created in the previous steps to V8 JavaScript's global context as the object "p." I named it "p" here, but it could be any valid JavaScript identifier. (source)
3,523,780
5,691,186
How can you disable the buffer in a boost::iostreams sink?
I've written a 'sink' using boost::iostreams, so that I can essentially have my own code run when someone tries to write to an iostream object. Unfortunately there is a buffer somewhere in the system, so that my Sink's write() function only gets called every 4kB or so. This is a problem because the sink I am implement...
I think I've found a workaround. You have to manually decide when you want to perform a flush, but if you do a seek - even seeking to the same position, i.e. stream.seekp(0, std::ios::cur) - then it will cause everything to be flushed as expected. It's a bit of a horrible workaround but it seems to do the job most of ...
3,524,009
3,525,519
How to change the control themes in a Win32 API application?
If I create a button in the Win32 API, the default conrol theme looks like a Windows 95/98 button. I remember in the past the Microsoft forums told me how to get the XP style, but I don't recall how to do this. Is there a way to programatically or manually change the control themes in a Win32 application? Thanks.
You want to Enable Visual Styles by adding a manifest dependency to the common control 6 assembly to your applications manifest. If you use DevStudio it should be as simple as adding the #pragma directive from the linked page: #pragma comment(linker,"\"/manifestdependency:type='win32' name='Micr...
3,524,053
3,524,071
char four[4] = "four"; What are the correct semantics for this statement?
int main(void) { char four[4] = "four"; return 0; } When compiled as a C++ program, G++ reports xxx.cpp: In function int main(): xxx.cpp:3: error: initializer-string for array of chars is too long When compiled a a C program, GCC reports no error. It appears to me, that the assignment is correctly copying all ...
Short answer: your code is valid C, but not valid C++. Long Aswer: "four" is actually 5 characters long - there is a \0 added there for you. In section 6.7.8 Initialization, paragraph 13, the C standard says: An array of character type may be initialized by a character string literal, optionally enclosed in braces. S...
3,524,221
3,524,287
Equivalent of C++ STL container "pair<T1, T2>" in Objective-C?
I'm new to Objective-C, so please don't judge me too much. I was wondering: Is there an equivalent of the C++ STL pair container I can use in Objective-C? I want to build an array that contains an NSInteger associated to an NSBool. I know I could use an array with each entry being a NSDictionary with a single key-value...
You can use the STL in Objective-C++. All you need to do is change the extension of your .m file to .mm and I would also advise you use #import instead of #include. That way you can use your pair STL container.
3,524,624
3,529,694
How can I expose a uniform interface to a template class?
I have implemented a templated buffer class like this: template <class T, class Impl> class base_hardware_buffer : Impl { public: typedef const T& const_reference; typedef T* pointer; void push_back(reference r) { // Do some generic operation, call impl when needed // ... } poi...
I can explain how I implemented a solution to a similar problem. Basically I have a "CreateBuffer" function that returns a pointer to a "base" buffer. Then when I call functions on that base buffer they move up to the relevant function. class BaseBuffer { public: BaseBuffer(void); virtual ~BaseBuffer(void); ...
3,524,915
3,525,050
STL containers , remove object from two containers
Suppose I have two containers , holding pointers to objects ,which share some of their elements . from http://www.cplusplus.com/reference/stl/list/erase/ it says that : This effectively reduces the list size by the number of elements removed, calling each element's destructor before. How can I remove an object...
If your containers are holding pointers, then the destructor for those objects won't be called (the STL won't follow those pointers and call the pointee's destructor). Conversely, if your containers were holding the full-size objects themselves, then the destructor for those objects would be called. You also had some ...
3,524,932
3,525,496
Using std::vector<T*>::push_back with std::mem_fun and std::bind1st
I'm trying to use std::vector<T*>::push_back with std::mem_fun and std::binder1st, but it doesnt seem to be feasible, can this be done? I've tried to exemplify with the code below. #include <vector> #include <functional> #include <iostream> using namespace std; struct A { int _Foo; virtual int AFoo()...
The problem is that binder1st defines operator() as: operator() (const typename Operation::second_argument_type& x) const and mem_fun1_t defines operator() as: S operator() (T* p, A x) const The problem is that push_back is defined as: void vector<T>::push_back(const T &x) So what we end up with is this: void mem_fu...
3,525,023
6,567,181
SPSS 15 I/O DLL: Modifying Existing Cases
I am writing an application in C++ that interfaces with SPSS 15 using their I/O DLL. Our SPSS database is made of a number of cases, each with their unique "ID" field. What I need to do is open the database in read/write, find the case with the matching ID and modify some of the variables according to CSV files that my...
I figure no one is going to bother answering now that it's solved. Anyway, it is not possible to insert a case in the middle of a database. You could potentially write wrappers around the API to simulate it, but otherwise there is no way to do what I am trying to do without manually iterating through each case and copy...
3,525,348
3,525,583
What are general steps for me to port my project to mono?
I have a dll. and visual C++ source for it. (my dll is visual c++ wraper around some ffmpeg av* libs - another precompiled dll's) while in the same solution (.sln) I have C# project that uses my dll. what are general steps for me to port my project to mono?
Compile your project in Visual Studio, but enable the following compiler options: /clr:pure: This will make a pure CLR assembly (without any x86/x86-64 asm), that should run on mono, unless you use some C runtime calls (CRT). /clr:safe: The same as pure, but you can't have CRT references, so your project might not com...
3,525,552
3,526,267
Hide class type in header
I'm not sure if this is even possible, but here goes: I have a library whose interface is, at best, complex. Unfortunately, not only is it a 3rd-party library (and far too big to rewrite), I'm using a few other libraries that are dependent on it. So that interface has to stay how it is. To solve that, I'm trying to ess...
Use the Pimpl (pointer to implementation) idiom. As described, OverlyComplicatedNodeClass is an implementation detail as far as the users of your library are concerned. They should not have to know the structure of this class, or even it's name. When you use the Pimpl idiom, you replace the OverlyComplicatedNodeClass...
3,525,631
3,525,680
Documenting namespaces that span multiple files doxygen
Consider I have 2 header files. // HEADER 1 /** * Doc for Foo here? */ namespace Foo { class This {...}; } && // HEADER 2 /** * Doc for Foo here? */ namespace Foo { class That {...}; } How should I handle this when documenting with Doxygen?
Maybe neither. For example, imagine you have "<root>/utility/header1.hpp" which has its contents in namespace utility and "<root>/utility/header2.hpp" which does also. You could add a file: "<root>/utility.hpp" which documents the utility namespace. You could put this at the top #error Documentation only. to make sure ...
3,525,689
3,525,734
Need beginner help with C++ syntax
I am busy with an assignment an I am getting an error from the compiler. I've got 4 yrs C# experience nil in C++. I'm getting the error "Invalid conversion from nodeType, initializing argument 1 of void linkedListType::deleteNode(const Type&) [with Type = int]' " on the line deleteNode(current->link); of this functio...
Well, the problem is pretty straightforward. This: current->link is defined to have type nodeType<Type>* But this function that you are trying to pass it to void linkedListType<Type>::deleteNode(const Type& deleteItem) accepts an argument of type const Type& Since nodeType<Type>* isn't at all the same thing as cons...
3,525,826
3,525,910
Why does my decryption function scramble the ciphertext even more, instead of decrypting it?
I've created this program that can encrypt a found file and then it can be decrypted later via the CryptDecrypt function. The function succeeds but instead of decrypting the file back to plain text it makes the file look even more encrypted. I've put both the CryptEncrypt function and CryptDecrypt function so you can h...
It looks like before encrypting or decrypting, you're generating a random key with CryptGenKey. This means that you will use a different key for encryption and decryption, so your file will not decrypt correctly. You will need to use the same key for encryption or decryption. Either by exporting and importing the key, ...
3,525,838
3,541,288
Need help replacing swprintf
I am using some cross platform stuff called nutcracker to go between Windows and Linux, to make a long story short its limited in its support for wide string chars. I have to take the code below and replace what the swprintf is doing and I have no idea how. My experience with low level byte manipulation sucks. Can some...
It is a bit hard to understand exactly what you are looking for, so I've guessed. As the tag was "C++", not "C" I have converted it to work in a more "C++" way. I don't have a linux box to try this on, but I think it will probably compile OK. Your description of the input data sounded like UTF-16 wide characters, ...
3,525,965
3,525,989
Overload += operator if + is overloaded?
Possible Duplicate: Overloading += in c++ Do I need to overload the += operator if I overload + or will the compiler know what to do? Thanks.
You need to overload both. However, if you reverse the order you can reuse your code: struct foo { // this is the "core" operation, because it's mutating (changes this) foo& operator+=(const foo&) { // ... return *this; } }; foo operator+(const foo& lhs, const foo& rhs) { foo ret =...
3,525,977
3,526,139
Creating a container 'thing' in C++ to hold static functions. What should 'thing' be?
I'm currently building a set of common functions (Search algorithm implementations), and think I'm doing the grouping wrong. At the moment, I have a class, Sorting, that is declared in a file called Sorting.h (it's nowhere near finished yet, btw) like so: #ifndef SORTING_H #define SORTING_H #include <vector> class So...
Use a namespace. The callers of the code won't need to care. Also, you need to template on any sortable type- a sort that can only sort a vector of integers is rather bad. Stick to the definition provided by std::sort. namespace Sorting { template<typename Iterator> void cocktail_sort(Iterator a, Iterator b) { ...
3,526,005
3,526,037
Address of Stack and Heap in C++
Correction: I messed up with the concept of pointer address and the address the pointer points to, so the following code has been modified. And now it prints out what I want, variable a, c, i, j, k, p are on the stack, and variable b,d are on the heap. Static and global variables are on another segment. Thanks a lot...
Your understanding is wrong. For example, b is a pointer - if you want the address of the object created by new, you need to print out b, not &b. b is a local variable, so it itself (found at &b) is on the stack. For your example, N, l, and m are presumably somewhere in your executable's data section. As you can se...
3,526,299
3,526,364
C++ templates declare in .h, define in .hpp
I saw some code in which the developer defined a class template in a .h file, and defined its methods in a .hpp file. This caught me a bit by surprise. Are there are particular conventions in C++ when dealing with templates and what files they should be in? For example say I had a Vector class template with methods fo...
Typically (in my experience, YMMV) an hpp file is an #include-ed CPP file. This is done in order to break the code up in to two physical files, a primary include and an implementation-details file that the users of your library don't need to know about. It is done like this: super_lib.h (the only file your clients ne...
3,526,301
32,576,059
Dynamic 2D Array allocation in C
How I should allocate dynamic arrays in C? Currently I have a function I wrote called malloc2D that looks like this: void* malloc2D(size_t unitSize, uint firstCount, uint secondCount) { void** pointer = malloc(sizeof(id) * firstCount); for (int i =0; i < firstCount; i ++){ pointer[i] = malloc(unitSize *...
You can allocate the array as a contiguous bloc like this. Suppose you want ints: int (*arr)[secondCount] = malloc( sizeof(int[firstCount][secondCount]) ); You could hide this behind a macro which takes the typename as a macro argument, although the code is simple enough that that is not really necessary.
3,526,423
3,526,905
Defining routines for use with volatile and non-volatile objects
I find myself wanting to write a routine that will operate on both volatile and non-volatile memory blocks. Something along the lines of: void byte_swap (unsigned * block_start, size_t amount) { for (unsigned * lp = block_start; lp < block_start + amount; lp++) { *lp = htonl(*lp); } memcpy (block_st...
You only need to use volatile when you are dealing with memory mapped IO, that is where successive reads or writes to the same memory address can and should return different values. If you are writing to what amounts to simply shared memory, a simple formal handover mechanism which allocates access the either the CPU o...
3,526,546
3,526,559
Get the list of methods of a class
Is there a way to create a list (e.g. an array) of pointers to each method of a C++ class? Something like Type.GetMethods() in the .NET framework, but using only standard C++.
No this is not possible in a general way. C++ does not have the same metadata infrastructure that .Net posses. Could you provide us with a scenario where you want to use this information? There may be a better approach you can use with C++
3,526,597
3,526,654
Current function address - x64
I am working on this small project where I'd like to generate the call graph of an application - I am not planning to do anything complex, it is mainly for fun/experience. I am working on x64 platform. The first goal I set myself is to be able to measure the time spent in each function of my test application. So far my...
I believe SymGetSymFromAddr64, probably along with StackWalk64 should get you (most of?) what you want.
3,526,644
3,537,978
How to document functions in described technique of creating C++ .Net dll's?
So here we have a technique, and here some more on it, of creating C++ DLLs with functions readable by .Net languages such as C#. The main Idea of technique as I use it (I can be ideologically wrong but it totally works for me) - you created a C++ project, it worked, now you want to use some of its functions from C# (f...
Whoah... you are using old style Managed C++ with the __gc business. You should instead use C++/CLI where you will say public ref class Foo. You can then use the same Doc Comments (starting with /// and having XML in them) as you would in C#.
3,526,690
3,526,706
Struggling to get '==' operator overloading to work (C++)
Okay, not sure what I'm doing here, other than it's not right. Trying to overload the '==' method of a class, and it's just... not working. At least, I get a false back from my main, and the cout in the implementation of '==' doesnt output. These are my three files: // TestClass.h #ifndef TESTCLASS_H #define TESTCLASS...
tc == tc1 compares pointer values. It "should" be *tc == *tc1, but I don't get why you'd dynamically allocate in the first place. Automatic (stack) allocation is highly preferred, only dynamically allocate when you need the object to be independent of scope. (And then keep track of it with automatically allocated smart...
3,526,702
3,526,830
What to consider with regards to alignment when designing a memory pool?
I'm working on a memory pool for a small game engine. The main use will be as a segregated storage; a pool contains object of a specific type and size. Currently the pools can be used to store anything, but allocations will be done in blocks of a specific size. Most of the memory need will be allocated at once, but "ov...
Allocations with malloc are guaranteed to be aligned for any type provided by the compiler and hence any object[*]. The danger is when your header has a smaller alignment requirement than the maximum alignment requirement for your implementation. Then its size might not be a multiple of the max. alignment, and so when ...
3,526,819
3,529,571
How do I receive raw, layer 2 packets in C/C++?
How do I receive layer 2 packets in POSIXy C++? The packets only have src and dst MAC address, type/length, and custom formatted data. They're not TCP or UDP or IP or IGMP or ARP or whatever - they're a home-brewed format given unto me by the Hardware guys. My socket(AF_PACKET, SOCK_RAW, IPPROTO_RAW) never returns from...
I think the way to do this is to write your own Network Service that binds to the MUX layer in the VxWorks network stack. This is reasonably well documented in the VxWorks Network Programmer's Guide and something I have done a number of times. A custom Network Service can be configured to see all layer 2 packets recei...
3,527,120
3,527,153
Are there advantages to a crashing on a secondary thread versus the main one?
I came across this code in a large codebase DWORD WINAPI ThreadFunc (LPVOID lpParam) { int *x = 0; *x = 1234; // Access violation return 0; } void Manager::Crash () { Log("Received a remote command to crash Server."); DWORD dwThreadId, dwThrdParam = 1; HANDLE hThread = ::CreateThread(NULL,...
He doesn't want to handle the exception that occurs. The original thread that received the Manager::Crash continues. An AV exception does not necessarily terminate the process. Although in this case the fact that is not handled by a __try/__except block (note, is a SEH try block, not the C++ one) then the unhandled se...
3,527,141
3,527,344
c++ left mouse button down help
ok i know how to do the left mouse button down evet(WM_LBUTTONDOWN). but im having some troubles with it. when use it with vectors it seems to add 101 elemnts everytime the left mouse button is down. i think that every time the mouse button is down, it sends 101 messages to WM_LBUTTONDOWN that causes 101 elements to be...
omg it was my fault i set the vetor to 100 elemnts sorry guys
3,527,187
3,527,337
What makes EXE's grow in size?
My executable was 364KB in size. It did not use a Vector2D class so I implemented one with overloaded operators. I changed most of my code from point.x = point2.x; point.y = point2.y; to point = point2; This resulted in removing nearly 1/3 of my lines of code and yet my exe is still 364KB. What exactly causes it to ...
What makes EXE’s grow in size? External libraries, especially static libraries and debugging information, total size of your code, runtime library. More code, more libraries == larger exe. To reduce size of exe, you need to process exe with gnu strip utility, get rid of all static libraries, get rid of C/C++ runtime...
3,527,248
3,527,662
MI and implicit copy constructor bug (was: Under what conditions can a template be the copy constructor?)
I was pretty sure that the answer to that question was, "Never, ever can a template be the copy constructor." Unfortunately, I just spent 3 hours figuring out why I was getting a warning about recursion, tracked it to the copy constructor, watched the debugger go insane and not let me look at the recursive code, and fi...
I'm pretty sure the answer to your question is "never". Section 12.8.2 of the ANSI C++ Standard says A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parame...
3,527,313
3,527,370
Using bundled properties as the weight map in dijkstra_shortest_paths
Perhaps this is a stupid question, but I'm trying to use BGL's dijkstra_shortest_paths, and, in particular, to use a field of my Edge bundled property as the weightmap. My attempts have currently led to tens of pages of compiler errors, so I'm hoping that someone knows how to help me. This is essentially what my code l...
In case anyone cares about this, using the named parameter version of the call seems to have worked, as follows: dijkstra_shortest_paths(m_graph, vertex_from, weight_map(get(&TrafficGraphEdge::length, m_graph)) .distance_map(make_iterator_property_map(distances.begin(...
3,527,342
3,527,421
initialize a vector from an existing array
const int NUMB = 4; int n[] = {5,6,7,8}; // create a vector of strings using the n[] array vector<int> partnums(n, n + NUMB); The class functions vector name(src.begin, src.end) Create a vector initialized with elements from a source container beginning at src.begin and ending at scr.end According to the book...
The C++ standard library uses a convention that the 'end' iterator is actually referring to one element past the end, so in your case 'begin' would be the 0th position and 'end' the fourth (not third) position. What is confusing in your citation above is that n + NUMB is referred to as the last element in the array, wh...
3,527,890
3,527,949
C++ Accessing a friends class->member->public method?
Is the following code legal in C++. Accessing a friend class member public method? I know this sounds confusing, and the best way to show it is in code. I was wondering if the TestClassC::Method() is valid in the code below? I've compiled (g++) and it works, however, I run into a situation, where it produces a segmenta...
The public/private/protected accessor modifiers are enforced at compile-time, not at runtime. The SEGFAULT is a runtime error, not a compile-time error. So, in the future, if you get a SEGFAULT, you can be sure that it is not related to the level of access. It sounds like your confusion is based on whether the access m...
3,527,938
3,560,667
C/C++/C#: how to force repaint of window chrome on windows 7?
My application has a standard top level window for the application. I need to force a repaint of the window chrome (otherwise known as the non-client area of the window). I do not care if the client area is also repainted or not but the chrome itself needs to be forced to repaint. In particular I need this to work on ...
According to MSDN, it seems that RedrawWindow( hWnd, NULL, NULL, RDW_INVALIDATE | RDW_FRAME ); is what you are looking for. RDW_FRAME causes any part of the nonclient area of the window that intersects the update region to receive a WM_NCPAINT message. The RDW_INVALIDATE flag must also be specified; otherwise, RDW_FR...
3,528,182
3,528,235
Visual Studio - Finding which modules are causing C1905 (processor incompatibility)
I'm attempting to make an x64 build of a project with Visual Studio 2005. It's currently failing with linker error C1905, 'Front end and back end not compatible (must target same processor).' From what I gather, this is essentially saying that my x64 build is attempting to link with x86 modules. Unfortunately, this pro...
First, check Configuration Manager (Build > Configuration Manager...) to ensure that you're building all of your projects for the same platform. If that doesn't help, then from the Visual Studio Command Prompt (available from the Start menu), you can use dumpbin to determine the architecture of your .lib and .obj files...
3,528,193
3,528,208
Doxygen for a project managed with git?
I'm working on a C++ and Objective C iPhone Project. I'm using git as my version control system. The codebase has been growing quite a bit, so I would like to add doxygen to the project. The problem is that I'm not sure about what would be the best approach to do it. I've thought about a couple of options: 1) Create th...
I believe one should never store generated files in a source repository, particularly when they're generated by commonly-available tools like Doxygen from files that are already stored in the repository. In the case of Doxygen, you only need to store Doxyfile in the repo. (Or, better, if you're using autoconf, store D...
3,528,199
3,528,249
C++ friend comparison between two instantiations of one class template
I am trying to write a class template that provides a comparison operator between two instatiations with different template types. As is often the case, this operator is a non-member friend. A simplified example of what I am trying to achieve can be seen below. template<typename T> class Wrapper { // Base type, which...
Number of things: When your class template is instantiated once for X and once for Y, you have two definitions of the operator==. Move the operator== out of the class declaration. Note that a friend is not a member. Hence the access violation related diagnostic. Try this: template<typename T> class Wrapper { // Ba...
3,528,252
3,579,631
Killing a pthread waiting on a condition variable
I have a pthread waiting on a condition variable using pthread_cond_wait(). It's waiting for data from a queue structure that is filled by another thread. I want to kill this thread, preferably without pthread_kill(). On Linux and WinPthreads doing a pthread_cancel(); pthread_join() is enough to kill it. However, on...
Do you have access to the queue, and control of the object schema for enqueued items? If so, define a queue object type that when de-queued, instructs the thread that is processing the item to exit gracefully. Now, to shut down these threads, simply post a number of these "quit" objects to the HEAD of the queue that c...
3,528,302
3,528,584
Is there a better way to do this?
I'm drawing 2D, concave, sometimes multicontoured, sometimes self intersecting polygons with OpenGL. Here is a sample: Right now, I take the points which if connected would result in the polygon's outline. Then I put these into the GLUTesselator where triangles come out. I then make texture coordinates and texture the...
First a simpler problem: suppose you just wanted to use one color. You could start with the list of outlines, then scan the whole window by row and column: whenever you crossed a boundary, you would increment or decrement (depending on the sense of the crossing) a counter how_many_outlines_am_I_inside. When it's zero, ...
3,528,715
3,528,736
char, pointer, cast and string questions
/*1*/ const char *const letter = 'A'; /*2*/ const char *const letter = "Stack Overflow"; Why is 1 invalid but 2 valid? letter is a pointer that needs to be assigned an address. Are quoted strings addresses? I'm assuming this is why #2 is valid and that single quoted strings are not considered addresses? Also, what i...
Because 'A' is not a pointer, it's a char, 65 or 4116 if the underlying character set is ASCII. "Stack", on the other hand, is string, basically the character array {'S', 't', 'a', 'c', 'k', '\0'}, which degrades to a pointer to its first character. Your "difference between static_cast and ()" has been answered here, f...
3,528,877
3,528,955
Can someone Explain Mutex and how it is used?
I read a few documents about Mutex and still the only Idea I have got is that it helps preventing threads from accessing a resource that is already being used by another resource. I got from Code snippet and executed which works fine: #include <windows.h> #include <process.h> #include <iostream> using namespace std; ...
A mutex provides mutually exclusive access to a resource; in your case, a database. There aren't multiple threads in your program, but you can have multiple instances of your program running, which is what your mutex is protecting against. Effectively, it is still protecting against access from more than one thread, ...
3,529,263
3,529,334
template specialization according to sizeof type
I would like to provide a templated function, that varies its implementation (->specialization) according to the sizeof the template type. Something similar to this (omitted typecasts), but without the if/elseif: template<class T> T byteswap(T & swapIt) { if(sizeof(T) == 2) { return _byteswap_ushort (sw...
You don't need SFINAE or type traits. Vanilla template specialization is enough. Of course it must be specialized on structs as C++(98) doesn't support function template partial specialization. template <typename T, size_t n> struct ByteswapImpl /* { T operator()(T& swapIt) const { throw std::exception(); } } */ /...
3,529,394
3,531,345
Obtain minimum NEGATIVE float value in C++
I was looking at std::numeric_limits<float>::min/max() but it appears 'min()' returns the smallest absolute value, not the lowest value. Is it safe to use -std::numeric_limits<float>::max(), i.e is float symmetric in min/max limits?
IEEE 754 floating point numbers use a sign bit for signed-ness (rather than something like twos complement), so if you're sure that your compiler/platform uses that representation (very common) then you can use -std::numeric_limits<float>::max() as you suspected.
3,529,449
3,529,656
Can I make the ternary operator treat my class like a bool?
I've recently been doing a huge refactoring where I was changing a lot of my code to return booleans instead of an explicit return code. To aid this refactoring I decided to lean on the compiler where possible by getting it to tell me the places where my code needed to be changed. I did this by introducing the follow...
class CCastableToBool { public: // ... operator bool() const { //... { return true; } //... return false; } private: // ... }; but beware, in C++ it is considered real...
3,529,674
3,529,804
Implicit type conversions - Compiler error
This question is related to this question. The following code compiles fine VC9 compiler but gives the error when compied with Comeau online. Can anybody tell me which one is correct and what is the meaning of the error? error: ambiguous "?" operation: second operand of type "TypesafeBool" can be converted to thi...
The error is that the ternary operator must have a single type, and your expression (1=1) ? f() : false has two types -- f() has type TypesafeBool and false has type bool. You can convert between them, but Comeau doesn't know which you want to use. To resolve it, cast one of the sides of the ternary to the type of th...
3,529,735
3,529,824
Why doesn't my trim function work?
void trim(string &str) { string::iterator it = str.begin(); string::iterator end = str.end() - 1; // trim at the starting for(; it != str.end() && isspace(*it); it++) ; str.replace(str.begin(), it, ""); // trim at the end for(; end >= str.begin() && isspace(*end); end--) ; ...
Changing a string invalidates iterators into the string. One way to fix this would be to modify the string only once. Incidentally, this might also be faster: void trim(std::string &str) { std::string::size_type begin=0; while(begin<str.size() && isspace(str[begin])) ++begin; std::string::size_type e...
3,529,740
3,530,679
C++ Win32 Window unresponsive
I have a console application from which I create a window. I can render stuff in the window just fine. But the window is unresponsive/uncontrollable by the user. As soon as you mouse over the window you get the hourglass cursor and cannot move the window. What might be causing this? EDIT: WNDCLASSEX wndClass; ...
Since it's already mentioned in comments, I'll make this community wiki You need to get the messages for the window and dispatch them accordingly. /* * HWND hWnd: this is the handle to your window (that is returned from CreateWindow[Ex] */ MSG msg; while (GetMessage(&msg, hWnd, NULL, NULL) > 0){ TranslateMessage...
3,529,779
3,529,832
Can I build boost for mingw and windows from same folder?
So I have a folder with boost 1.44.0 and I need both msvc and MinGW binary libraries. I have already done the msvc build and need to do the MinGW gcc build next. Can I build from the same folder? My reasoning is this should not create a problem as the .a/.so libraries are just placed in the same lib folder but the head...
That should be fine. Libraries are just files on the harddisk so they can easily coexist in the same folder, as long as they have different names. In summary: yes your assumptions are correct.
3,529,831
3,530,061
_Bool and bool: How do I solve the problem of a C library that uses _Bool?
I've written a collection of data structures and functions in C, some of which use the _Bool data type. When I began, the project was going to be pure C. Now I am investigating using a C++ based GUI tool kit and have made the backend code into a library. However, when compiling the C++ GUI the following error is emitte...
Just #include <stdbool.h> and use bool.
3,529,936
3,530,038
How to resolve compilation error "cannot convert const to reference" in VC++9
I am working in migration project from VC6 to VC9. In VC9 (Visual Studio 2008), I got compilation error while passing const member to a method which is accepting reference. It is getting compiled without error in VC6. Sample Program: class A { }; typedef CList<A, A&> CAlist; class B { CAlist m_Alist; public: ...
That is because the GetNext() method returns a temoprary object of class A and the function AddTail takes the parameter A&. Since a temporary object can not be bound to a non-const reference you get the error. The simplest way to solve it is to break it into two statements. For example: while( pos != NULL) { ...
3,530,205
3,532,460
Mesh from heightmap in Ogre3D
Using the Ogre3D engine (C++), I would like to generate a mesh from a grayscale heightmap. I know that the Terrain tools can do that but I just want a simple mesh. What would be the best way to do that? This sounds pretty basic but I can't find my way in the Ogre3d doc. Thanks!
One way to do it is extract all the height values and pump them into an Ogre::ManualObject. Then call ManualObject::convertToMesh(...) for the conversion. Fire up a MeshSerializer and use it to save the mesh out to a file. MeshPtr pmo = mo.convertToMesh( "GrassBladesMesh" ); MeshSerializer ser; ser.exportMesh( pmo.ge...
3,530,406
3,530,512
Exception free tree destruction in C++
I have recently managed to get a stack overflow when destroying a tree by deleting its root 'Node', while the Node destructor is similar to this: Node::~Node(){ for(int i=0;i<m_childCount;i++) delete m_child[i]; } A solution that come up into my mind was to use own stack. So deleting the tree this way: std...
This is what all garbage collectors struggle with. However, the best thing you can do (IMHO) is to pray for enough memory for the stack, and your prayers will be heard 99.99999% of the time. Should it not happen, just abort(). BTW if you are interested, there is a solution to traverse long (and deep) trees without allo...
3,530,466
3,530,733
vector freeing issue compared to array
I am storing dynamically allocated class pointers in a vector like below. vector<Test *> v; Test *t1 = new Test; Test *t2 = new Test; v.push_back(t1); v.push_back(t2); Now, if i have to free Test objects, i have to loop through entire vector and free one by one and then do a clear. for(int i = 0; ...
Your examples don't do the same thing at all. If you want the vector equivalent of this array code: Test *a = new Test[2]; delete []a; it is simply std::vector<Test> a(2); If you have a vector of pointers to dynamically allocated objects, you need to delete every one of them, as in your example: for(int i = 0; i<v.s...
3,530,470
3,530,514
What is the type of T?
In the code below: template<typename T> struct X {}; int main() { X<int()> x; // what is the type of T ? } What is the type of T? I saw something like this in the boost sources.
Consider the function int func(). It has a function type int(void). It can be implicitly converted to pointer type as the C++ Standard says in 4.3/1, but it this case there's no need in such conversion, so T has the function type int(void), not a pointer to it.
3,530,490
3,534,126
boost::asio async_accept Refuse a connection
My application have an asio server socket that must accept connections from a defined List of IPs. This filter must be done by the application, (not by the system), because it can change at any time (i must be able to update this list at any time) The client must receive an acces_denied error. I suppose when the handle...
The async_accept method has an overload to obtain the peer endpoint. You can compare that value inside your async_accept handler. If it does not match an entry in your container, let the socket go out of scope. Otherwise, handle it as required by your appliation.