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
734,958
735,007
C++ empty-paren member initialization - zeroes out memory?
I originally wrote some code like this: class Foo { public: Foo() : m_buffer() {} private: char m_buffer[1024]; }; Someone who is smarter than me said that having the m_buffer() initializer would zero out the memory. My intention was to leave the memory uninitialized. I didn't have time to discuss it furthe...
If you have a member initialized like that, it will be value-initialized. That is also true for PODs. For a struct, every member is value-initialized that way, and for an array, every element of it is value-initialized. Value-initialization for a scalar type like pointer or integer you will have it inialized to 0 conv...
734,996
735,120
How to marshal C++/CLI array of struct to unmanaged C++
I'm searching for the correct syntax to pass a struct array to an unmanaged C++ dll. my dll imports are called like this #define _DllImport [DllImport("Controller.dll", CallingConvention = CallingConvention::Cdecl)] static _DllImport bool _Validation(/* array of struct somehow */); In my client code I have List<M...
Create a managed version of the unmanaged struct using StructLayout.Sequential (make sure to put things in the same order). You should then be able to pass it like you'd pass it to any managed function (e.g., Validation(MyStruct[] pStructs). For example, let's say our native function has this prototype: extern "C" { ...
735,021
735,094
Most useful or amazing STL short liners
I'm looking for practical and educational samples of C++ / STL code fitting in few lines. My actual favorites are: Empty a vector freeing its reserved memory: vector <...>().swap (v) (swap with a temporary) Copy a map to a vector: map<T1, T2> myMap; vector< pair<T1, T2> > myVec(myMap.begin(), myMap.end()); // or myVe...
// std::back_inserter usage ( std::inserter for map ) std::copy( source.begin(), source.end(), std::back_inserter( container ) ); - // mem_fun and bind usage (but boost better) std::some_algorithm(..., std::mem_fun( func ) ); not so useful, but powerful: check is container sorted std::adjacent_find( container.beg...
735,170
735,304
Can the "Application Error" dialog box be disabled?
I am using Hudson as a continuous integration server to test C/C++ code. Unfortunatly, I have a bug somewhere that causes memory corruption, so on some Windows machines I will sometimes get a "Application Error" dialog box explaining that an instruction referenced memory that could not be read. This dialog box pops u...
Use "Disable error reporting", as Mr. Gently suggests. See also this PC World article. If you happen to have MS Visual Studio on your build machine, it will catch Application Errors and pop up a dialog box. To disable these dialogs (and also the Just-In-Time Debugging feature of Visual Studio), run the command drwts...
735,204
735,241
Convert a String In C++ To Upper Case
How could one convert a string to upper case. The examples I have found from googling only have to deal with chars.
Boost string algorithms: #include <boost/algorithm/string.hpp> #include <string> std::string str = "Hello World"; boost::to_upper(str); std::string newstr = boost::to_upper_copy<std::string>("Hello World");
735,249
735,338
Blocking socket returns EAGAIN
One of my projects on Linux uses blocking sockets. Things happen very serially so non-blocking would just make things more complicated. Anyway, I am finding that often a recv() call is returning -1 with errno set to EAGAIN. The man page only really mentions this happening for non-blocking sockets, which makes sense. Wi...
It's possible that you have a nonzero receive timeout set on the socket (via setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,...)) as that would also cause recv to return EAGAIN
735,346
735,402
Cannot Load C++ DLL in C#
>My previous thread< I created this one,because I installed WinXP on VMBox and I cannot get it working again. This time I created an OnLoad Event on my form if (LoadLibrary("blowfish.dll") == 0) { Misc.LogToFile("Could not load dll", true); Application.Exit(); } Runs fin...
To further trouble should you could call Marshal.GetLastWin32Error(); which should give you an error code. Is it possible that you deployed a debug version of your native dll which also requires a debug version of MSVCR90D.DLL? You should have distributed the release version because the debug version requires a differ...
735,647
735,656
#ifdef for 32-bit platform
In an application I maintain, we've encountered a problem with file descriptor limitations affecting the stdlib. This problem only affects the 32-bit version of the standard lib. I have devised a fix for my code and would like to implement it, but only when compiling for 32-bit executable. What pre-processor symbol can...
I'm not sure if there is a universal #if def that is appropriate. The C++ standard almost certainly does not define one. There are certainly platform spcefic ones though. For example, Windows #if _WIN64 // 64 bit build #else // 32 bit build #endif EDIT OP mentioned this is a cross compile between Windows and Non-Wi...
736,061
736,111
C/C++ pattern to USE_HEAP or USE_STACK
Is there a way to define a macro (or something similar) that would allow objects to be allocated on the stack or on the heap, cleanly? eg. Current code: A a; a.someFunc(); The simplest suggestion might be the following, but as you can see below, it's not very clean to maintain 2 sets of code. #ifdef USE_STACK A a; ...
EDIT: improved to allow calling of wrapped member functions through operator-> Expanding on Manuel's answer to make it more complete, try this: #include <iostream> #define USE_STACK template <class T> class HeapWrapper { #ifdef USE_STACK T obj_; #else T *obj_; #endif public: #ifdef USE_STACK HeapWrapper()...
736,188
736,210
Iterating a read() from a socket
Is this the proper way to iterate over a read on a socket? I am having a hard time getting this to work properly. data.size is an unsigned int that is populated from the socket as well. It is correct. data.data is an unsigned char *. if ( data.size > 0 ) { data.data = (unsigned char*)malloc(data.size); memset(&...
You need to check the return value from read before you start adding it to other values. You'll get a zero when the socket reports EOF, and -1 on error. Keep in mind that for a socket EOF is not the same as closed.
736,533
736,550
How do you convert a string to ascii to binary in C#?
A while back (freshman year of high school) I asked a really good C++ programmer who was a junior to make a simple application to convert a string to binary. He gave me the following code sample: void ToBinary(char* str) { char* tempstr; int k = 0; tempstr = new char[90]; while (str[k] != '\0') { ...
This is very easy to do with C#. var str = "Hello world"; With LINQ foreach (string letter in str.Select(c => Convert.ToString(c, 2))) { Console.WriteLine(letter); } Pre-LINQ foreach (char letter in str.ToCharArray()) { Console.WriteLine(Convert.ToString(letter, 2)); }
736,701
752,324
class & function names highlighting in Vim
I just recently set up my Vim environment from Textmate, after becoming addicted to its modal input. However, syntax highlighting seems to be not so beautiful in Vim. I code in C++ and since the function call and class names can't be highlighted, the code is more difficult to read. I played with color scheme for a bit...
Interestingly, the syntax highlighters in VIM don't support applying a syntax to identifiers or function names - at least not the syntax highlighters for C and C++. So, even if you do: :hi Function guifg=red or :hi Identifier guifg=red it doesn't give these a color. I just seems to be not much more than keywords an...
736,782
736,790
CoInitializeEx fails when calling OpenCV method cvLoadImage()
I am trying to integrate some OpenCV functionality into my application. Currently I have code set up with DirectShow to get a video feed from my camera, which is then showed in an MFC window. This code cannot be changed or removed. The code runs completely fine, but regardless of the location i place the following li...
CoInitialize will fail if the thread was previously initialized as a different apartment, i.e., if there was a previous CoInitializeEx(NULL, COINIT_MULTITHREADED) I would guess that OpenCV calls CoInitializeEx(NULL, COINIT_MULTITHREADED), causing your subsequent calls to CoInitializeEx to fail. You can confirm this by...
736,981
738,264
How do I deal with "Project Files" in my Qt application?
My Qt application should be able to create/open/save a single "Project" at once. What is the painless way to store project's settings in a file? Should it be XML or something less horrible? Of course data to be stored in a file is a subject to change over time. What I need is something like QSettings but bounded to a p...
You can use QSettings to store data in a specific .ini file. From the docs: Sometimes you do want to access settings stored in a specific file or registry path. On all platforms, if you want to read an INI file directly, you can use the QSettings constructor that takes a file name as first argument and pass QSettings:...
736,982
736,994
C++ polymorphism not supported for pointer-to-pointer
I'm searching for a proper way to clean my pointers. Here the example code: class Parent { protected: int m_Var; public: Parent() : m_Var(0) {} virtual ~Parent() {} void PubFunc(); }; class Child : public Parent { protected: bool m_Bool; public: Child() : m_Bool(false) {...
There are soo many ways to handle memory correctly. The one close to your example would be: template <typename T> RemoveObj(T **p) { if (p == NULL) return; delete *p; *p = NULL; } Additionally you might want to use std::auto_ptr instead. It would look like: int main() { std::auto_ptr<Parent*> pPObj(new...
737,108
737,133
Converting from Derived* to Base*&
I was trying to answer the question mentioned here by passing the reference to the pointer instead of pointer to pointer like this: class Parent { }; class Child : public Parent { }; void RemoveObj(Parent*& pObj) { delete pObj; pObj = NULL; } int main() { Parent* pPObj = new Parent; Child* pCObj =...
An object of type Child* cannot be bound to a Parent*& for exactly the same reason that a Child** cannot be converted to a Parent**. Allowing it would allow the programmer (intentionally or not) to break type safety without a cast. class Animal {}; class DangerousShark : public Animal {}; class CuteKitten : public An...
737,240
737,245
Array size at run time without dynamic allocation is allowed?
I've been using C++ for a few years, and today I saw some code, but how can this be perfectly legal? int main(int argc, char **argv) { size_t size; cin >> size; int array[size]; for(size_t i = 0; i < size; i++) { array[i] = i; cout << i << endl; } return 0; } Compiled under...
This is valid in C99. C99 standard supports variable sized arrays on the stack. Probably your compiler has chosen to support this construct too. Note that this is different from malloc and new. gcc allocates the array on the stack, just like it does with int array[100] by just adjusting the stack pointer. No heap alloc...
737,409
737,437
Are get and set functions popular with C++ programmers?
I'm from the world of C# originally, and I'm learning C++. I've been wondering about get and set functions in C++. In C# usage of these are quite popular, and tools like Visual Studio promote usage by making them very easy and quick to implement. However, this doesn't seem to be the case in the C++ world. Here's the C#...
I'd argue that providing accessors are more important in C++ than in C#. C++ has no builtin support for properties. In C# you can change a public field to a property mostly without changing the user code. In C++ this is harder. For less typing you can implement trivial setters/getters as inline methods: class Foo { p...
737,575
737,584
Must I use pointers for my C++ class fields?
After reading a question on the difference between pointers and references, I decided that I'd like to use references instead of pointers for my class fields. However it seems that this is not possible, because they cannot be declared uninitialized (right?). In the particular scenario I'm working on right now, I don't ...
Answer to Question 1: However it seems that this is not possible, because they [references] cannot be declared uninitialized (right?). Right. Answer to Question 2: In my snippet, bar1 is automatically instantiated with the default constructor (which isn't what I want), &bar2 causes a compiler error because ...
737,583
737,595
What are the reasons for preferring Singleton or function scope local static objects over one another?
Both Marshall Clines' "C++ FAQ Lite" and Scott Meyers' Effective C++ suggest using functions returning local static objects to avoid possible problems with non-local static object initialization order. In short (from "Effective C++", 3rd edition by Scott Meyers): FileSystem& tfs() { static FileSystem fs; return fs;...
You can use both: class Singleton { public: static Singleton & Instance() { static Singleton s; return s; } private: Singleton() {} }; Now the only way a Singleton can be created is via the Instance function (because the constructor is private) and so you can guarantee ...
737,653
737,656
What's the best technique for exiting from a constructor on an error condition in C++
What's the best technique for exiting from a constructor on an error condition in C++? In particular, this is an error opening a file. Thanks for the responses. I'm throwing an exception. Here's the code (don't know if it's the best way to do it, but it's simple) // Test to see if file is now open; die otherwise if ( ...
The best suggestion is probably what parashift says. But read my caution note below as well please. See parashift FAQ 17.2 [17.2] How can I handle a constructor that fails? Throw an exception. Constructors don't have a return type, so it's not possible to use return codes. The best way to signal constructor ...
737,830
737,849
C++ functions accepting both pointers and references
I am writing a library in C++ and have some functions that work with modules. An example would look like this: void connect(Module *a, Module *b); The problem is, that it would be sometimes handy if the function accepted also references (some of the Modules may be allocated on the stack and some on the heap and all th...
Why not just call the function with connect(&a, &b); like in your inline function, whenever you have to call it with references? This makes it very clear that the function takes pointers, and that a and b are not pointers. You only have to type two more characters.
737,996
738,024
Directory of running program on Linux?
Hey, I've been writing a program (a sort of e-Book viewing type thing) and it loads text files from a folder within the folder of which the executable is located. This gives me a bit of a problem since if I run the program from another directory with the command "./folder/folder/program" for example, my program will no...
EDIT - don't use getcwd(), it's just where the user is not where the executable is. See here for details. On linux /proc/<pid>/exe or /proc/self/exe should be a symbolic link to your executable. Like others, I think the more important question is "why do you need this?" It's not really UNIX form to use the executable...
738,204
738,214
Why might my virtual function call be failing?
Update: This issue is caused by bad memory usage, see solution at the bottom. Here's some semi-pseudo code: class ClassA { public: virtual void VirtualFunction(); void SomeFunction(); } class ClassB : public ClassA { public: void VirtualFunction(); } void ClassA::VirtualFunction() { // Intentionally...
class Base { public: virtual void f() { std::cout << "Base" << std::endl; } void call() { f(); } }; class Derived : public Base { public: virtual void f() { std::cout << "Derived" << std::endl; } }; int main() { Derived d; Base& b = d; b.call(); // prints Derived } If in the Base class you do not wan...
738,606
742,372
A C++ Application Compiled With VS2008 Doesn't Run In Other Computer
I have created a wn32 project with Visual Studio 2008 and Visual C++ language, it uses the ws2_32.lib library and then I compiled in Release mode. It runs very good in the same computer, but when I copy the exe file to other computer (that doesn't have installed Visual Studio), it doesn't run. The message I see is: Th...
I agree with JaredPar. The application you build with VS2008 is using dynamic linking, whereas the DEV C++ is linking statically, hence the larger size and why one works and not the other. However, if its a plain win32 application project you've got (and you don't want/need to distribute it with a setup), you may be ab...
738,933
739,121
Multiple Singleton Instances
I am writing a library of utility classes, many of which are singletons. I have implemented them as such using inheritance: template <class T> class Singleton { public: T& getInstance() { if(m_instance == 0) { m_instance = new T; } return m_instance; ...
Your problem is that your template is going to be instantiated in more than one compilation unit as it is completely inline. Therefore in every compilation unit that uses the template you will end up creating one singleton (per compilation unit). What you would need is to force global linkage, so that all compilation u...
738,952
738,972
const float & x = something; // considered harmful?
There was some code like this: // Convenience to make things more legible in the following code const float & x = some.buried.variable.elsewhere; // Go on to use x in calculations... I have been told that the "const float &" is "bad" and should just be a plain float or const float. I, however, could not think of a co...
I can't think of a reason why const float & would be better than const float. References make sense if you're either worried about copies being made (which is irrelevant with a primitive type like float) or you want to be able to update a value across all instances that share the reference (which is irrelevant with co...
739,038
739,048
Why do priority queues mostly use 0 as the most important priority?
Why are most priority/heap queues implemented as 0 being the highest priority? I'm assuming I'm missing out some key mathematical principle. As I was implementing my own priority queue recently it seemed easier to write the insert function if priority went up with the integer value, but apparently people smarter than m...
Most priority queues are implemented as a fibonacci heap or something similar. That data structure supports extracting the minimum in constant time, which makes it natural to make 0 the highest priority, and take elements out of the queue by extracting the minimum.
739,095
739,115
Win32 LB_GETTEXT returns garbage
I have a problem which is most likely a simple problem, but neverthe less still a problem for me. I am using the Listbox in Win32 / C++ and when getting the selected text from my listbox the string returned is just garbage. It is a handle to a struct or similar? Below is the code and an example of what I get. std::stri...
The LB_GETSEL message does not return the index of a selected item, it returns the selected STATE of the ITEM you pass in WPARAM. You also have a serious bug where if no items are selected you will attempt to retrieve the string of the item at index -1, which is clearly wrong. Checking the return values of these SendMe...
739,398
739,412
Transiting from COBOL to C++
I am a fairly junior programmer and have the task of interviewing an experienced mainframe COBOL programmer for a position doing C++ development for Windows Mobile. By experienced I mean that the candidate's entire programming career has been COBOL. I am not biased against any particular language, just slightly conce...
The best thing is, give him a task, similar to what he will have to do at your company. Tell him he can use pseudo code (So no Internet is needed). Also, The main problem Cobol people have is to grasp OO (Since Cobol is mostly procedural...I am aware of new OO versions). One more pitfall Cobol people have is grasping t...
739,439
739,447
Is the PS3's Cell architecture the wrong platform to be learning game programming?
I have an opportunity to attend Sony licensed training classes to learn about programming with the PS3's cell architecture. However I only have a rudimentary knowledge of C++ and was wondering if the PS3 is a bit of an overkill for a starter aspiring game dev like me. And also what is the best resources to get me to ...
The problem isn't so much that a PS3 is overkill, it's that the Cell processor is notoriously difficult to program to it's potential. The highly parallelized architecture is potentially quite powerful, but it's not easy to actually get that performance.
739,539
741,234
Continuous Integration: Unmanaged C++ on Visual Studio 2008
I've spent 4 years developing C++ using Visual Studio 2008 for a commercial company; it's now time for me to upgrade my development process. Here's the problem: I dont have a 1 button build automation. I also dont have a CI server that automatically builds when a commit happens, and emails me whether a build is broken ...
I would take some time to seriously consider TeamCity. We used CruiseControl.NET for a while and TeamCity completely demolishes it. Plus it has built-in plugins for Boost and CppUnit, so your unit testing will come for free. Best of all, the tool is free for < 20 users and gives you three build agents. I just finishe...
739,594
1,546,689
Static-code analyzer: unmanaged C++ Visual Studio 2008
I develop commercial unmanaged C++ app on Visual Studio 2008, and I want to add a static-code analysis tool. Any recommendations? I think it would be real nice if the tool can be integrated into MSVC. I'm thinking about PC-Lint + Visual Lint However, I have been taking a hard look at Coverity, Understand, and Klockwor...
I work for RedLizard building Goanna, a C++ static analysis plugin for Visual Studio. Its focus is on desktop use by a programmer. You can run it on individual files, just as you do the compiler, and it can give you results quickly. There is a trial available. Right-click a file, select Run Goanna, and the results appe...
739,830
739,852
library for server side (c/c++) xmlrpc
I want to implement support of the XMLRPC protocol for my server that is written in C and C++ and now looking for the most widely adopted xmlrpc library. License is not an issue, GPL would be fine. What would you suggest ? Is there any defacto standard xmlrpc C library for such a purpose ?
The de facto standard would imo be this one: http://xmlrpc-c.sourceforge.net/ and it supports both C and C++ and it even has its own embedded http daemon for servicing the http requests ... edit: and it's available under a BSD-style license, so it allows you to boldly go where GPL didn't allow you to go before ;)
740,026
757,752
Boost Deserialization Optimizations?
I'm deserializing a fair amount of data through Boost.Serialization (one for each frame). However, when I output how long the deserialization takes, it varies wildly. It is not unusably slow at the moment, but it would be nice to make it faster. The data represents the same classes, arrays, maps and vectors but merely ...
You might want to reconsider the design of the feature using this serialization. From your description it seems as though you are serializing/deserializing an entire STL container very frequently. This shouldn't be required. Serialization shouldn't be used unless the data needs to be persisted so that it can be re-buil...
740,030
740,038
How to release the unused capacity of a string
I am dealing with a lot of strings in my program. These string data don't change through out the whole life time after they being read into my program. But since the C++ string reserves capacity, they waste a lot of space that won't be used for sure. I tried to release those spaces, but it didn't work. The following is...
When you call reserve, you're making a request to change the capacity. Implementations will only guarantee that a number equal to or greater than this amount is reserved. Therefore, a request to shrink capacity may be safely ignored by a particular implementation. However, I encourage you to consider whether this isn't...
740,131
740,147
C/C++ codehighlighter in visual studio 2005
I just starting using VS2005 and I wish to have code highlighting in C/C++. The VS menu Tools->Options->TextEditor->C/C++ is very poor. I come from PHP and there the IDE's are very friendly when is about highlighting. I didn't expect that Visual Studio to be so poor at this kind of options. Can you recommend me a free...
It's not free, but Visual Assist X has some really nice highlighting. Another (suboptimal for you) solution is to switch editors. Emacs is infinitely configurable. I believe that Eclipse CDT and NetBeans have better syntax highlighting.
740,169
740,192
lib to read a DVD FS (data disc)
I am thinking i might want to port a lib to read a DVD filesystem. I am not talking about movies but datadisc. Theres existing code for me to do raw reads from the disc. I need code that request this data and allow me to browse files on the disc. What lib can i use for this? -edit- NOTE: I am using an OSless hardware. ...
You need libudf which is part of GNU libcdio.
740,228
740,245
Define smallest possible datatype in c++ that can hold six values
I want to define my own datatype that can hold a single one of six possible values in order to learn more about memory management in c++. In numbers, I want to be able to hold 0 through 5. Binary, It would suffice with three bits (101=5), although some (6 and 7) wont be used. The datatype should also consume as little ...
A char is the smallest possible type. If you happen to know that you need several such 3 bit values in a single place you get use a structure with bitfield syntax: struct foo { unsigned int val1:3; unsigned int val2:3; }; and hence get 2 of them within one byte. In theory you could pack 10 such fields into a 32-b...
740,263
740,272
C++ dll in C program
I'd like to create a dll library from C++ code and use it in C program. I'd like to export only one function: GLboolean load_obj (const char *filename, GLuint &object_list); Header file from library: #ifndef __OBJ__H__ #define __OBJ__H__ #include <windows.h> #include <GL/gl.h> #include <GL/glext.h> #include <GL/glu...
The parameter "GLuint &object_list" means "pass a reference to an GLuint here". C doesn't have references. Use a pointer instead. // declaration extern "C" GLboolean load_obj (const char *filename, GLuint *object_list); // definition GLboolean load_obj (const char *filename, GLuint *object_list) { code... }
740,423
740,486
Qt class for handling file paths
Possible Duplicate: Qt equivalent of PathAppend? Is there a class that handles file paths in Qt? Particularly I'm looking for something like .NET's Path.Combine. I know there's one in boost::filesystem but I was wondering if there's one in Qt.
There is QDir which might be of help (see QDir::relativeFilePath and QDir::canonicalPath and others). Quoting from QDir doc: A QDir is used to manipulate path names, access information regarding paths and files, and manipulate the underlying file system.
740,435
740,444
How to convert this VC++ 6 code to VC++ 2008?
Forgive me my C++ is incredibly rusty. But I am trying to take some old code and recompile it under Visual C++ 2008. It was originally written for Visual C++ 6.0 The error I am getting is this: error C4430: missing type specifier - int assumed. Note: C++ does not support default-int Ok seems simple enough. But the...
You need to have the operator=() method return something (it would assume int if the diagnostic weren't an error, as the error message somewhat confusingly indicates). Generally it would be a reference to the object the operator is working on so the assignments can be chained as in a normal assignment expression. Some...
740,577
740,686
sizeof a union in C/C++
What is the sizeof the union in C/C++? Is it the sizeof the largest datatype inside it? If so, how does the compiler calculate how to move the stack pointer if one of the smaller datatype of the union is active?
The Standard answers all questions in section 9.5 of the C++ standard, or section 6.5.2.3 paragraph 5 of the C99 standard (or paragraph 6 of the C11 standard, or section 6.7.2.1 paragraph 16 of the C18 standard): In a union, at most one of the data members can be active at any time, that is, the value of at most one o...
740,700
740,714
ABC Virtual OStream Insertion Operator
Consider the following snippet: struct ObjectInterface { virtual ~ObjectInterface() {} virtual void Print(std::ostream& target) const = 0; }; struct Foo : ObjectInterface { virtual void Print(std::ostream& target) const { target << "Foo"; } }; struct Bar : ObjectInterface { virtual voi...
You need a free function: ostream & operator << ( ostream & os, const ObjectInterface & oi ) { oi.Print( os ); return os; }
740,836
741,373
Compiling C++ Programs with Emacs on Windows
I've been using Emacs for quite some time for basic text editing but as of today I am attempting to use it for c++ compilation. I have looked for the past few hours about how to go about this but I keep hitting roadblocks in their techniques (I think some of this is having to do with the tutorials being outdated). Basi...
The M-x compile command calls out to a shell (e.g. linux bash, windows cmd.exe, etc) to run the make command. On windows I think emacs defaults to the cmd.exe shell (through a special C:/Program Files/Emacs/emacs/bin/cmdproxy.exe executable). If you want your M-x compile to use a different shell (probably cygwin bash ...
741,000
744,595
Help storing an intrusive_ptr of a template class in a std::map
I have a small template class of type Locker contained within a boost::intrusive_ptr that I want to store inside a std::map: template <typename T> bool LockerManager<T>:: AddData(const std::string& id, T* pData) { boost::intrusive_ptr<Locker<T> > lPtr(Locker<T>(pData)); // Line 359 - compiles mMap.insert(make_p...
Actually, intrusive_ptr already has a < operator and a copy constructor defined, so that wasn't the problem. There were two main things that we were missing. First, we needed to use value_type, instead of make_pair, to avoid implicit type conversion in the insert statement. Second, we missed the fact that the intrusi...
741,054
741,085
Mapping between stl C++ and C# containers
Can someone point out a good mapping between the usual C++ STL containers such as vector, list, map, set, multimap... and the C# generic containers? I'm used to the former ones and somehow I've accustomed myself to express algorithms in terms of those containers. I'm having some hard time finding the C# equivalent to t...
Here's a rough equivalence: Dictionary<K,V> <=> unordered_map<K,V> HashSet<T> <=> unordered_set<T> List<T> <=> vector<T> LinkedList<T> <=> list<T> The .NET BCL (base class library) does not have red-black trees (stl map) or priority queues (make_heap(), push_heap(), pop_heap()). .NET collections don't use "iterators"...
741,301
741,371
How can I add and subtract 128 bit integers in C or C++ if my compiler does not support them?
I'm writing a compressor for a long stream of 128 bit numbers. I would like to store the numbers as differences -- storing only the difference between the numbers rather than the numbers themselves because I can pack the differences in fewer bytes because they are smaller. However, for compression then I need to subtra...
If all you need is addition and subtraction, and you already have your 128-bit values in binary form, a library might be handy but isn't strictly necessary. This math is trivial to do yourself. I don't know what your compiler uses for 64-bit types, so I'll use INT64 and UINT64 for signed and unsigned 64-bit integer qua...
741,423
741,445
Creating popup menu in Qt for QTableView
I have a QTableView in the main UI of my program. I'd like to show popup menu when user right clicks on the cells of the table and take appropriate action when an option is selected from the menu. I am using Qt Creator 1 (Qt version 4.5). How can I do that?
Check out the customContextMenuRequested signal to get the event, and use a QMenu for the menu itself. Use QTableView::indexAt to find out what, if any, cell was clicked based on the coordinates given to the signal and take the appropriate action when a menu item is clicked.
741,452
741,565
C++ Tricky Inheritance Class Definition Problem
I'm getting this error when dealing with a number of classes including each other: error: expected class-name before '{' token I see what is going on, but I do not know how to properly correct it. Here is an abstracted version of the code: A.h #ifndef A_H_ #define A_H_ #include "K.h" class A { public: A...
Circular inclusions do not work. Try to keep inclusions to a strict minimum. If you do that, you'll either be fine altogether, or you'll discover problems in your design. In your case, i don't see anything wrong with your design. When defining class K, you're only using a pointer to an object of type B. That does not ...
741,476
741,477
Is it possible to put several objects together inside a union?
What if I have this: union{ vector<int> intVec ; vector<float> floatVec ; vector<double> doubleVec ; } ; Of course, I'll be using just one of the 3 vectors. But... what happens when all the 3 vectors are contructed?? Would the consructors of the 3 vectors interfere with each other?? (since the 3 of them ar...
Current C++ standard does not allow non-POD types inside unions. You will get this compiler error from gcc: error: member ‘std::vector<int, std::allocator<int> > <anonymous union>::i’ with constructor not allowed in union error: member ‘std::vector<int, std::allocator<int> > <anonymous union>::i’ with destructor not al...
741,597
741,606
Using types defined in template arguments
When using a container class like vector, list, etc., I can use the type of the elements by writing vector<type>::value_type. However, the following code template<class container> void foo(container& c) { typedef container::value_type elementtype; elementtype b; } fails with the error "expected initializer be...
You're missing the required typename keyword: typedef typename container::value_type elementtype; This is because container is a dependent name in this template, so the compiler has no way of knowing whether container::value_type is always a type or not, as it may depend on the choice of container. Surely this questio...
741,719
741,747
What's the difference between APR (Apache Portable Runtime) 1.3 and 0.9?
I'm just getting started with APR and it seems that there are two supported versions developed side-by-side: http://apr.apache.org/ The docs don't explain the difference between 1.3.x and 0.9.x... Can anyone please shed light on the matter? Or in short, which should I use?
See http://www.apache.org/dist/apr/Announcement0.9.html : This version of APR is principally a bug fix release, and is provided only for users requiring APR 0.9 compatibility. Most developers are encouraged to adopt the latest APR 1.x version to ensure the most comprehensive support and access to the latest features a...
741,746
741,758
Problems with starting a program + DLL multiple times in Windows XP?
We develop a network library that uses TCP and UDP sockets. This DLL is used by a testclient, which is started multiple times at the same PC for a load test. In Windows Vista, it is no problem to start the testclient many times. In Windows XP, starting it up to 5 times is no problem, but if we start it 6 times or more,...
An idea: You have some bug. Seriously, there is no way to know what's your problem without any information what so ever. When a process crashes it usually has a very good reason to do so. find out what that is. Compile your dlls and executables in debug, attach a debugger and make sense of the stack trace you get. i...
741,834
741,849
How to avoid running out of memory in high memory usage application? C / C++
I have written a converter that takes openstreetmap xml files and converts them to a binary runtime rendering format that is typically about 10% of the original size. Input file sizes are typically 3gb and larger. The input files are not loaded into memory all at once, but streamed as points and polys are collected, th...
First, on a 32-bit system, you will always be limited to 4 GB of memory, no matter pagefile settings. (And of those, only 2GB will be available to your process on Windows. On Linux, you'll typically have around 3GB available) So the first obvious solution is to switch to a 64-bit OS, and compile your application for 64...
742,034
743,455
qpThreads documentation
Is there any documentation on qpThreads? In what way is it different from pthreads?
Found some documentation finally. Sourceforge qpthreads
742,342
764,328
Simple OpenGL texture map not working?
I'm trying to figure out texture mapping in OpenGL and I can't get a simple example to work. The polygon is being drawn, though it's not textured but just a solid color. Also the bitmap is being loaded correctly into sprite1[] as I was successfully using glDrawPixels up til now. I use glGenTextures to get my tex name,...
I found the problem. My call to glEnable was glEnable(GL_BLEND | GL_TEXTURE_2D). Using glGetError I saw I was getting a GL_INVALID_ENUM for this call, so I moved GL_TEXTURE_2D to its own enable function and bingo. I guess logical OR isn't allowed for glEnable?
742,415
742,422
C memset seems to not write to every member
I wrote a small coordinate class to handle both int and float coordinates. template <class T> class vector2 { public: vector2() { memset(this, 0, sizeof(this)); } T x; T y; }; Then in main() I do: vector2<int> v; But according to my MSVC debugger, only the x value is set to 0, the y value is untouched. Iv...
No don't use memset -- it zeroes out the size of a pointer (4 bytes on my x86 Intel machine) bytes starting at the location pointed by this. This is a bad habit: you will also zero out virtual pointers and pointers to virtual bases when using memset with a complex class. Instead do: template <class T> class vector2 { p...
742,545
742,571
Operator = Overload with Const Variable in C++
I was wondering if you guys could help me. Here are my .h: Class Doctor { const string name; public: Doctor(); Doctor(string name); Doctor & Doctor::operator=(const Doctor &doc); } and my main: int main(){ Doctor d1 = Doctor("peter"); Doctor d2 = Doctor(); d2 = d1; } I want to ...
You are almost there. Few noteworthy points: The name should not be const qualified. A const cannot be modified, which is exactly what we want in the assignment operator. The C++ keyword is class and not Class as your code has it (it'll give you compile errors) As Michael Burr notes: "It should be noted though that i...
742,607
742,617
Using local classes with STL algorithms
I have always wondered why you cannot use locally defined classes as predicates to STL algorithms. In the question: Approaching STL algorithms, lambda, local classes and other approaches, BubbaT mentions says that 'Since the C++ standard forbids local types to be used as arguments' Example code: int main() { int ar...
It's explicitly forbidden by the C++98/03 standard. C++11 remove that restriction. To be more complete : The restrictions on types that are used as template parameters are listed in article 14.3.1 of the C++03 (and C++98) standard: A local type, a type with no linkage, an unnamed type or a type compounded fr...
743,055
743,100
Convert iterator to pointer?
I have a std::vector with n elements. Now I need to pass a pointer to a vector that has the last n-1 elements to a function. For example, my vector<int> foo contains (5,2,6,87,251). A function takes vector<int>* and I want to pass it a pointer to (2,6,87,251). Can I just (safely) take the iterator ++foo.begin(), conver...
That seems not possible in my situation, since the function I mentioned is the find function of unordered_set<std::vector*>. Are you using custom hash/predicate function objects? If not, then you must pass unordered_set<std::vector<int>*>::find() the pointer to the exact vector that you want to find. A pointer to an...
743,191
743,848
How to Parse Lines With Differing Number of Fields in C++
I have a data that looks like this: AAA 0.3 1.00 foo chr1,100 AAC 0.1 2.00 bar chr2,33 AAT 3.3 2.11 chr3,45 AAG 1.3 3.11 qux chr1,88 ACA 2.3 1.33 chr8,13 ACT 2.3 7.00 bux chr5,122 Note that the lines above are tab separated. Moreover, it sometime may contain 5 fields or 4 fields. What I want to do is to captu...
Another C++ only version that just uses the fact that istream must set the failbit if operator>> fails to parse. while(getline(ss, line)) { stringstream sl(line); sl >> tag >> v1 >> v2 >> v3 >> v4; if(sl.rdstate() == ios::failbit) // failed to parse 5 arguments? { sl.clear(); sl.seekg(...
743,197
743,211
size() Vs empty() in vector - why empty() is preferred?
While debugging something, I saw the STL vector::empty() implementation: bool empty() const {return (size() == 0); } I believe, whenever we are probing the emptiness of vector it is always recommended to use empty over size(). But seeing that implementation, I am wondering, what is the benefit of doing so? Ins...
You would need to write the condition out everytime you use size(). It's convenient to use empty(). This is of course, provided you don't switch containers. As others have pointed out, it is upto the implementation to use size() in empty() or not. However, the standard does guarantee that: empty() is a constant-time op...
743,203
743,205
Accessing static class variables in C++?
Duplicate: C++: undefined reference to static class member If I have a class/struct like this // header file class Foo { public: static int bar; int baz; int adder(); }; // implementation int Foo::adder() { return baz + bar; } This doesn't work. I get an "undefined reference to `Foo::bar'" error. How d...
You must add the following line in the implementation file: int Foo::bar = you_initial_value_here; This is required so the compiler has a place for the static variable.
743,321
743,334
Is it good to send stack allocated object as a pointer parameter to some other function?
Is it good to send stack allocated object as a pointer parameter to some other function?
Yes, but the more common C++ idiom for this situation is to use a reference (and probably a const rreference) instead of a pointer. So instead of void foo( sometype * p ) { p->func(); } you write: void foo( sometype & p ) { p.func(); } This has the advantage that you don't need to dereference the object in the ...
743,395
743,397
How to refactor a class in C++ to make a certain function const?
I have a class which looks something like this: class MyClass { public: // some stuff omitted /*** A function which, in itself, is constant and doesn't change the class ***/ void myFunction( void ) const; private: /*** If loaded is true, then internal resources are loaded ***/ boolean loaded; };...
Use the mutable keyword. class MyClass { public: void myFunction( void ) const; private: mutable boolean loaded; }; This says that the loaded member should be treated as being logically const but that physically it may change.
743,413
743,436
Tool Chain for WxWidgets explained
Where can I find an writeup that shows me how to set up a tool chain for WxWidgets (C++) on linux/ubunto and/or OS X. I downloaded, compiled & installed WxWidgets both on linux and OS X, compiled and tried the samples, but seem to be stuck setting up a compile environment in my own home directory. DialogBlocks from htt...
Like all C/C++ programs, the compiler has to know in what directories to look for include files, and the linker has to know what libraries it should link to. The WxWidgets package, if installed correctly, includes the program wx-config. This can be used while compiling and linking, like so: g++ $(wx-config --cxxflags) ...
743,458
743,483
How does const correctness help write better programs?
This question is from a C# guy asking the C++ people. (I know a fair bit of C but only have some general knowledge of C++). Allot of C++ developers that come to C# say they miss const correctness, which seems rather strange to me. In .Net in order to disallow changing of things you need to create immutable objects or o...
A whole section is devoted to Const Correctness in the FAQ. Enjoy!
743,594
743,604
C++ Implementation of a Binary Heap
I need a min-heap implemented as a binary tree. Really fast access to the minimum node and insertion sort. Is there a good implementation in stl or boost that anyone can point me too?
I think std::priority_queue is what you are looking for.
743,669
743,685
Are inline functions in C/C++ a way to make them thread-safe?
I make the following reasoning, please tell me what's wrong (or right) about it: "If inlining a function duplicates the code in the place the function is called, then the static and local variables are duplicated for each function calling it and if there is only one thread running the function that calls the inlined on...
When you declare a function as inline, it is merely a hint to the compiler. Static variables have a clear definition in the language. If the compiler does inline the function, it is still obligated to keep the static variables shared between all instances of the function. Therefore, they will remain global and have to ...
743,697
743,702
What is the exact definition of instance variable?
I think instance variables are simple data types like int or double. Everything that is created automatically when the object is created. If an object creates additional objects - like everything that is it done with the NEW keyword - these are not instance variables. Am I right or wrong? What is the exact definition?...
Wrong. Anything that is bound within the instance (i.e. an instantiated object) is instance variable. As opposite of static (class) variables, which are bound to the class. It doesn't matter if they are simple types or pointers to objects.
743,732
744,440
About the MSDN Documentation on NOTIFYICONDATA's cbSize member
I am reading the NOTIFYICONDATA documentation in MSDN. It says the NOTIFYICONDATA structure has a cbSize member should be set to the size of the structure, but NOTIFYICONDATA structure's size has different size in every Shell32.dll, so you should get the Shell32.dll version before setting cbSize. The following quotes f...
Which features are available through platform sdk headers are controlled by _WIN32_WINNT, which should be defined to the lower version of the operating system you are targeting. From http://msdn.microsoft.com/en-us/library/6sehtctf.aspx the correct values are: 0x0500 for Windows 2000 operating system, 0x0501 for W...
743,735
743,810
Why is printf showing -1.#IND for FPTAN results?
I am working on a program which produces assembler code from expressions. One of the functions required is tan(x) which currently works using the following sequence of code (the addresses are filled in at run time): fld [0x00C01288]; fld st(0); fsin; fld st(1); fcos; fdivp; fst [0x0030FA8C]; However, I would like to u...
Let me just throw something out there: how about using fstp st(0); instead of fincstp; The docs on fincstp say it's not equivalent to popping the item from the stack because it leaves that spot tagged as filled - perhaps this is messing up the float handling inside of printf? (You may be able to guess I don't know w...
743,901
743,914
Complex statements in the member initialization part?
I have this: struct myClass{ multiset<string,binPred<string> > values ; myClass(const char param1, const char param2) : values(less<string>()) { } } ; I need to initialize the values member with a different functor depending on the values of param1 and param2. Unfortunately, the logic to decide which func...
You can use a static member function that will accept the parameters you have and return a necessary value. This solves the problem completely and allows for clean easily debuggable code.
744,110
744,129
CEdit numeric validation event C++ MFC
I have a CEdit text box which is a part of a property pane and only allows numeric values (positive integers). The box works fine when people enter non-numeric values, but when they delete the value in the box a dialog pops up saying: "Please enter a positive integer." Here is the situation: 1. I have a number (say 20...
The message you are receiving is coming from the data validation routines, not the data exchange routines. There is probably a call like this in DoDataExchange(): void MyPropertyPane::DoDataExchange(CDataExchange* pDX) { DDX_Control(pDX, IDC_NUMERIC_BOX, m_NumericBox); DDX_Text(pDX, IDC_NUMERIC_BOX, m_value); ...
744,750
744,773
Converting a C++ .exe project to a dll
Microsoft provides the source code of vshadow to manipulate VSS (Volume Shadow Service [shadow copy]), and I've modified it a bit but I want to make it into a dll so I can use it in my C# projects. I don't know exactly how to go about doing that, the source code is fairly simple, and it shouldn't be too hard, but I don...
You will need to change your project settings in Visual Studio to create a DLL. In addition you will need to define dll entry points. However, the VSS is a set of COM API's, so you can call them directly from C# with pinvoke, instead of using this wrapper C++ executable. Since the SDK only contains libs, not DLL's you...
744,768
744,922
How to determine the actual level of development in a shop, e.g. C++ vs. C?
I imagine most of you know what I am getting at. You start a new job and within the first week or so of scanning through the code you realize you are in yet another C shop that throws in the occasional stream or hapless user defined class here and there. You quickly realize that not only aren't you going to learn any...
It's really all across the board. On one end of the spectrum, I've worked in one place where the code was recently rewritten in C. Recently being 10 years ago. Everyone was highly skeptical of this new-fangled technology. Slightly farther down the spectrum, you'll find C programmers who happen to have compilers with C+...
745,043
745,090
Are there any tools that are able to do cyclomatics on Pro*C++ sources?
Are there any tools that are able to do code metrics on Pro*C++ sources? I haven't been able to find anything specific via Google. Does anyone have any experience with this?
Pro*C can generate valid C++ files, for code metrics tools on standard c++ Google is your friend.
745,536
745,801
Small open source Unicode library for C/C++
Does anyone know of a great small open source Unicode handling library for C or C++? I've looked at ICU, but it seems way too big. I need the library to support: all the normal encodings normalization finding character types - finding if a character should be allowed in identifiers and comments validation - recognizin...
I looked at UT8-CPP, and libiconv, and neither seemed to have all the features I needed. So, I guess I'll just use ICU, even though it is really big. I think there are some ways to strip out the unneeded functions and data, so I'll try that. This page (under "Customizing ICU's Data Library") describes how to cut out so...
745,692
840,156
C++ pointer casting issue
I need to pass a pointer through a scripting language which just has a double and string type, for this I only have to worry about 32-bit pointers. Seeing as the pointers are 32-bit, I figured doubles had enough precision to safely store the pointer, which works, however the problem arises with some pointers to stream,...
Ok, the solution I came up with was to simplfy the casts. I defined a structure, like the one below that stored pointers already cast to the types I wanted. struct Streams { std::istream *is; std::ostream *os; std::stringstream *ss; std::fstream *fs; }; I then populated the struct (setting the ones tha...
745,819
745,949
How can I implement metaclasses in C++?
I've been reading a bit about what metaclasses are, but I would like to know if they can be achieved in C++. I know that Qt library is using MetaObjects, but it uses an extension of C++ to achieve it. I want to know if it is possible directly in C++. Thanks.
It's possible to create meta-classes, however C++ is not about that, it's about statically compile-time based implementations, not runtime flexibility. Anyways it depends if you want Meta-Classes with methods or just Meta-Classes with data, the Data classes can be implemented with Boost constructs like boost::any, and ...
745,850
745,861
Issues with C++ 'new' operator?
I've recently come across this rant. I don't quite understand a few of the points mentioned in the article: The author mentions the small annoyance of delete vs delete[], but seems to argue that it is actually necessary (for the compiler), without ever offering a solution. Did I miss something? In the section 'Special...
Well, the ideal would probably be to not need delete of any kind. Have a garbage-collected environment, let the programmer avoid the whole problem. The complaints in the rant seem to come down to "I liked the way malloc does it" "I don't like being forced to explicitly create objects of a known type" He's right abou...
745,897
746,266
Reading parts of an input file
I would like to read an input file in C++, for which the structure (or lack of) would be something like a series of lines with text = number, such as input1 = 10 input2 = 4 set1 = 1.2 set2 = 1.e3 I want to get the number out of the line, and throw the rest away. Numbers can be either integers or doubles, but I know wh...
Simply read one line at a time. Then split each line on the '=' sign. Use the stream functionality do the rest. #include <sstream> #include <fstream> #include <iostream> #include <string> int main() { std::ifstream data("input.dat"); std::string line; while(std::getline(data,line)) { s...
746,034
747,240
glDrawPixels in grayscale?
I have an image that I'm rendering like this: glDrawPixels(image->width, image->height, GL_BGR, GL_UNSIGNED_BYTE, image->imageData); Is there anyway I can draw it in grayscale instead (without loading it into a texture first)? I don't care if only, say, the blue component is used for the gray value rather than the L2 ...
A perverse idea for you to try, and I've no idea if it'll work: glPixelZoom(1.0f/3.0f,1.0f); glDrawPixels(3*width,height,GL_LUMINANCE,GL_UNSIGNED_BYTE,data); ie treat your 3-channel image as being a 1-channel (grayscale) image 3 times as wide, and compensate for this by squishing the width using the x zoom factor. I ...
746,298
747,415
How do you build a debug .exe (MSVCRTD.lib) against a release built lib (MSVCRT.lib)?
I'm using Visual C++ 2008, SP1. I have a QT app (gui, .exe) in debug build config. It's set to use the Multi-threaded Debug DLL version of the CRT, aka MSVCRTD.lib. I'm linking against a 3rd party library that is built in release mode and using the Multi-threaded DLL (non-debug) version of the CRT, aka MSVCRT.lib. It l...
You could build your project to link against the release CRT and enable debug information for your code. In "Project Properties" go to C++/General and change the Debug Information Format. In the "Optimization" section turn off optimization. Switch to the "Linker/Debugging" section and enable generation of debug info. M...
746,391
746,471
Deriving from a class with operator overloading
I want to create a collection of classes that behave like math vectors, so that multiplying an object by a scalar multiplies each field by that ammount, etc. The thing is that I want the fields to have actual names, instead of being treated as an index. My original idea to implement this was creating a base class Rn w...
I'll only address the technical difficulty, not whether this is a good idea or not. The problem is that the result of operator* of Derived is a Base, and operator= of Derived (which is a default operator=) doesn't know how to "eat" a Base. A simple solution is to create a constructor of Derived that gets a Base, and do...
746,414
746,608
What is the best way to get all Windows startup processes using Windows API?
I know there are startup folders and certain registry keys I need to look into. But how to do that using Windows API? I'm interested to know for Windows XP and Vista. Thanks for your time.
There is no single API to get all the programs that run while the system is starting up. Consider all the things that Autoruns shows. Updates to that program occasionally allow it to show new classes of programs, and since those are updates to the program and not to the OS, it's obviously not some API that's changing t...
746,604
746,653
Bind pointer to member operators in C++
What is the point of them? I've never used them for anything, and I can't see myself needing to use them at all. Am I missing something about them or are they pretty much useless? EDIT: I don't know much about them, so a description about them might be necessary...
A PMF (pointer to member function) is like a normal (static) function pointer, except, because non-static member functions require the this object to be specified, the PMF invocation syntax (.* or ->*) allow the this object to be specified (on the left-hand side). Here's an example of PMFs in use (note the "magic" line...
746,702
4,024,686
"endpoint is a duplicate" when starting an RPC server
My program uses Microsoft RPC for interprocess communications. To prepare for receiving RPC calls the program runs the following sequence: RpcServerUseProtseqEp(), then RpcServerRegisterIf(), then RpcServerListen() The program starts its RPC server with the sequence above, works for some time, then terminates and may...
i had the same problem, i can't fixed totally, but this code works for me: UCHAR* pszProtocolSequence = (UCHAR*)"ncacn_ip_tcp"; // Use RPC over TCP/IP UCHAR* pszSecurity = NULL; UCHAR* pszEndpoint = (UCHAR*)"9300"; UINT cMinCalls = 1; UINT cMaxCalls = m_dwConcurrentChannels; UINT fDontWait = FALSE; int RPC_tries, MAX_...
746,735
746,753
Is there a way to use an "ostream" to write over an existing instance of std::string
I know all kinds of ostreams holds their own internal buffers. I have to know whether there is some kind of ostream which accept an instance std::string and write on that instance. (I want to avoid redundant copies) Note: My question is about the standard library, don't offer me other libraries that can do that, I know...
If you are asking can you alter the buffering of ostreams, then the answer is yes. However, depending on what you actually want the buffer to do, this is not a particularly simple task. You will want to consult a book like Langer & Kreft for more info. L&K have an example of how to implement an unbuffered output strea...
746,879
754,531
Using MFC MDI with multiple top level window
I am working with a multiple top level windows application. The main window is a MDIFrameWnd, I put some code in CWinApp to switch m_pMainWnd when switch top level window. It's work fine but fire a assert when I close one of the main window. This assert is from CMDIChildWnd: void CMDIChildWnd::AssertValid() const { ...
I found the problem is. A Menu bar control in main frame will destory menu in its dtor. Thanks every one.
747,310
747,344
Debugging on Linux for Windows Developer
Primarily I've done basic (novice level) software development on a Windows machine, but I've always had MS Visual Studio to help me step through the process of debugging. Now, however, it looks like I will be on Linux, so in order to get ready for the jump I want to make sure I have a tool/tools lined up to help me s...
I would suggest using Eclipse Eclipse is a mature IDE with plenty of support available. There is also Code::Blocks if you want to try something different
747,440
747,462
TypeDef as an overridable class feature
If I have a class that contains a number of typedef'd variables, like so: class X { typedef token TokenType; bool doStuff() { TokenType data; fillData(&data); return true; } }; Is there any way to override the typedef for TokenType in a derived class? N.B. This is NOT a good place to use templates (This is already ...
What you can do is shadow, but not override. That is: you can define a derived class Y with its own typedefs for TokenType, but that will only come into play if somebody references Y::TokenType directly or via an object statically typed as Y. Any code that references X::TokenType statically will do so even for objects ...
748,014
748,059
Do I need to manually close an ifstream?
Do I need to manually call close() when I use a std::ifstream? For example, in the code: std::string readContentsOfFile(std::string fileName) { std::ifstream file(fileName.c_str()); if (file.good()) { std::stringstream buffer; buffer << file.rdbuf(); file.close(); return buffer.str(); }...
NO This is what RAII is for, let the destructor do its job. There is no harm in closing it manually, but it's not the C++ way, it's programming in C with classes. If you want to close the file before the end of a function you can always use a nested scope. In the standard (27.8.1.5 Class template basic_ifstream), ifst...
748,085
748,100
How to convert a double* to an array<double>(6)
I have a function that returns a array of 6 doubles. double* Validation(); I would like to cast this return value in managed code. array<double>^ validationPosition = gcnew array<double>(6); validationPosition = Validation(); I get this error: error C2440: '=' : cannot convert from 'double *' to 'cli::array<Type> ^'...
If you want this to be in a managed array, you will need to copy it into the array. The native double* array will not be usable directly as a managed array. You can use Marshall::Copy to copy this, or just loop through your 6 values. You will also want to (probably) delete[] your return values, since it sounds like it...
748,547
754,405
Internet Explorer control won't load CSS and JS
I have embedded an IE control in a Win32 app. The only purpose of this app is to ensure that a URl is always loaded and being refreshed every N minutes. My problem is that almost always the first time the URL is accessed the CSS and JS files are not loaded. This behavior repeats randomly while the application is runnin...
If the purpose is to load URIs, why use the IE control? You can't predict when it will cache. Instead use the the WinInet API http://msdn.microsoft.com/en-us/library/aa383630(VS.85).aspx Here's a tutorial You need to set the desired caching behavior, but you can just program what you want it to do directly without de...
749,061
749,097
In C++, how can I get a pointer into a vector?
I'm writing some C++ code that manipulates a bunch of vectors that are changing in size and are thus being reallocated constantly. I would like to get a "pointer" into these vectors that remains valid even after reallocation of the vector. More specifically, I just want these "pointers" to remember which vector they p...
Try a std::pair< vector*, int>, as neither the position of the vector nor the index of the element changes. Or, as a class: template<class T> class VectorElementPointer { vector<T>& vectorref; typename vector<T>::size_type index; public: VectorElementPointer(vector<T>& vref, typename vector<T>::size_type index):v...
749,129
749,483
std::set filled with boost::variant elements cannot be sorted descendantly?
typedef boost::variant<long long,double,string> possibleTypes ; set<possibleTypes,less<possibleTypes> > ascSet ; set<possibleTypes,greater<possibleTypes> > descSet ; When I try to compile I get a bunch of errors in some library headers. But, if I remove the third line (the one with descSet ) the code compile just fin...
As it was suggested, if I define this: bool operator>(const possibleTypes& a, const possibleTypes& b){ return b < a ; } Then the following code doesn't compile: possibleTypes pt1="a", pt2="b" ; greater<possibleTypes> func ; cout << func(pt1,pt2) << endl ; However, this code compiles just fine: possibleTypes pt1...
749,171
5,326,024
How to attach a winforms dialog to an existing toolbar/menubar (compiled C++ app)?
To attach a winforms dialog on Microsoft Wordpad toolbar/menubar?
First you need to get your assembly loaded into the target process. Then you'll need to use Win32 API functions to create the new menu item, with a unique child ID. Finally, you'll need to subclass the window procedure and process WM_COMMAND messages, which are generated by Windows when a native menu item is selected. ...
749,517
749,555
How to download an image from an URL to a local dir?
I'm using C++ without .NET on Win32, how can I download an image over HTTP from a website without having to re-invent the wheel? Is there an API or library that provides a single function to do this? http://mywebsite/file.imgext --> C:\path\to\dir\file.imgext
You could use cURLpp I havn't used it yet, but example20 looks like it could solve your problem.