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
722,386
722,413
How to get rid of g++ hash_map deprecation warning?
When I compile a c++ application I'm writing that makes use of hash_map, I get this warning on g++ 4.3.2: You are using the deprecated header . To eliminate this warning, use an ANSI-standard header file or use hte -Wno-deprecated compiler flag. 9> #include <ext/hash_map> What include replaces this? I've searched for a while on google, and can't find anything except for people having similar problems, but no solution.
My very first Google hit for "g++ hash_map deprecated" takes me to a page that includes a list of things to use instead of the deprecated headers and classes. For hash_map, the list suggests using unordered_map, in the unordered_map header. The class is new for TR1.
722,555
798,447
Unexposing a snapshot in XP (Volume Shadow Copy)
Microsoft provides a way of mounting a read-only snapshot as a volume using their vshadow program. However, it does not provide a way to unmount the snapshot (I wonder what would happen if I deleted the snapshot?). Going through the documentation on MSDN I found UnexposeSnapshot Method, and added the ability to use it in the vshadow. However, it says that it's only supported for Vista and Server 2008 machines. Is there anyway around this? The XP configuration for vshadow won't compile. It would be really bizarre if Microsoft wrote a way to mount volume shadow copies in XP and server 2003, yet didn't provide a way to unmount them. Any ideas?
Use Windows' built-in mount management utility mountvol.exe. On API level, you should be able to use DeleteVolumeMountPoint.
722,788
722,794
How do I access a C++ subscript operator from within the class in which it resides?
Where, ClassA has an operator as such, that returns ClassB: class ClassA { public: ClassA(); ClassB &operator[](int index); } If I want to access said operator from within ClassA's constructor, as so: ClassA::ClassA() { // How do I access the [] operator? } At the moment, as a work-around I'm just using a method called GetAtIndex(int index) which the [] operator calls, and so does the constructor. It would be nice if I could access it in the same as as C# works: // Note: This is C# class ClassA { ClassB this[int index] { get { /* ... */ } set { /* ... */ } } void ClassA() { this[0] = new ClassB(); } } Note: I'm using g++
Try the following (*this)[0] = ...
722,801
722,870
fast way to parse a configuration
Say you have char *= "name:454"; What is the best way to parse name and the number, thus std:string id would equal to "name"; double d would equal to 454; STL please, no boost.
#include <iostream> #include <sstream> #include <string> int main() { /* output storage */ std::string id; double d; /* convert input to a STL string */ std::string s("name:454"); size_t off = std::string::npos; /* smart replace: parsing is easier with a space */ if ((off = s.find(':')) != std::string::npos) { // error check: all or none s = s.replace(off, 1, 1, ' '); std::istringstream iss(s); iss >> id >> d; std::cout << "id = " << id << " ; d = " << d << '\n'; } return 0; } Though, I'd just write my own parser or use the C scanner function for speed.
722,814
722,840
What is a good multiplatform vector graphics library for C/C++?
I'm looking for a good multiplatform library for vector graphics in C/C++. Any recommendation or thougts? Thanks EDIT: Thanks for all your answers!! Could anyone tell me the pros and cons of qt vs cairo, for example? Cairo got more votes, but it seems to be from 5 to 7 times slower according to some benchmarks...
You can try out Cairo - it's opensource, not too heavy and has a flexible license.
722,822
722,879
Correct place to initialize class variables?
Where is the correct place to initialize a class data member? I have the class declaration in a header file like this: Foo.h: class Foo { private: int myInt; }; Then I try to set a value to myInt in the corresponding .cpp file: Foo.cpp: int Foo::myInt = 1; I get a compiler error for redefining myInt. What am I doing wrong???
What you have there is an instance variable. Each instance of the class gets its own copy of myInt. The place to initialize those is in a constructor: class Foo { private: int myInt; public: Foo() : myInt(1) {} }; A class variable is one where there is only one copy that is shared by every instance of the class. Those can be initialized as you tried. (See JaredPar's answer for the syntax) For integral values, you also have the option of initializing a static const right in the class definition: class Foo { private: static const int myInt = 1; }; This is a single value shared by all instances of the class that cannot be changed.
722,838
722,848
beginner c++: virtual functions in a base class
I'm writing some code where I defined the following base class. class Chorus{ public: //Destructor virtual ~Chorus(); //callback function virtual int callback( void *outputBuffer, void *notUsed, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void *userData ); virtual void initializeDelayBuffer(void); virtual void destroyDelayBuffer(void); }; I want to use this as a base class and not actually do anything with it on its own. So I have two seperate classes which are derived from this class Chorus. I wanted to do this to simply provide some basic constraints as to what any derived Chorus class MUST have to be considered usable in my program. When I build my project (Visual Studio 2008), I get unresolved external symbol errors on all the virtual functions from this Chorus class. I'm guessing it's the typical error where I didn't make forward declarations of these functions. But, since they are virtual and I don't want them to actually be defined to do anything until they are defined within the deriving classes, what do I do to resolve this issue?
If your intent is for them to be simply place holders for child classes to implement, then make them pure virtual functions by ending with = 0. For example virtual void destroyDelayBuffer(void) = 0; This makes the method "abstract" so to speak. The C++ compiler will not look for an actual definition of the method but instead will force all derived classes to implement these methods before an instance can be created.
722,932
722,958
Complicated error LNK2005: already defined C++
I'm getting the LNK2005: already defined in (...) error when building my project in Visual Studio 2008. I've referenced other related questions, but mine seems to be a bit more complicated due if nothing else to the number of files I'm working with. First, I think it will be helpful for me to map out the #include statements I have in the files of my project in the format [current_file] ->includes_this_file All my header files are guarded with the standard #ifndef [Header] #define [Header] ... #endif. [Modulator.h] prototypes for Modulator class [ChorusUnit.h] ->Modulator.h prototypes for Chorus classes which have member objects of type Modulator [AudioHandler.h] ->ChorusUnit.h prototypes for AudioHandler class which has member objects of Chorus classes [Chorus.cpp] ->AudioHandler.h definitions for the members of Modulator and Chorus classes [AudioHandler.cpp] ->Chorus.cpp definitions for the members of AudioHandler class [ChorusUnit.cpp] ->AudioHandler.cpp the file containing the main() function that actually runs the code of my project. The ordering of includes is because all the definitions of functions to the classes found in Modulator.h, ChorusUnit.h, and AudioHandler.h need to reference members of the other classes, so I needed the prototypes defined first for all the classes to see each other. The error specifically says that every single definition found in Chorus.cpp and AudioHandler.cpp in file Chorus.obj is already defined in AudioHandler.obj. Also there is another set of the same error type that says every single definition found in Chorus.cpp and AudioHandler.cpp in file ChorusUnit.obj is already defined in AudioHandler.obj. There is probably a pretty straightforward solution, but I am not particularly experience (being mostly a Java programmer) in linking in general. As far as my limited knowledge on the subject goes, I only defined everything once and everything was only included once so I'm personally at a loss as to why these are already defined. Some please enlighten me!
The error is probably that you say you #include Chorus.cpp in AudioHandle.cpp - this is not what you probably want. The reason is, that all .cpp files (unless you've done something special in your IDE) are compiled separately, then linked. When you #include another .cpp file, the file's text is literally included; therefore, all objects defined in the included file appear in the including file as well. When you link the two files, the common objects cause a conflict.
723,344
723,398
method running on an object BEFORE the object has been initialised?
#include <iostream> using namespace std; class Foo { public: Foo(): initialised(0) { cout << "Foo() gets called AFTER test() ?!" << endl; }; Foo test() { cout << "initialised= " << initialised << " ?! - "; cout << "but I expect it to be 0 from the 'initialised(0)' initialiser on Foo()" << endl; cout << "this method test() is clearly working on an uninitialised object ?!" << endl; return Foo(); } ~Foo() {}; private: int initialised; }; int main() { //SURE this is bad coding but it compiles and runs //I want my class to DETECT and THROW an error to prevent this type of coding //in other words how to catch it at run time and throw "not initialised" or something Foo foo=foo.test(); }
You can't prevent people from coding poorly, really. It works just like it "should": Allocate memory for Foo (which is the value of the "this" pointer) Going to Foo::test by doing: Foo::test(this), in which, It gets the value by this->initialised, which is random junk, then it Calls Foo's default constructor (because of return Foo();), then Call Foo's copy constructor, to copy the right-handed Foo(). Just like it should. You can't prevent people from not knowing the right way to use C++. The best you could do is have a magic number: class A { public: A(void) : _magicFlag(1337) { } void some_method(void) { assert (_magicFlag == 1337); /* make sure the constructor has been called */ } private: unsigned _magicFlag; } This "works" because the chances _magicFlag gets allocated where the value is already 1337 is low. But really, don't do this.
723,581
723,613
How did I break inheritance?
Refactored from bug_report_view.cc and bug_report_view.h, I extracted send_report(), report_phishing(), a few other smaller functions and BugReport::Cleanup into bug_report.cc and bug_report.h (my versions). Compiling now, I get: [...]bug_report.cc:196: error: no matching function for call to ‘URLFetcher::URLFetcher(std::wstring&, URLFetcher::RequestType, BugReport::PostCleanup*)’ ../chrome/browser/net/url_fetcher.h:136: note: candidates are: URLFetcher::URLFetcher(const URLFetcher&) ../chrome/browser/net/url_fetcher.h:82: note: URLFetcher::URLFetcher(const GURL&, URLFetcher::RequestType, URLFetcher::Delegate*) For some reason, BugReport::PostCleanup (in my version) isn't recognized as a subclass of URLFetcher::Delegate, but BugReportView::PostCleanup (in the first links) is. So where did I mess up? Thanks.
The problem is not the type of the PostCleanup class. The problem is the type of the first parameter to the URLFetcher class constructor. The constructor expects a GURL &, you are passing a std::wstring called post_url. You will need to perform some kind of conversion between the two. Possibly something like this would be appropriate: GURL post_url(l10n_util::GetString(IDS_BUGREPORT_POST_URL)); URLFetcher* fetcher = new URLFetcher(post_url, URLFetcher::POST, new BugReport::PostCleanup); In the code you have modified, the class has a GURL member which is initialised in the constructor, you have changed it to a variable referenced only in that one function, but changed the type.
723,702
723,720
Inheritance vs Specialization
Considering the following two usage scenarios (exactly as you see them, that is, the end-user will only be interested in using Vector2_t and Vector3_t): [1]Inheritance: template<typename T, size_t N> struct VectorBase { }; template<typename T> struct Vector2 : VectorBase<T, 2> { }; template<typename T> struct Vector3 : VectorBase<T, 3> { }; typedef Vector2<float> Vector2_t; typedef Vector3<float> Vector3_t; [2]Specialization: template<typename T, size_t N> struct Vector { }; template<typename T> struct Vector<T, 2> { }; template<typename T> struct Vector<T, 3> { }; typedef Vector<float, 2> Vector2_t; typedef Vector<float, 3> Vector3_t; I can't make up my mind as to which is a nicer solution. The obvious advantage to inheritance is code reuse in the derived classes; a possible disadvantage being performance (bigger size, users may pass by value, etc). Specialization seems to avoid all that, but at the expense of me having to repeat myself multiple times. What other advantages/disadvantages did I miss, and in your opinion, which route should I take?
What you ultimately want, i think, is to have the user type Vector<T, N> And depending on N, the user will get slight different things. The first will not fulfill that, but the second will, on the price of code duplication. What you can do is to invert the inheritance: template<typename T, size_t N> struct VectorBase { }; template<typename T> struct VectorBase<T, 2> { }; template<typename T> struct VectorBase<T, 3> { }; template<typename T, size_t N> struct Vector : VectorBase<T, N> { }; And implement the few functions that depend only on N being some specific value in the appropriate base-class. You may add a protected destructor into them, to prevent users deleting instances of Vector through pointers to VectorBase (normally they should not even be able to name VectorBase: Put those bases in some implementation namespace, like detail). Another idea is to combine this solution with the one mentioned in another answer. Inherit privately (instead of publicly as above) and add wrapper functions into the derived class that call the implementations of the base-class. Yet another idea is to use just one class and then enable_if (using boost::enable_if) to enable or disable them for particular values of N, or use a int-to-type transformer like this which is much simplier struct anyi { }; template<size_t N> struct i2t : anyi { }; template<typename T, size_t N> struct Vector { // forward to the "real" function void some_special_function() { some_special_function(i2t<N>()); } private: // case for N == 2 void some_special_function(i2t<2>) { ... } // case for N == 3 void some_special_function(i2t<3>) { ... } // general case void some_special_function(anyi) { ... } }; That way, it is completely transparent to the user of Vector. It also won't add any space overhead for compilers doing the empty base class optimization (quite common).
723,762
723,780
Programs causing static noise in speakers?
Does anyone know a reason why my programs could be causing my speakers to output some soft static? The programs themselves don't have a single element that outputs sound to anything, yet when I run a few of my programs I can hear a static coming from my speakers. It even gets louder when I run certain programs. Moving the speakers around doesn't help, so it must be coming from inside the computer. I'm not sure what other details to put down since this seems very odd. They are OpenGL programs written in C++ with MS Visual C++. Edit: It seems to be that swapping the framebuffers inside an infinite loop is making the noise, as when I stop swapping I get silence...
Since you say you don't touch sound in your programs, I doubt it's your code doing this. Does it occur if you run any other graphics-intensive programs? Also, what happens if you mute various channels in the mixer (sndvol32.exe on 32-bit windows)? Not knowing anything else I'd venture a guess that it could be related to the fan on your graphics card. If your programs cause the fan to turn on and it's either close to your sound card or the fan's power line crosses an audio cable, it could cause some static. Try moving any audio cables as far as possible from the fan and power cables and see what happens. It could also be picking up static from a number of other sources, and I wouldn't say it's necessarily unusual. If non-graphics-intensive programs cause this as well, it could be hard-disk access, or even certain frequencies of CPU/power usage being picked up on an audio line like an antenna. You can also try to reduce the number of loops in your audio wires and see if it helps, but no guarantees.
723,796
723,829
Linking error in C++ - implementing a indexList
Linking... Directory.obj : error LNK2019: unresolved external symbol "public: void __thiscall indexList<class entry,100>::read(class std::basic_istream<char,struct std::char_traits<char> > &)" (?read@?$indexList@Ventry@@$0GE@@@QAEXAAV?$basic_istream@DU?$char_traits@D@std@@@std@@@Z) referenced in function _main Getting this error and others associated with indexList implementation. I have included all the right files, not sure what this means? indexList.h indexList.cpp Also, using VS .NET 2003 - They are under the "Source Files" and "Header Files" However, I tested with deleting the indexLish.h and the error doesn't change?
What you have is a class template. This means when the compiler needs to call a function, it will look at your template definition and generate the corresponding code as needed. For example, the following probably has a compile-time error in it if tried to call it: template <typename T> void doSomething(const T& x) { x->_this_function_does_not_exist_ever_(); } But as long as you don't call doSomething you won't get errors. The problem you have is that your header file tells the compiler "hey, these functions exist", but when the compiler tries to generate them it cannot find any definitions. (You cannot "compile" definitions in a source file and link them in, they must be visible to the caller.) The most common solution is to simply define the entire class template in the .h or .hpp file.
723,973
723,974
Will the initialization list always be processed before the constructor code?
Will the initialization list always be processed before the constructor code? In other words, will the following code always print <unknown>, and the constructed class will have "known" as value for source_ (if the global variable something is true)? class Foo { std::string source_; public: Foo() : source_("<unknown>") { std::cout << source_ << std::endl; if(something){ source_ = "known"; } } };
Yes, it will, as per C++11: 12.6.2 /10 (same section in C++14, 15.6.2 /13 in C++17): In a non-delegating constructor, initialization proceeds in the following order (my bold): First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list. Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers). Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers). Finally, the compound-statement of the constructor body is executed. The main reason for using init-lists is to help the compiler with optimisation. Init-lists for non-basic types (i.e., class objects rather than int, float, etc.) can generally be constructed in-place. If you create the object then assign to it in the constructor, this generally results in the creation and destruction of temporary objects, which is inefficient. Init-lists can avoid this (if the compiler is up to it, of course but most of them should be). The following complete program will output 7 but this is for a specific compiler (CygWin g++) so it doesn't guarantee that behaviour any more than the sample in the original question. However, as per the citation in the first paragraph above, the standard does actually guarantee it. #include <iostream> class Foo { int x; public: Foo(): x(7) { std::cout << x << std::endl; } }; int main (void) { Foo foo; return 0; }
723,975
723,980
Do I need to use reference parameters for returning values?
If a HANDLE is an output parameter, is it necessary to use a reference to the HANDLE or use HANDLE directly? bool fn(HANDLE h_result); or bool fn(HANDLE& h_result);
To return values you can: Use a reference as a parameter Use a pointer as a parameter Actually return the value via return When you specify the following: bool fn(HANDLE h_result); You are making a copy of h_result. So if you change it in your function, you are changing the copy, not the original. When dealing with pointers, the concept is exactly the same. Just remember that a pointer is simply a variable that holds a memory address. It doesn't matter what's in that memory address. If you want to return a memory address via a parameter, then you need to use a pointer to a pointer or a pointer reference.
724,060
726,519
How do I render text on to a square (4 vertices) in OpenGL?
I'm using Linux and GLUT. I have a square as follows: glVertex3f(-1.0, +1.0, 0.0); // top left glVertex3f(-1.0, -1.0, 0.0); // bottom left glVertex3f(+1.0, -1.0, 0.0); // bottom right glVertex3f(+1.0, +1.0, 0.0); // top right I guess I can't use glutBitmapCharacter, since this is only ideal for 2D ortho. Simple enough, I'd like to render "Hello world!" anywhere on said square. Should I create a texture and then apply it to the vertices using glTexCoord2f?
The simplest way is to load a font map from a image, such as those generated by the bitmap font builder (I know it's windows but I can't find one for linux), eg: The example is a 256x256 gif, though you may what to convert it to a png/tga/bmp. It's full ASCII mapped gird, 16x16 characters. Load the texture and use glTexCoord2f to line it up on your quad, and you should be good to go. Here's an example using a bitmap of the above: unsigned texture = 0; void LoadTexture() { // load 24-bit bitmap texture unsigned offset, width, height, size; char *buffer; FILE *file = fopen("text.bmp", "rb"); if (file == NULL) return; fseek(file, 10, SEEK_SET); fread(&offset, 4, 1, file); fseek(file, 18, SEEK_SET); fread(&width, 1, 4, file); fread(&height, 1, 4, file); size = width * height * 3; buffer = new char[size]; fseek(file, offset, SEEK_SET); fread(buffer, 1, size, file); glEnable(GL_TEXTURE_2D); glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, buffer); fclose(file); printf("Loaded\n"); } void DrawCharacter(char c) { int column = c % 16, row = c / 16; float x, y, inc = 1.f / 16.f; x = column * inc; y = 1 - (row * inc) - inc; glBegin(GL_QUADS); glTexCoord2f( x, y); glVertex3f( 0.f, 0.f, 0.f); glTexCoord2f( x, y + inc); glVertex3f( 0.f, 1.f, 0.f); glTexCoord2f( x + inc, y + inc); glVertex3f( 1.f, 1.f, 0.f); glTexCoord2f( x + inc, y); glVertex3f( 1.f, 0.f, 0.f); glEnd(); }
724,084
724,134
Howto incorporate -I in makefile
I have no problem compiling specific code the following way: g++ -I /opt/local/include Code1.cc -o Code1 However when I tried to do that in the makefile: CXX = g++ -Wall -Werror -gstabs -pedantic -O2 -g all: Code3 Code2 Code1 Code3: Code3.cc Tools.cc $(CXX) $^ -o $@ Code2: Code2.cc Tools.cc $(CXX) $^ -o $@ Code1: Code1.cc Tools.cc $(CXX) -I /opt/local/include $^ -o $@ It complains. What's the correct way to do it? Note that only Code1.cc require the external library as include. The header of Code1.cc looks like this: #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <iomanip> #include <boost/math/distributions/chi_squared.hpp> using namespace std; using boost::math::chi_squared; using boost::math::quantile; The error I get is as follows: g++ -Wall -Werror -gstabs -pedantic -O2 -g -I/opt/local/include Code1.cc Tools.cc -o EstimateErrorMean In file included from /opt/local/include/boost/detail/lcast_precision.hpp:16, from /opt/local/include/boost/lexical_cast.hpp:31, from /opt/local/include/boost/math/special_functions/gamma.hpp:23, from /opt/local/include/boost/math/distributions/chi_squared.hpp:13, from EstimateErrorMean.cc:19: /opt/local/include/boost/integer_traits.hpp:164:66: error: use of C99 long long integer constant /opt/local/include/boost/integer_traits.hpp:164:77: error: use of C99 long long integer constant /opt/local/include/boost/integer_traits.hpp:170:70: error: use of C99 long long integer constant
-pedantic causes all required warnings to be reported, and -Werror causes warnings to be reported as errors. As C++ does not define the "ULL" long long integer constant syntax (C99 does), this is probably being reported and then promoted to full-on error status by g++. Try removing -pedantic. Or try #including <boost/cstdint.hpp>.
724,096
758,222
Disk Based Dynamic Memory Allocation
I have a program in which I want to be able to store certain data (dynamically allocated blocks), on disk for reduced memory usage and persistence. My first thought was to write my own custom allocator which managed the content of files on the disk, but I want to see what alternatives there are too. I've looked into custom memory allocators and topics on object serialization but there are subtle differences, both good and bad, when adapting those principles to managing the address space of a file. In this situation: Memory is accessed only through IO (read/write) functions rather than directly No objects(methods/pointers) are stored, only data. The size of a file is not static, so it should grow when needed rather than being large and static For my uses, it is acceptable to re-map existing pointers after defragmentation Because the data is not of a fixed size, most database implementations seem not well suited. I ask, what is the best approach for this problem? Should I implement a simple memory allocator which treats a file as the heap? For reference, im using C++ on embedded devices. Edit: I've implemented my own memory manager which uses buddy memory allocation and block sizes of powers of two. I'm satisfied that it is correct and does not leak, coalesces free blocks, and can do a 'stop the world' defragmentation. The problem is, as expected, there is quite a bit of internal and external fragmentation. I'm not an expert in this field and although I find it fascinating (I'm still a student), I wonder if there are any other implementations that have done the same or similar thing? Surely I cant be the only one? Some helpful but so far incompatible topics are: mmap tbh I havent used mmap but, it addresses the file IO, but not the management of the file address space. BOOST:serialization I have a (probably unjustified) reluctance to use boost libraries at the moment. STXXL Interesting but doesnt address variable size memory allocation Doug Lea Memory Allocator Has very good insights into issues with memory allocators, but I'm not in a position to try and make my own implementation
Your two goals are to reduce memory usage and persist your data. That definitely sounds like a job for a database. But then you say Because the data is not of a fixed size, most database implementations seem not well suited. I think you'll be interested in this distinctive feature of SQLite (a very lightweight cross-platform database with public domain source code): Variable-length records ... SQLite, in contrast, use only the amount of disk space actually needed to store the information in a row. If you store a single character in a VARCHAR(100) column, then only a single byte of disk space is consumed. (Actually two bytes - there is some overhead at the beginning of each column to record its datatype and length.) It also is a good choice for embedded development: Embedded devices and applications Because an SQLite database requires little or no administration, SQLite is a good choice for devices or services that must work unattended and without human support. SQLite is a good fit for use in cellphones, PDAs, set-top boxes, and/or appliances. It also works well as an embedded database in downloadable consumer applications.
724,156
724,166
Keyboard input hesitation when held down?
Does anyone know why there is some hesitation when you hold down a keyboard key and try to process it? I'm calling a function right in my WinProc(...) that will move an image on the screen (OpenGL) when a key is held down. I press it and get a single response, then there is about .5 seconds of nothing, then it behaves as normal (moves 1 pixel every WinMain loop). I'm wondering if the Windows messages are being delayed somehow because of some feature I need to disable??? Here's my code: int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hprevinstance, LPSTR lpcmdline, int nshowcmd) { bool quit = false; MSG msg; createWindow(hinstance, SCRW, SCRH, SCRD, WINDOWED); // Main loop while (!quit) { if (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) { if (msg.message == WM_QUIT) quit = true; TranslateMessage(&msg); DispatchMessage(&msg); } renderFrame(); // processes graphics SwapBuffers(hdc); } return msg.lParam; } and WinProc (there were more cases but same thing...): LRESULT CALLBACK WinProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { switch(msg) { case WM_KEYDOWN: switch ( wparam ) { case VK_RIGHT: key_RIGHT(); return 0; } return 0; } } and key_RIGHT: void key_RIGHT() { MoveObjectRight1Pixel(); }
It's a rather standard keyboard setting to have a small delay between when the key was pressed and when repeat messages get generated. Instead of processing keyboard input in your Windows message handler, you could instead keep an array of 256 bits indicating the current state of the keyboard. When you receive a WM_KEYDOWN or WM_KEYUP, you update the bit of the corresponding key. Then, in your main loop, you check the current state of the key and the previous state of the key (by keeping a second array of 256 bits that you make a copy to every frame). If the key is currently down but was not down in the previous frame, then you move your object accordingly. Another alternative is to use the GetAsyncKeyState() function.
724,347
724,392
Can file pointer change during the process of write or read of a CFile object
I have a CFile object, which can be accessed by multiple threads. There is the possibility that one thread is writing data to this file while another thread is reading data from the file. I want to know is there any unsafety under this policy? Can the file pointer change before the write or read process complete? Is the answer is yes, how to avoid the unsafety of multi-thread which can be reading or writing at the same time? Thank you very much!
CFile objects are not thread-safe. If you need to access them from multiple threads, you'll need to perform your own synchronization. From http://msdn.microsoft.com/en-us/library/aa270950.aspx: Accessing Objects from Multiple Threads For size and performance reasons, MFC objects are not thread-safe at the object level, only at the class level. This means that you can have two separate threads manipulating two different CString objects, but not two threads manipulating the same CString object. If you absolutely must have multiple threads manipulating the same object, protect such access with appropriate Win32 synchronization mechanisms, such as critical sections. For more information on critical sections and other related objects, see in the Win32 SDK. The class library uses critical sections internally to protect global data structures, such as those used by the debug memory allocation.
724,465
724,544
How to check for TR1 while compiling?
We are programming a logging library that keeps itself in a .hpp file. We would like to include <tr1/unordered_map> (if the compiler supports TR1,) or the standard <map> otherwise. Is there a standard way of checking at compile time if tr1 is available or not? I was thinking that the same way that the "__cplusplus" define symbol is present, there could have been defined a "__cxx__tr1" or something like that. I haven't seen that in the drafts for TR1, so I assume it is not present, but I wanted to ask first just in case. As a note, if those defines don't exist, it wouldn't be a bad idea to include them in proposals themselves.
If you are using any configuration tools like autotools you may try to write a test like: AC_CHECK_HEADER(tr1/unordered_map,[AC_DEFINE([HAVE_TR1],[],["Have tr1"])],[]) AC_CHECK_HEADER(unordered_map,[AC_DEFINE([HAVE_CXX0X],[],["Have C++0x"])],[]) And then use these defines in your code. Generally speaking __cplusplus macro should give you standard version number, but there is no compiler that gives you 100% standard implementation... Thus write configure macros. Unfortunately this is only quite reliable way to check such things unless you want to write 1001 #ifdef for each compiler (what boost does) And then: #include "config.h" #ifdef HAVE_CXX0X # include <unordered_map> typedef std::unordered_map<foo,bar> my_map; #elif HAVE_TR1 # include <tr1/unordered_map> typedef std::tr1::unordered_map<foo,bar> my_map; #else # include <map> typedef std::map<foo,bar> my_map; #endif
724,536
730,868
Does memory stay allocated when a C++ thread exits?
I'm using the pthread library on Linux. I'm assigning a string in thread A, and then trying to print the string in thread B. However, the string just prints out empty (I have verified that it works in thread A). Note: The string resides inside an object, which I suspect may be getting cleaned up or re-instantiated empty... The container object doesn't give me a seg fault or anything, just all the values are empty. Is this because threads cannot access memory from other threads, or because the memory is being unallocated once thread A stops? Or is it neither; it could well be a bug in my code, but I just wanted to rule this out... Update: Turns out it was a memory issue. With thanks to your answers, I have also answered this my self, please do comment on my answer if you agree/disagree.
Turns out, the issue was caused by incorrect use of memory, as expected. I'm 99% sure the following example is accurate; it's pretty much pseudo code, so wont compile, obviously. Update: Just added a 3rd solution thanks to nusi. The wrong way (with stack memory): std::map<int, MyType1> myMap; void firstFunctionRunFromThread1() { MyType1 mt1; mt1.Test = "Test 1"; myMap[0] = mt1; } void onlyFunctionRunFromThread2() { MyType1 mt1 = myMap[0]; // This actually does print "Test 1", so the memory is being accessed. std::cout << mt1.Test << endl; /* However, because we're using stack memory here, this value is lost * when we go back to thread #1. */ mt1.Test = "Test 2"; } void secondFunctionFromThread1() { MyType1 mt1 = myMap[0]; // This will actually print out "Test 1", where "Test 2" is expected! std::cout << mt1.Test << endl; } The complicated, correct method (using heap memory): See also the simple method which uses stack memory. std::map<int, MyType1> myMap; void firstFunctionRunFromThread1() { // Use heap memory so the memory stays allocated. MyType1 *mt1 = new MyType1(); mt1->Test = "Test 1"; myMap[0] = *mt1; } void onlyFunctionRunFromThread2() { /* Now, get a pointer to the object; we can't use stack memory * here because the values assigned would be lost as soon as * we try and access them from secondFunctionFromThread1() */ MyType1 *mt1 = &myMap[0]; // As expected, this prints "Test 1" std::cout << mt1->Test << endl; /* Now, because we're assigning to memory on the heap, this will * stay assigned until the entire application exits, yay! */ mt1->Test = "Test 2"; } void secondFunctionFromThread1() { /* Not sure if using heap memory here is neccecary, but we'll do * it anwyay just to play on the safe side... let me know if this * is pointless... */ MyType1 *mt1 = &myMap[0]; // Hurray, this prints "Test 2"!!! :) std::cout << mt1->Test << endl; } The simple, correct method (using stack memory correctly): Thanks to nusi for his answer. std::map<int, MyType1> myMap; void firstFunctionRunFromThread1() { MyType1 mt1; mt1.Test = "Test 1"; myMap[0] = mt1; } void onlyFunctionRunFromThread2() { /* Using the & before the variable turns it into a reference, so * instead of using stack memory, we use the original memory. * NOTE: Is this explanation correct? */ MyType1 &mt1 = myMap[0]; // This actually does print "Test 1", so the memory is being accessed. std::cout << mt1.Test << endl; // We're assigning to the reference, so this works. mt1.Test = "Test 2"; } void secondFunctionFromThread1() { MyType1 mt1 = myMap[0]; // Prints "Test 1" as expected. std::cout << mt1.Test << endl; }
724,765
724,838
Problem using pthread to utilize multiple cores
I’m developing a Ray Tracer in C++ using SDL and Pthread. I’m having issues making my program utilize two cores. The threads work, but they don’t use both cores to 100%. To interface SDL I write directly to it's memory, SDL_Surface.pixels, so I assume that it can't be SDL locking me. My thread function looks like this: void* renderLines(void* pArg){ while(true){ //Synchronize pthread_mutex_lock(&frame_mutex); pthread_cond_wait(&frame_cond, &frame_mutex); pthread_mutex_unlock(&frame_mutex); renderLinesArgs* arg = (renderLinesArgs*)pArg; for(int y = arg->y1; y < arg->y2; y++){ for(int x = 0; x < arg->width; x++){ Color C = arg->scene->renderPixel(x, y); putPixel(arg->screen, x, y, C); } } sem_post(&frame_rendered); } } Note: scene->renderPixel is const, so I assume both threads can read from the same memory. I have two worker threads doing this, in my main loop I make these work using: //Signal a new frame pthread_mutex_lock(&frame_mutex); pthread_cond_broadcast(&frame_cond); pthread_mutex_unlock(&frame_mutex); //Wait for workers to be done sem_wait(&frame_rendered); sem_wait(&frame_rendered); //Unlock SDL surface and flip it... Note: I've also tried creating and joining the threads instead of synchronizing them. I compile this with "-lpthread -D_POSIX_PTHREAD_SEMANTICS -pthread" and gcc does not complain. My problem is best illustrated using a graph of the CPU usage during execution: (source: jopsen.dk) As can be seen from the graph my program only uses one core at a time, then switching between the two every once in a while, but it doesn't drive both to 100% ever. What in the world have I done wrong? I'm not using any mutex or semaphors in scene. What can I do to find the bug? Also if I put while(true) around scene->renderPixel() I can push both cores to 100%. So I've suspected that this is caused by overhead, but I only synchronize every 0.5 second (e.g. FPS: 0.5), given a complex scene. I realize it might not be easy to tell me what my bug is, but an approach to debugging this would be great too... I haven't played with pthreads before... Also, can this be a hardware or kernel issue, my kernel is: $uname -a Linux jopsen-laptop 2.6.27-14-generic #1 SMP Fri Mar 13 18:00:20 UTC 2009 i686 GNU/Linux Note:
This is useless : pthread_mutex_lock(&frame_mutex); pthread_cond_wait(&frame_cond, &frame_mutex); pthread_mutex_unlock(&frame_mutex); if you wait to wait for a new frame do something like : int new_frame = 0; First thread : pthread_mutex_lock(&mutex); new_frame = 1; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); other thread : pthread_mutex_lock(&mutex); while(new_frame == 0) pthread_cond_wait(&cond, &mutex); /* Here new_frame != 0, do things with the frame*/ pthread_mutex_unlock(&mutex); pthread_cond_wait(), actually release the mutex, and unschedule the thread until the condition is signaled. When the condition is signaled the thread is waken up and the mutex is re-taken. All this happen inside the pthread_cond_wait() function
725,040
725,066
Converting (void*) to std::vector<unsigned char>
I have a (void*) buffer that I need to convert to std::vector<unsigned char> before I can pass it on. Unfortunately, my C++ casting skills a little weak. Any suggestions?
You will need the length of the buffer. Once you do, we can do this: unsigned char *charBuf = (unsigned char*)voidBuf; /* create a vector by copying out the contents of charBuf */ std::vector<unsigned char> v(charBuf, charBuf + len); Okay, the comment got me started on why I did not use reinterpret_cast: In C++, the C-style cast is a convenience function -- it asks the compiler to choose the safest and most portable form of conversion over the set of available cast operators. The reinterpret_cast is implementation defined and should always be the last thing on your mind (and used when you are necessarily doing a non-portable thing knowingly). The conversion between (unsigned doesn't change the type) char * and void * is portable (you could actually use static_cast if you are really picky). The problem with the C-style cast is: the added flexibility can cause heartaches when the pointer type changes. Note: I agree with the general convention of not casting as much as possible. However, without any source provided, this is the best I could do.
725,138
725,144
How to detect 'strict aliasing' at compile time?
'Strict aliasing' optimization needs special care from the source code, s.a. using a union instead of pointer casts. Is there a way to detect using preprocessor directives (#if/else) whether the compiler is trying to do such optimizations? I would like to maintain the old and non-strict-aliasing-prepared code path for processors and compilers that don't care. It seems faster. Edit: GCC predefined macros does not seem to have anything about aliasing. In other words, I'm most interested on gcc 4.x, but also in a general solution (which does not seem to exist).
Completely implementation dependant - you need to check the docs for your specific compiler(s). And when asking questions like this, it's a good idea to mention which compiler(s) you are using. A semi-portable way to do this is from your Makefile - define different targets for aliased & unaliased versions and define your own STRICT_ALIASING (or whatever) preprocessor symbol for the aliased version.
725,142
725,197
How does a reference-counting smart pointer's reference counting work?
In other words, how does the implementation keeps track of the count? Is there a map-like object maintained which is accessible by all the shared_ptr instances whose key is the pointer's address and value is the number of references? If I've to implement a shared_ptr, this is the first idea that's coming to my mind. Is there a possibility for a memory leak in case of these reference-counting smart pointers? If so, how can I avoid them?
I've seen two different non-intrusive approaches to this: The smart pointer allocates a small block of memory to contain the reference counter. Each copy of the smart pointer then receives a pointer to the actual object and a pointer to the reference count. In addition to an object pointer, each smart pointer contains a previous and next pointer, thereby forming a doubly-linked list of smart pointers to a particular object. The reference count is implicit in the list. When a smart pointer is copied, it adds itself to the list. Upon destruction, each smart pointer removes itself from the list. If it's the last one in the list it then frees the referenced object as well. If you go here and scroll to the bottom, there is an excellent diagram which explains these methods much more clearly.
725,375
725,531
Const-correct Notifier in Observer Pattern
I want to implement an Observer of a Model class which does not change the Model. Thus, it should be able to use a const-Reference to access the Model. But the Registering of the Observer prohibits this. Here is how the observer pattern is implemented in my Project: //Attributes of type Observable are used by classes that want to notify others //of state changes. Observing Objects register themselves with AddObserver. //The Observable Object calls NotifyObservers when necessary. class Notifier { public: AddObserver(Observer*); RemoveObserver(Observer*); NotifyObservers(); }; class Model { public: Notifier& GetNotifier() //Is non const because it needs to return a non-const { //reference to allow Observers to register themselves. return m_Notifier; } int QueryState() const; void ChangeModel(int newState) { m_Notifier.NotifyObservers(); } private: Notifier m_Notifier; }; //This View does not Modify the Model. class MyNonModifingView : public Observer { public: SetModel(Model* aModel) //should be const Model* aModel... { m_Model = aModel; m_Model->GetNotifier().AddObserver(this); //...but can't because //SetModel needs to call GetNotifier and add itself, which requires //non-const AddObserver and GetNotifier methods. } void Update() //Part of Observer-Interface, called by Notifiers { m_Model->QueryState(); } }; The only place where a non-modifying observer needs to "change" the Model is when it wants to register with it. I feel that I can not avoid a const_cast here, but I wanted to know if there are better solutions. Sidenote: Put another way, I don't consider the "List of Observers" which a model object manages to be part of the state of the Model. C++ can not tell the difference and lumps state and observers together, forcing both to be const or non-const. Cheers, Felix
If you consider the Notifier object not to be part of the Model object which owns it, so that modifying the Notifier doesn't "count" as modifying the Model, then make getNotifier a const method returning a non-const reference: Notifier& GetNotifier() const //Is const but returns a non-const { //reference to allow Observers to //register themselves. return m_Notifier; } You will then have to either mark m_Notifier as mutable, or else own it by pointer (or smart pointer) or reference rather than by inclusion. Either way, you avoid a const_cast. It is usually preferable to embed objects rather than point/refer to them, but if this is a case where a Notifier isn't considered part of the Model which uses it, then embedding is not essential. Owning it by reference forces you to initialize the reference when Model is constructed, which leads to dependency injection, which is no bad thing. Owning by smart pointer means that, as with embedding, you don't have to do anything about cleanup. There may be other ways to design things (such as Vinay's addition of another class), but your comment "Is non-const because it needs to return a non-const reference" suggests to me that you can do exactly what you originally wanted, you just don't realise you can.
726,002
726,028
C2065 undeclared identifier while assigning a define to an int
I have a small problem with a define. I want to assign it to an integer variable but the compiler says it's undeclared. Here's what the code looks like: defines.h #ifndef DEFINES_H #define DEFINES_H #define MYDEFINE 2 #endif myclass.h namespace mynamespace { class myClass { int someFunction(); }; } myclass.cxx #include "defines.h" #include "myclass.h" namespace mynamespace { int myClass::someFunction() { int var = MYDEFINE; return 0; } } In the line with the int assignment the compiler error takes place. I also tried to use another define, defined in the same header file as above, as a function parameter with the same effect. Any ideas? Thanks in advance. I know using defines is a bad habit, but I only extend an existing project and I try to stay in their design ways. EDIT: The error message simply is: Fehler 1 error C2065: 'MYDEFINE': nichtdeklarierter Bezeichner ... As you might see this is not the real source code, but I think I was very careful while putting together the question. EDIT2: Thanks for the hint with the #warning. There were 2 files with the same name in different folders. I've no idea why the compiler didn't bring this up. Anyway, it works now.
You should check whether the symbol MYDEFINE is really defined. Check whether the header file where it is declared is really included (and compiled). Use #warning near the define to make sure it is compiled for myclass.cxx: #ifndef DEFINES_H #define DEFINES_H #define MYDEFINE 2 #warning My define is defined #endif If it is not compiling (you'll not find the warning message in compilation log), make a search for DEFINES_H. It might be already defined somewhere else.
726,016
726,136
Windows Explorer like folder tree browser
I am trying to implement a platform independent file/directory tree browser. Basically, I am trying to replicate windows explorer's tree control to browse the computer. However, I can't figure out how to find the "Desktop" or "My Computer" folder string (It changes in every pc and os type, version and language). If I can find a way to get the topmost folder string, than I can traverse down and populate the tree hopefully. Is there a registry string somewhere? Initially, I will only target MS Windows os'es (XP, Vista, etc) but later I plan to support Linux and Macs as well. I use wxWidgets for my GUI but I am open to all suggestions for this specific problem. Oh, and I am using C++ in VS2008.
Ignoring portability, what you need is the "PIDL" tree. PIDLs are generalizations of file paths. You can get the PIDLs for special folders with SHGetFolderLocation. The desktop is CSIDL_DESKTOP (not CSIDL_DESKTOPDIRECTORY), My Computer is CSIDL_DRIVES. To convert the PIDLs to names, have a look at SHGetNameFromIDList
726,096
726,123
Accessing private members
Is it appropriate to access a class' private members by casting it to a void pointer and then to a struct? I don't think I have permissions to modify the class that contains the data members that I need to access. I don't want to take a risk accessing the data members in an indirect way if it is not ethical. EDIT: Had to edit this further... I am pretty sure the class wouldn't be modified, so it's ok to that extent... my only concern is, if the person who coded that class gets to know of this, it might not go down well with him :(.
"Never say never". I'm sure somewhere in the universe, there's a situation that will force you to have to do this... But I certainly would cringe if I had to do it. You truly need get lots of opinions on your situation before pulling the trigger. Can you describe your specific situation and maybe we could see if it makes sense or what better alternatives might exist? In response to comment/question-- Define "permissions" -- institutional permission? That sounds like not a programming problem, but something to talk to whoever is asserting said permission. Maybe this is more of a political issue than a technical one? Again, I think we need more specifics--even if it was somewhat about the politics of the situation. That may or may not be deemed out of scope for the website, however.
726,119
727,013
How can you make buttons on a MSVS C++ CToolBar larger along with their images?
We have a touch screen, and the toolbar is too small to hit with my meaty fingers. Is there an easy way I can have an option to make the toolbar buttons bigger and easier to hit? So far I've attempted a few things: m_toolbar.SetSizes( CSize(64,64), CSize(50,50) ); m_toolbar.SetSizes( CSize(64,64), CSize(50,50) ); m_toolbar.GetToolBarCtrl().SetButtonWidth( 64, 64 ); m_toolbar.GetToolBarCtrl().SetButtonSize( CSize(64, 64) ); None of these approaches stretches the images as well. The buttons get larger, and are fully functional, but the images do not overlap the buttons the way they normally would. I would prefer to keep a single image list for the icons, and have the images stretched to fit.
At toolbar creation time, create an empty CImageList with size 64x64 (let's call it large). Load the original image list from resources (we call it small). Iterate over each image in small and copy/resize it to large. Then assign large to your toolbar. Somewhat cumbersome bui should work. HTH,
726,410
726,420
Serialize in C++ then deserialize in C#?
Is there an easy way to serialize data in c++ (either to xml or binary), and then deserialize the data in C#? I'm working with some remote WINNT machines that won't run .Net. My server app is written entirely in C#, so I want an easy way to share simple data (key value pairs mostly, and maybe some representation of a SQL result set). I figure the best way is going to be to write the data to xml in some predefined format on the client, transfer the xml file to my server, and have a C# wrapper read the xml into a usable c# object. The client and server are communicating over a tcp connection, and what I really want is to serialize the data in memory on the client, transfer the binary data over the socket to a c# memory stream that I can deserialize into a c# object (eliminating file creation, transfer, etc), but I don't think anything like that exists. Feel free to enlighten me. Edit I know I can create a struct in the c++ app and define it in c# and transfer data that way, but in my head, that feels like I'm limiting what can be sent. I'd have to set predefined sizes for objects, etc
Protocol Buffers might be useful to you. Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages – Java, C++, or Python. .NET ports are available from Marc Gravell and Jon Skeet.
726,456
726,492
C++ template class error with operator ==
Error: error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const entry' (or there is no acceptable conversion) The function: template <class T, int maxSize> int indexList<T, maxSize>::search(const T& target) const { for (int i = 0; i < maxSize; i++) if (elements[i] == target) //ERROR??? return i; // target found at position i // target not found return -1; } indexList.h indexList.cpp Is this suppose to be an overloaded operator? Being a template class I am not sure I understand the error? Solution- The overload function in the class now declared const: //Operators bool entry::operator == (const entry& dE) const <-- { return (name ==dE.name); }
Start by reading the error text exactly as it is: binary '==' : no operator found which takes a left-hand operand of type 'const entry' It means it can't find any == operator that accepts an entry type as its left operand. This code isn't valid: entry const e; if (e == foo) You've showed us the code for your list class, but that's not what the error is about. The error is about a lack of operators for the entry type, whatever that is. Either give the class an operator== function, or declare a standalone operator== function that accepts a const entry& as its first parameter. struct entry { bool operator==(const entry& other) const; }; // or bool operator==(const entry& lhs, const entry& rhs); I think the latter is the preferred style.
726,664
726,681
String to enum in C++
Is there a way to associate a string from a text file with an enum value? The problem is: I have a few enum values stored as string in a text file which I read on the fly on meeting some condition... Now I want to assign the read value to an enum. What is the most effective way to do so? It doesn't need to be the simplest approach.
You can set up a map that you can use over and over: template <typename T> class EnumParser { map <string, T> enumMap; public: EnumParser(){}; T ParseSomeEnum(const string &value) { map <string, T>::const_iterator iValue = enumMap.find(value); if (iValue == enumMap.end()) throw runtime_error(""); return iValue->second; } }; enum SomeEnum { Value1, Value2 }; EnumParser<SomeEnum>::EnumParser() { enumMap["Value1"] = Value1; enumMap["Value2"] = Value2; } enum OtherEnum { Value3, Value4 }; EnumParser<OtherEnum>::EnumParser() { enumMap["Value3"] = Value3; enumMap["Value4"] = Value4; } int main() { EnumParser<SomeEnum> parser; cout << parser.ParseSomeEnum("Value2"); }
726,698
726,748
Timer message in MFC/Win32
I was just trying the SetTimer method in Win32 with some low values such as 10ms as the timeout period. I calculated the time it took to get 500 timer events and expected it to be around 5 seconds. Surprisingly I found that it is taking about 7.5 seconds to get these many events which means that it is timing out at about 16ms. Is there any limitation on the value we can set for the timeout period ( I couldn't find anything on the MSDN ) ? Also, does the other processes running in my system affect these timer messages?
Windows is not a real-time OS and can't handle that kind of precision (10 ms intervals). Having said that, there are multiple kinds of timers and some have better precision than others.
726,924
726,962
Working with audio in C++
I need to be able to get the length of an audio file (preferably in milliseconds, the timing is very important for the application), and play back the audio. The application is written in C++ on the windows XP platform. Any suggestions for audio formats/3rd party libraries that would do the trick?
The Phonon library (part of Qt) is very powerful and comfortable. It is LGPL. Downside: it's not as performant as some of the game-oriented libraries such as FMod, SDL_Mixer and OpenAL. However, the latency is generally acceptable for desktop apps. As for audio formats: use Ogg Vorbis by default. It's an open standard, royalty free and has better quality than MP3.
727,050
1,850,399
MagickNet C++ Source Compilation Failure
I'm attempting to compile a working copy of the MagickNet class library (DLL) using the sources from the ImageMagick and MagickNet libraries. I was unable to obtain a copy of the MagickNet source files from the creator's homepage as it is currently down, so I was forced to obtain the files and C++ project file from here, courtesy of a Google search. Following the instructions stated here and here, I created a project using the "static multi-threaded DLL" option and compiled it, before moving to the MagickNet project file and compiling that as well, after making sure all the paths pointed to the right folders. Even so, I keep receiving this error upon compilation: CORE_RL_magick_.lib(nt-base.obj) : error LNK2005: _DllMain@12 already defined in MSVCRT.lib(dllmain.obj) I also receive 371 other errors, all of them related to an "unresolved external symbol xxxxxxxx", and a final 372nd error describing that I have "195 unresolved externals". I managed to solve the DllMain error above by commenting out the DllMain declaration from the nt-base.c source file from the CORE_magick project in the ImageMagick solution, however the 372 other "unresolved externals" errors still remain. I had performed a (Google) search for people with similar issues, and some have said that the author had offered a download of a pre-compiled MagickNet DLL which works 100%, however (as I mentioned earlier) his homepage appears to be inaccessible now. I'm currently seeking one of these solutions: A solution to my compilation issue, as I may be making a mistake on my part since I'm not familiar with C++ at all, A link to another MagickNet source files/project zip that is 100% confirmed to compile correctly with the latest version of ImageMagick, A link to a 100% working precompiled copy of the MagickNet DLL, if anyone kept a copy from the author's homepage. It should be approximately 3MB as it contains the ImageMagick libraries as well. I would really appreciate any one of these solutions, as I desperately require ImageMagick's ability to manipulate and convert images, as well as MagickNet's ease of use. I can provide additional details if you need more information. Also, I am using Visual Studio 2008 to compile the source files, and the supplied projects convert with no issues at all.
I was just able to get past this and was successfully able to compile MagickNET against the latest version of ImageMagick. I had to do several things. Configured ImageMagick to use StaticMTDll. Edited magick-config.h to undefine X11 support. Removed the CORE_xlib project from the ImageMagick solution. Clean/Rebuild of ImageMagick Added the following lib files to the linker settings for MagickNet CORE_DB_bzlib_.lib CORE_DB_coders_.lib CORE_DB_jbig_.lib CORE_DB_jpeg_.lib CORE_DB_magick_.lib CORE_DB_png_.lib CORE_DB_tiff_.lib CORE_DB_ttf_.lib CORE_DB_wand_.lib CORE_DB_wmf_.lib CORE_DB_zlib_.lib CORE_DB_libxml_.lib CORE_DB_jp2_.lib CORE_DB_lcms_.lib Ws2_32.lib Built MagickNet I did have to make updates to MagickNet because methods have been deprecated since the source release on the MagickNet website. I'll try and put a repository online to share the entire solution.
727,066
727,240
Dynamically change allocation strategy in boost::vector and boost::matrix
In my new project i am building a data management module.I want to give a simple template storage type to upper layers like template<typename T> class Data { public: T getValue(); private: boost::numeric::ublas::matrix<T> data; } My aim is, to change allocator of data with some different allocators like Boost.inter process allocator or Boost.pool allocator (Boost Ublas Matrix and vector classes takes allocator as a template parameter ).And give only a single class and Factory method to create appropriate allocator under cover.A virtual base class could be sweet but i couldn't handle how to use it with templates.What kind of design patterns or solutions do you offer? Edit: I will use boost.pool and boost.shared_memory_allocator.Briefly i want to have different classes with different allocation strategies.But my point is upper parts of program should have no knowledge about it.Real challenge for me is to collect different template classes with an identical base classes. Edit: For one who want to use matrix class with custom allocator. it is like this: using boost::numeric::ublas; template<typename T, class Allocator = boost::pool_allocator<T>> class { public: matrix<T, row_major, std::vector<T,Allocator>> mData; }
It's not clear what you want, but as a shot in the dark, is the following helpful? template<typename T> class IData { public: virtual T getValue() = 0; virtual ~IData() {} }; template<typename T, typename Allocator=std::allocator<T> > class Data : public IData<T> { public: virtual T getValue(); private: boost::numeric::ublas::matrix<T, Allocator> data; }
727,336
728,294
How to Cross Compile for Cell Linux on the PS3 from Windows?
How can a cross compilation setup be achieved to allow compiling Cell Linux programs on a Windows PC using the cygwin toolchain? The cygwin tools provide a GNU compiler to use in building the cross compiler, and associated tools for the build process e.g. rpm, cpio, make, flex, bison and so on. I am moderately confident this is possible, but unaware of anyone who has actually done this. It has already been done for x86 Linux, but I wish to use Windows, without requiring the use and overhead of a virtual machine running an entire 2nd operating system. The Cell Linux toolchain is a patched GNU toolchain, with C and C++ compilers for the PPU and SPU processors, and associated binutils. The sources for the Cell Linux SDK for Cell Linux can be found here. The source RPMS here have build scripts for use with the rpmbuild tool on Linux. The specific question is: how can a set of Cell Linux GNU compilers for the PPU and SPU processors be built, on Windows, using Cygwin.
I've never done it, so I can't give you step by step instructions, but I can give you a general idea. The instructions you linked will serve as a pretty good outline, but there will be definite changes. For the host PC, you can install gcc and other build tools from MinGW or cygwin. That will give you the windows native parts of your toolchain. Then you'll need to download the sources for the cell portions of the toolchain and compile them (with the appropriate options, --target, etc.) using the build environment you just installed. Then you download and compile the sources for libspe2, and you're done. But I'll warn you - it sounds easier than it is. Be prepared to spend a lot of time on it.
727,439
727,448
How do you convert a Visual Studio project from using wide strings to ordinary strings
When I created my visual studio project it defaulted to forcing me to use wide strings for all the functions which take character strings. MessageBox() for example, takes a LPCWSTR rather than a const char*. While I understand that it's great for multi-lingual and portable applications, it is completely unnecessary for my simple little app. Quite frankly, it's more of a pain to constantly type TEXT() around all my strings. Is there a compiler option, define or project setting which I can alter to fix this in my Visual Studio project?
Right click on your project -> Properties then go to the following tree item: Configuration Properties -> General For Unicode select: Use Unicode Character Strings For normal multi-byte select: Use Multi-Byte Character Set When you put TEXT() or _T() around your strings, you are making it compatible with both of the character string options. If you select Use multi-byte character set then you do not need anything around your strings. If you select Use unicode character set, you need at least L in front of your strings. By selecting Use Unicode Character Strings you are also by default using all of the Win32 API that end in W. Example: MessageBox maps to MessageBoxW. When you select Use multi-byte character set you are also by default using all of the Win32 API that end in A. Example: MessageBox maps to MessageBoxA.
727,516
727,518
What does the unary plus operator do?
What does the unary plus operator do? There are several definitions that I have found (here and here) but I still have no idea what it would be used for. It seems like it doesn't do anything but there has be a reason for it, right?
It's there to be overloaded if you feel the need; for all predefined types it's essentially a no-op. The practical uses of a no-op unary arithmetic operator are pretty limited, and tend to relate to the consequences of using a value in an arithmetic expression, rather than the operator itself. For example, it can be used to force widening from smaller integral types to int, or ensure that an expression's result is treated as an rvalue and therefore not compatible with a non-const reference parameter. I submit, however, that these uses are better suited to code golf than readability. :-)
727,541
727,674
C++/Java Inheritance vs. Delegation vs. etc
I am creating a class library with many different options for possible customizations. For example, you can design your class so that it can perform FeatureX(), or you can design your class so that it can perform FeatureY(). Under normal circumstances, you would simply create an interface IFeatureX with a pure virtual method called FeatureX, and another interface IFeatureY with a pure virtual method called FeatureY. If a class has both FeatureX and FeatureY, it can inherit from both, no problem. My problem is, what if a function/method requires an object that can perform both FeatureX() and FeatureY()? How do I express a type, in C++ preferably, but an answer in Java could help as well, to ensure that both FeatureX and FeatureY are available? Do I create another interface IFeatureXY that inherits from IFeatureX and IFeatureY? Okay... if there are only two features I could get away with this. But if there are say... 10 features, the number of possible interfaces becomes massive. Is there a simple way to do this? I tried solving the problem using C++ templates and delegation but didn't get too far. I'm hoping there is a simple solution to this, and there probably is one that I just overlooked. I appreciate any help and advice you guys have. Thanks.
If you're not afraid of using templates, you can make your function a template and use SFINAE to check for the two interfaces: template <class T> void my_function(const T& data, typename enable_if_c< is_convertible<T*, IFeatureX*>::value && is_convertible<T*, IFeatureY*>::value>::type*=0) { ... } This will create a method for every type that extends both feature interfaces (note that the SFINAE trick is not needed for it to work; an unconstrained template would work, but just fail to compile when you pass a type that doesn't meet the requirements). Another possibility is to create an interface IFeatureXY extending both, and use this in the function parameters; this has the drawback that types that do implement both interfaces, but not this joint interface would not be usable with this method. Also, you can pass two arguments to the function, one per interface, and require they are pointers to the same object; this is fragile, but could be hardened by making some template class to hold the two pointers - eg. product_type<IFeatureX*, IFeatureY*>, which would be initialized by the single object in question and which would hold the two types. In Java, you could probably do the same thing with bounded type variables (if they allow multiple bounds; I'm not sure now).
727,737
727,907
Why is stringstreams rdbuf() and str() giving me different output?
I have this code, int main() { std::string st; std::stringstream ss; ss<<"hej hej med dig"<<std::endl; std::getline(ss,st,' '); std::cout <<"ss.rdbuf()->str() : " << ss.rdbuf()->str(); std::cout <<"ss.rdbuf() : " << ss.rdbuf(); return 0; } Giving me this output ss.rdbuf()->str() : hej hej med dig ss.rdbuf() : hej med dig But why is that? Is that because of ostreams definition of operator<str() gives me different output. In my eyes the output should be the same even if I have used getline.
ss.rdbuf()->str(); Returns copy of all buffer content. What doing std::cout << ss.rdbuf();? See description for basic_ostream<charT,traits>& operator<<(basic_streambuf<charT,traits>* sb); It read character by character from buffer and write them to ostream, until eof/fail on writing/exception occurs. You already have read one word from buff. Now it read rest part.
727,762
727,781
How should I change this declaration?
I have been given a header with the following declaration: //The index of 1 is used to make sure this is an array. MyObject objs[1]; However, I need to make this array dynamically sized one the program is started. I would think I should just declare it as MyObject *objs;, but I figure if the original programmer declared it this way, there is some reason for it. Is there anyway I can dynamically resize this? Or should I just change it to a pointer and then malloc() it? Could I use some the new keyword somehow to do this?
You're correct. If you want to dynamically instantiate its size you need to use a pointer. (Since you're using C++ why not use the new operator instead of malloc?) MyObject* objs = new MyObject[size];
727,918
727,935
What happens when GetTickCount() wraps?
If a thread is doing something like this: const DWORD interval = 20000; DWORD ticks = GetTickCount(); while(true) { DoTasksThatTakeVariableTime(); if( GetTickCount() - ticks > interval ) { DoIntervalTasks(); ticks = GetTickCount(); } } Eventually, ticks is going to wrap when the value doesn't fit in a DWORD. I've been discussing this with a colleague. One of us believes the code will still behave 'nicely' when the wrap occurs, because the subtraction operation will also wrap. The other of us, believes it won't always work, especially if the interval is large. Who's right, and why? Thanks.
From the docs: The elapsed time is stored as a DWORD value. Therefore, the time will wrap around to zero if the system is run continuously for 49.7 days. To avoid this problem, use GetTickCount64. Otherwise, check for an overflow condition when comparing times. However, DWORD is unsigned - so you should be okay. 0 - "very big number" = "small number" (assuming you don't have any overflow checking active, of course). I had a previous edit which suggested you'd get a negative number, but that was before I took into account that DWORD is unsigned. You'll still have a problem if the operation takes just under 49.7 days though. That may not be an issue for you ;) One way to test would be to stub out the GetTickCount() method so you could write unit tests where you explicitly make it wrap. Then again, if you're really only doubting the arithmetic part, you can easily write unit tests for that :) Really, the fact that the number is coming from a system clock is pretty much irrelevant so long as you know the behaviour when it wraps - and that's specified in the documentation.
728,068
728,070
How to calculate a time difference in C++
What's the best way to calculate a time difference in C++? I'm timing the execution speed of a program, so I'm interested in milliseconds. Better yet, seconds.milliseconds.. The accepted answer works, but needs to include ctime or time.h as noted in the comments.
See std::clock() function. const clock_t begin_time = clock(); // do something std::cout << float( clock () - begin_time ) / CLOCKS_PER_SEC; If you want calculate execution time for self ( not for user ), it is better to do this in clock ticks ( not seconds ). EDIT: responsible header files - <ctime> or <time.h>
728,126
728,134
What data source could I use for my stock market program?
I would like to make a free open-source C++ application for both Linux and Windows which will create live stock market charts (i.e. they're refreshed frequently). Please could you give me some pointers on these issues: What should I use as the data source? Are there free services I can implement? I would like to use the same or similar information as companies like Google. I'm not sure what GUI toolkit would be best to use, is there one which has charting built in, or would I need to use a specialized library for this? Some things to note: This is my first attempt at both cross-platform C++ development, and a GUI application for Linux. I'm based in the UK, so I'd like to use data sources that provide information for the London stock exchange (LON) as well as NASDAQ, etc.
As of Nov 2014, these links are dead. Google Finance API: http://code.google.com/apis/finance/ Yahoo! Finance API: http://developer.yahoo.com/finance/ Cross-platform C++ charts w/ Qt: http://www.int.com/products/2d/carnac/chart_component.htm
728,192
728,345
How to remove, reinstall and/or find info about Visual Studio 2008 hotfixes?
Another developer and I are experiencing different behavior in native C++ executables built with Microsoft Visual Studio 2008, Version 9.0.30729.1 SP on different machines. We are statically linking to the Standard Library so we don't think it's a DLL version issue. We have ruled out differences in our source code and build settings. We theorized that perhaps we had different "hotfixes" installed on our separate machines that either affect code generation or perhaps have differences in their C++ Standard Library implementations. We each used [Help | About Microsoft Visual Studio | Copy Info] to get version information and then diffed them. Sure enough, we found a few discrepancies. I have some hotfixes that my colleague does not. And he has a couple which are missing from my installation. Here's an example hotfix entry from the version info: Hotfix for Microsoft Visual Studio 2008 Professional Edition - ENU (KB953256) KB953256 This hotfix is for Microsoft Visual Studio 2008 Professional Edition - ENU. If you later install a more recent service pack, this hotfix will be uninstalled automatically. For more information, visit http://support.microsoft.com/kb/953256. As you'll notice, link provided is dead. In fact, of the four differences we found, all but one have dead links: http://support.microsoft.com/kb/948484 (dead link) http://support.microsoft.com/kb/952241 http://support.microsoft.com/kb/953256 (dead link) http://support.microsoft.com/kb/958357 (dead link) Does anyone out there know how to actually find more info about these kinds of mystery hotfixes? Any advice on these particular ones? Short of each fully reinstalling Visual Studio, does anyone have tips on how we might get our separate installations synchronized, perhaps through removing and/or reinstalling hotfixes?
The main culprit for causing different behavior in native C++ apps would probably be: KB958357 This seems to be an earlier version of what is now KB962219. Details are available in this posting on the Visual C++ Team Blog: http://blogs.msdn.com/vcblog/archive/2008/12/17/vc9-sp1-hotfix-for-the-vector-function-ft-crash.aspx This hotfix actually fixes 5 bugs: function::swap() was broken by the Small Functor Optimization in VC9 TR1 (the Feature Pack). This broke vector> in VC9 SP1. "Broken" meant "compiling but crashing". vector> nonconformantly required X to have a default constructor. (This is a specific example of a general bug: vector>, vector>>, etc. were also affected.) vector> nonconformantly required X and Y to have default constructors. (This is a specific example of a general bug, see above.) vector> nonconformantly required X to have a default constructor. Random distributions were broken, triggering infinite loops and emitting bogus results. Those look like sufficient changes to cause differing behavior, but it all depends on your code. See if installing the latest version of that hotfix on each machine resolves the discrepancies you're seeing.
728,233
728,272
Why are references not reseatable in C++
C++ references have two properties: They always point to the same object. They can not be 0. Pointers are the opposite: They can point to different objects. They can be 0. Why is there no "non-nullable, reseatable reference or pointer" in C++? I can't think of a good reason why references shouldn't be reseatable. Edit: The question comes up often because I usually use references when I want to make sure that an "association" (I'm avoiding the words "reference" or "pointer" here) is never invalid. I don't think I ever thought "great that this ref always refers to the same object". If references were reseatable, one could still get the current behavior like this: int i = 3; int& const j = i; This is already legal C++, but meaningless. I restate my question like this: "What was the rationale behind the 'a reference is the object' design? Why was it considered useful to have references always be the same object, instead of only when declared as const?" Cheers, Felix
The reason that C++ does not allow you to rebind references is given in Stroustrup's "Design and Evolution of C++" : It is not possible to change what a reference refers to after initialization. That is, once a C++ reference is initialized it cannot be made to refer to a different object later; it cannot be re-bound. I had in the past been bitten by Algol68 references where r1=r2 can either assign through r1 to the object referred to or assign a new reference value to r1 (re-binding r1) depending on the type of r2. I wanted to avoid such problems in C++.
728,325
728,330
Can you call a C# DLL from a C DLL?
I've built a DLL in C#. Now I want to use the R Environment to call functions in that DLL. The R environment supports calling unmanaged C/C++ DLL's but not into .NET DLL's. So my question is, can I call functions in a C# DLL from a C/C++ DLL? If so, do you have a link to info about how to do this?
The most straight forward way of doing this is to expose one of the C# classes in your C# DLL as a COM object, and then create an instance of it from your C/C++ DLL. If that isn't an acceptable option, you'd need to create a mixed-mode C++ DLL (which contains both managed and unmanaged code). Your C/C++ DLL can call exported functions in your mixed-mode DLL, which can in turn forward the calls on to your C# class.
728,380
728,556
Is there a way to get Asio working without Boost?
I know there is a version of ASIO that is not included in the Boost namespace, but even then ASIO depends on Boost, but I'm wondering if there is a way to get ASIO to work without dependencies on Boost (because I cannot include Boost into the project, for too many reasons).
No, i don't believe so. ASIO has been using boost for as long as i have heard of it. I think they're very much interconnected. But you may be interested in a tool, bcp, which lets you extract the minimal subset of boost required for the libraries that you want to use.
728,416
728,441
Is there any difference between +-ing strings and <<-ing strings in c++?
What is the difference, if any between the effects of the following snippets: cout << "Some text" << s1 << "some more text\n"; cout << "Some text" + s1 + "some more text\n";
The result of operator+ on strings is a new string. Therefore, in the example cout << "Some text" + s1 + "some more text\n"; two new strings are created (implies memory allocation) before the whole thing is written to cout. In your first example, everything is written directly to cout without unnecessary memory allocation.
728,602
728,682
Windows Mobile Development: Choice of .Net compact vs. Native (c++) code
I work on an experienced and diverse development team and we are preparing to approach our first mobile development which will be for Windows Mobile 6 (platform changes are not an option). We have skills and experience in both Visual C++ and .Net technologies for Windows desktop and server development. The mobile development will include some image processing, and read/write access to a bluetooth device. Unfortunately I can't really give any more details than that. We are trying to choose between writing the mobile client using managed code or native code. We would use C# or C++ respectively. My questions are: How big is the expected performance differential between these languages? I have heard that native code is significantly faster on mobile devices, but I would love to hear from someone with experience. Are there any major advantages to either language in terms of working with the Windows Mobile services for accessing bluetooth devices? Is there an impact on battery life between managed or native code? Are there any other major should-knows for us to consider? I appreciate your feedback.
A very similar question was asked and answered just a few days ago. You can find useful information there. Short answers to your questions: Native code is faster, but for many applications the speed difference won't be noticeable. Don't use native code just for the speed, unless this is a key factor for your application. Managed applications can also run fast - it may take them longer to launch. There is a good Bluetooth library for .NET applications. I am not aware of a similar library for C++ applications. It is up to your design to achieve good battery life. Choice of platform doesn't matter.
728,972
729,603
Finding all the subsets of a set
I need an algorithm to find all of the subsets of a set where the number of elements in a set is n. S={1,2,3,4...n} Edit: I am having trouble understanding the answers provided so far. I would like to have step-by-step explanation of how the answers work to find the subsets. For example, S={1,2,3,4,5} How do you know {1} and {1,2} are subsets? Could someone help me with a simple function in c++ to find subsets of {1,2,3,4,5}
It's very simple to do this recursively. The basic idea is that for each element, the set of subsets can be divided equally into those that contain that element and those that don't, and those two sets are otherwise equal. For n=1, the set of subsets is {{}, {1}} For n>1, find the set of subsets of 1,...,n-1 and make two copies of it. For one of them, add n to each subset. Then take the union of the two copies. Edit To make it crystal clear: The set of subsets of {1} is {{}, {1}} For {1, 2}, take {{}, {1}}, add 2 to each subset to get {{2}, {1, 2}} and take the union with {{}, {1}} to get {{}, {1}, {2}, {1, 2}} Repeat till you reach n
728,986
729,004
does assignment operator work with different types of objects?
class A { public: void operator=(const B &in); private: int a; }; class B { private: int c; } sorry. there happened an error. is assignment operator valid ? or is there any way to achieve this? [There is no relation between A and B class.] void A::operator=(const B& in) { a = in.c; } Thanks a lot.
Yes you can do so. #include <iostream> using namespace std; class B { public: B() : y(1) {} int getY() const { return y; } private: int y; }; class A { public: A() : x(0) {} void operator=(const B &in) { x = in.getY(); } void display() { cout << x << endl; } private: int x; }; int main() { A a; B b; a = b; a.display(); }
729,146
729,182
How to programmatically check Internet bandwidth in VC++?
I need to find the bandwidth available at a particular time. The code must be developed in Visual C++ or in .Net family . If anyone knows how, please help me out.
The only way to check your bandwidth is to actually try to use it, i.e. by downloading a file from somewhere else and measuring the throughput. Even then it'll only be an approximation, because other network effects will affect the results: latency asymmetric upload / download other traffic
729,363
729,373
Is it possible to access private members of a class?
Is it possible to access private members of a class in c++. provided you don't have a friend function and You don't have access to the class definition
You mean using some pointer arithmetic to gain the access ? It is possible but is definitely dangerous. Take a look at this question also: Accessing private members
729,562
729,579
How to compile C# application with C++ static library?
I turned my C++ Dynamic link library into Static library just to acquire more knowledge. My question is how can I use the .obj file to compile both projects with C# express/MS visual studio?
No, you can't access static libraries directly from C#. You have to use a DLL.
729,652
729,690
Writing a MySQL UDF using C++ STL functionality
There is a statement in the MySQL Docs (http://dev.mysql.com/doc/refman/5.0/en/adding-udf.html) that is bothering me: "A UDF contains code that becomes part of the running server, so when you write a UDF, you are bound by any and all constraints that otherwise apply to writing server code. For example, you may have problems if you attempt to use functions from the libstdc++ library." Why there may be problems if you use C++ standard library functions to write a UDF ?? Does that mean that I'm condemned to use plain old C to write my UDFs ?? (please say no)
Not having any knowledge at all of libstdc++, but going by the "For example" bit meaning that this warning is applicable to more than libstdc++ I would suggest that this means be wary of standard libraries in general as they may peform things that wouldn't work in a UDF environment. For example (digging back to C) strtok maintains a local state between calls meaning you have to serialize its use or face corruption of its results if you tried to use it to work on two different strings at the same time. Thus strtok would not work in an environment like a UDF where you have no control as to where and when the function is called. Thus I would say that anything that would not work in a multithreaded environment should be avoided. But note that the above is based purely on my speculation, and is not based in reality.
729,683
730,266
sizeof(*this) gives wrong value
I have a class, C. C has a member variable declared as: bool markerStart; From within C a call to sizeof(*this) gives a value of 0x216 bytes. Elsewhere within C, I do: markerStart = false; Rather than setting markerStart to false, this call is actually clobbering the start of the next class in memory! Looking at the disassembled code, I find: markerStart = false; 06FB6B7F mov eax, dword ptr [this] 06FB6B78 mov byte ptr [eax+218h], 0 The second move instruction is setting a byte at this + 0x218 to zero, but since the class is only 0x216 bytes long, this is clobbering memory! In response to a comment, it definitely is the markerStart = false instruction. I can watch it happening in the disassembler view and in the memory view (and using Windbg, by using a data breakpoint). The first byte of the next class gets set to zero, which messes up its vftbl pointer. Note: taking the address of markerStart and subtracting it from this, yields 0x211! Can anyone give me a clue on where to start looking to resolve this problem? Update: Thanks for all the help. Without code, it was next to impossible for any of you to solve the problem. What I was looking for were hints as to where to start looking. Most of you provided excellent hints, so thank you! I finally found the problem. In this case alignment had been set in one class, and not been correctly reset following the critical block of code. The class with the faulty alignment happened to get compiled immediately before the declaration of class C - hence that's where the problem showed up.
As pointed out by Pontus, you probably broken the one definition rule somehow. You've probably included the header file with the definition of class C in two translation units where other code, often in a preceding header file, changes the way the definition of class C is interpreted so that it has a different size in the two translation units. One possibility, is that you've accidently changed the default member alignment (either through a command line argument to the compiler or via a #pragma in the source) so that two different translation units think the structure has a different size because of differing amounts of padding (most x86 compilers default to alignment on 4-byte boundaries, but allow you to request alignment on 1-byte boundaries as needed). Look in the other header files for a #pragma changing the default alignment that is missing a following #prama to restore it back to the previous value (you don't specify what compiler, so I can't give specifics).
729,721
729,757
Waiting for pthread_create to finish without using pthread_join
I want to halt one thread till another thread has finished initializing without using pthread_join. I tried using a join but it leads to a deadlock due to some asynchronous inter-thread communication system that we have. Right now, I'm using a (custom) lock to achieve this. In Thread 1: lock_OfflineWorker.Lock() if (pthread_create(&tid0, NULL, RunOfflineWorker, NULL) != 0) { } lock_OfflineWorker.TryLock(); lock_OfflineWorker.Unlock(); In Thread 2: bool OfflineWorker::Initialize() { lock_OfflineWorker.Unlock(); } But this is inelegant and I'm not too sure about the side effects (possibility for another deadlock). Is this Ok? If not, is there another way to achieve this (using locks or otherwise) EDIT: Forgot include the "RunOfflineWorker" function void* RunOfflineWorker(void* pData) { g_OfflineWorker.Initialize(); }
You can use a pthread condition to wait until the job reaches the wanted state. The thread1 waits with pthread_cond_wait() and the thread2 signals it with pthread_cond_signal(). You need : bool condition ; // or anything else to be tested pthread_mutex_t mutex ; pthread_cond_t cond ; The first thread inits all : condition = false ; pthread_mutex_init( &mutex , PTHREAD_MUTEX_INITIALIZER ); pthread_cond_init( &cond , PTHREAD_COND_INITIALIZER ); Then it waits with the mutex locked. Usually you put the wait in a loop to check the condition whatever it is. pthread_mutex_lock( &mutex ); while( ! condition ) { pthread_cond_wait( &cond , &mutex ); } pthread_mutex_unlock( &mutex ); The other thread does this when appropriate : pthread_mutex_lock( &mutex ); condition = true ; // or false ... pthread_cond_signal( &cond ); pthread_mutex_unlock( &mutex );
729,792
750,745
bandwidth throttling with Qt
I'm using the QNetworkAccessManager to download files from the web, it provides an easy API to the task. But I wish to add a download rate limit to the class, so all http replies won't exceed that limit (I see no reason to limit the requests). I've googled abit and found an interesting post here. But what it does is subclass QTcpSocket and gives control over the bandwidth using a separate class that manages a set of sockets. While this is nice I want to continue using the QNetworkAcessManager class. The way I see it I could: subclass QNetworkAccessManager and integrate the subclassed QTcpSocket somehow (this might involve subclassing even more classes, the QHttp* ones). use the classes offered in the article and build my own QNetworkAccessManager around those. the QNetworkAccessManager allows the use of a proxy. I could write a fake proxy class that will have the bandwidth throttling logic in it. But this seems like an ugly hack to me. While the first 2 options are possible, I was wondering if there's an easier way to do this? If not which one would you suggest?
I ended up using the RcTcpSocket and RateController from this article with the QHttp class. Prior to making get/post requests with the QHttp I create a RcTcpSocket, add it to my RateController and use QHttp::setSocket(QTcpSocket*). I still didn't find a solution to keep using QNetworkAccessManager but this is close enough and works very good.
730,125
730,203
Using pthread condition waits in a structure
I previously inquired about synchronizing two threads without using pthread_join and I was able to resolve it using pthread_cond_wait and pthread_cond_signal. I've written a small struct to bundle this functionality into a single place: struct ConditionWait { int i_ConditionPredicate; pthread_mutex_t lock_Var; pthread_cond_t cond_Var; int i_ValidResult; ConditionWait() { pthread_mutex_init(&lock_Var, NULL); pthread_cond_init(&cond_Var, NULL); i_ValidResult = 1; i_ConditionPredicate = 0; } void Signal() { pthread_mutex_lock(&lock_Var); i_ConditionPredicate = i_ValidResult; pthread_cond_signal(&cond_Var); pthread_mutex_unlock(&lock_Var); } void Wait() { pthread_mutex_lock(&lock_Var); while(i_ConditionPredicate != i_ValidResult) { pthread_cond_wait(&cond_Var, &lock_Var); } pthread_mutex_unlock(&lock_Var); } }; Assuming that I call Wait() and Signal() from two different threads, would this be thread safe. Would taking the same lock in two functions of the same object cause deadlocks or race conditions? Edit: I'm using this now in my program and it works fine. I'm not too sure whether it's just luck
This will only work once, after you wake up the thread waiting, the next attempts to wait will all succeed and never block since you never "reset" the condition predicate. If this is what you want (or it doesn't matter in your situation) then yes, this is safe and is how condition variables are typically used. PS: You should also use pthread_mutex_destroy() and pthread_cond_destroy() in the destructor of this thing.
730,134
741,541
How to Enforce C++ compiler to use specific CRT version?
I am using VS2008 for developing a COM dll which by default uses CRT version 9 but I am using TSF (Text service framework) that is not compatible with the new CRT. I think the solution is to use the compatible one so how can I specify the CRT version?
I whole heartily join the recommendation not to manually change the CRT version you link against. If however, for some reason (which I cannot imagine) this is the right course of action for you, the way to do so is change the manifest for your project. First make sure a manifest is not generated on every build (on VS2005: Configuration properties/Linker/Manifest file/Generate manifest), as it would overwrite your manual changes. Also make sure there that isolation is enabled. Next, locate the manifest file - should be at the $(IntDir) (e.g., Debug). You should see a section similar to - <dependency> <dependentAssembly> <assemblyIdentity type='win32' name='Microsoft.VC80.DebugCRT' version='8.0.50727.762' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' /> </dependentAssembly> </dependency> (For debug builds, of course). You need to edit the version and publicKeyToken attributes of the CRT element. You can inspect the files at your local WINDOWS\WinSxS folder to see the versions available. Check here how to extract the publicKeyToken once you find the version you want. (Although I'd first try and look directly into manifests of other projects, linking against your desired CRT version). If you do go there, expect some rough water. You may have some luck if your application is a console app that does not link against other Side-by-Side components (MFC, OpenMP, etc.). If your application is non-trivial, I'd be surprised if there aren't some intricate version dependencies amont the SxS components. (edit) You'd also need to distribute with your application the specific CRT you're using. Here's someone who did that.
730,253
730,277
Issue with C++ Intellisense and Error Checking
Using Visual C++ 2008. First time, I'm experimenting in crossing over from C# and wanted to try my hand at it. I have not changed base settings much, other than a few things like smart block and maybe a few colors. Because I'm at level ZERO on c++ knowledge all the Googling I've done is over my head. Part 1 of the problem My issue is that I just created my first windows form project. now that I double click and go into something like this, intellisense doesn't list any members? private: System::Void executeDocumentationCmd_Click(System::Object^ sender, System::EventArgs^ e) { this. NOTHING POPS UP? } If I type in MessageBox::, then it will popup intellisense for Show. Is this normal? I find it helpful as I'm learning basics to have it list available txt boxes and members, but it won't do that like it does in C# intellisense. I have stdafx.h included. I deleted the ncb file per online help and restarted, nothing. Additional headers? Part 2 of the problem: No underlined errors in realtime coding as in C# editing. Is this a feature that C++ express has (error checking before the compile)? I'm not seeing any warnings or errors listed as I type in wrong information.
this in C++ is a pointer that is dereferenced by -> not . Also, intellisense for C++ in VS2008 is not as helpful as in C#, this includes not having error checking. VS2010 will be introducing inline error checking for C++. There are some very big differences between C# and C++ that you will need to be aware of. It's a big topic so I don't think a post here can summarise them but two important points are the lack of garbage collection (lookup the delete keyword) and pointers. Pointers exist in C# but they are only available in unsafe code blocks whereas in C++, pointers are almost king. You may want to invest in a book to help you with your learning.
730,400
730,413
gprof and arguments to executable
when using gprof: $ gprof options [executable-file [profile-data-files...]] [> outfile] if you have options to pass to the executable like: gprof a.out --varfred=32 then gprof assumes that I am passing an invalid option to it, instead of to the program being profiled (a.out). Any way to get around this?
You don't run your executable with gprof, so you only specify it so gprof can load symbols. You run the executable first, on its own just as normal, and it then emits profiling data. This data is loaded, along with the executable, by gprof later. This is all explained in the gprof manual, of course.
730,498
730,536
Iterator access performance for STL map vs. vector?
What is the performance difference between using an iterator to loop through an STL map, versus a vector? I'd like to use the map key for insertion, deletion, and some accesses, but I also need to do regular accesses to every element in the map.
With both map and vector, iterating through the entire collection is O(N). however (like list vs vector) vector stores elements contiguously, so accessing the next element is much cheaper because it will use cache optimally, whereas the map won't. But since you need to have lookup based on keys, there isn't really an alternative. You could use a vector of pairs sorted on the first element, but if the collection needs to be mutable this is going to be very slow. Just use a map.
730,603
730,659
Help with OSSpinLock* usage to replace a while(true) {sleep(1);}
I am maintaining a carbon C++ application on OS X. There is a "spin lock" in one of the objects in the code that looks like this, while ( mState != RELEASED ) { sleep( 1 ); } There is a post render maintenance callback that is fed to AudioUnitAddRenderNotify() that would set the mState of these various objects. I was thinking about using the built-in OSSpinLock family of functions to replace this (if nothing else because they are thread safe and the above code doesn't seem to be). Would this be a reasonable equivalent? Should I also add some lock protection in the maintenance thread which manipulates the mState of these objects? OSSpinLock spin_lock = OS_SPINLOCK_INIT; if (!OSSpinLockTry(&spin_lock)) OSSpinLockLock(&spin_lock); while (mState != RELEASED) OSSpinLockTry(&spin_lock); OSSpinLockUnlock(&spin_lock);
Don't use a spinlock -- spinlocks waste CPU cycles, looping endlessly until they get the lock. Spinlocks should only be used when the time that the lock will be held will be very short. A better alternative would be to use a condition variable, such as the ones available in the pthreads library. This way, your thread will sleep and not waste any CPU cycles until the condition is satisfied. See the example listed in that link for how to use pthreads condition variables.
730,700
730,731
How do you "decode" Visual Studio Link Errors?
I'm not very experienced in C++, and when I have to work with another library and I get link errors, I'm completely in the dark on what the compiler is trying to tell me (other than it can't find something reference somewhere). Are there any good links that describe, in detail, the meaning of the symbols and characters in a link error message? Or how to trouble shoot such errors? For example, this is a link error I received recently: testproj error LNK2019: unresolved external symbol "public: __thiscall google::protobuf::internal::GeneratedMessageReflection::GeneratedMessageReflection(class google::protobuf::Descriptor const *,class google::protobuf::Message const *,int const * const,int,int,int,class google::protobuf::DescriptorPool const *,int)" (??0GeneratedMessageReflection@internal@protobuf@google@@QAE@PBVDescriptor@23@PBVMessage@23@QBHHHHPBVDescriptorPool@23@H@Z) referenced in function "void __cdecl testproj::protobuf_BuildDesc_def_2eproto_AssignGlobalDescriptors(class google::protobuf::FileDescriptor const *)" (?protobuf_BuildDesc_def_2eproto_AssignGlobalDescriptors@testproj@@YAXPBVFileDescriptor@protobuf@google@@@Z)
The symbols are the "mangled" versions of the function names. Basically because of c++ overloading (2 functions with different signatures can have the same name). The signature information is encoded into the name. The message you pasted has both the encoded and plain text versions. public: __thiscall google::protobuf::internal::GeneratedMessageReflection::GeneratedMessageReflection(class google::protobuf::Descriptor const *,class google::protobuf::Message const *,int const * const,int,int,int,class google::protobuf::DescriptorPool const *,int) ?0GeneratedMessageReflection@internal@protobuf@google@@QAE@PBVDescriptor@23@PBVMessage@23@QBHHHHPBVDescriptorPool@23@H@Z) are the same thing, just the later is mangled. Notice that the mangled version starts with: ?0GeneratedMessageReflection@internal@protobuf@google which corresponds nicely with: google::protobuf::internal::GeneratedMessageReflection Because the first few lines give you the relevant information, you can pretty much ignore the mangled versions. The plain text versions of the signatures are sufficient to fix the linker error.
730,773
731,904
c++ profiling/optimization: How to get better profiling granularity in an optimized function
I am using google's perftools (http://google-perftools.googlecode.com/svn/trunk/doc/cpuprofile.html) for CPU profiling---it's a wonderful tool that has helped me perform a great deal of CPU-time improvements on my application. Unfortunately, I have gotten to the point that the code is still a bit slow, and when compiled using g++'s -O3 optimization level, all I know is that a specific function is slow, but not which aspects of it are slow. If I remove the -O3 flag, then the unoptimized portions of the program overtake this function, and I don't get a lot of clarity into the actual parts of the function that are slow. If I leave the -O3 flag in, then the slow parts of the function are inlined, and I can't determine which parts of the function are slow. Any suggestions? Thanks for your help!
If you're on linux, use oprofile. If you're on Windows, use AMD's CodeAnalyst. Both will give sample-based profiles down to the level of individual source lines or assembly instructions and you should have no problem identifying "hot spots" within functions.
730,913
740,626
Dedicated function for memory allocation causes memory leak?
Hy all, I believe that the following piece of code is generating memory leak? /* External function to dynamically allocate a vector */ template <class T> T *dvector(int n){ T *v; v = (T *)malloc(n*sizeof(T)); return v; } /* Function that calls DVECTOR and, after computation, frees it */ void DiscontinuousGalerkin_Domain::computeFaceInviscidFluxes(){ int e,f,n,p; double *Left_Conserved; Left_Conserved = dvector<double>(NumberOfProperties); //do stuff with Left_Conserved // free(Left_Conserved); return; } I thought that, by passing the pointer to DVECTOR, it would allocate it and return the correct address, so that free(Left_Conserved) would successfully deallocate. However, it does not seem to be the case. NOTE: I have also tested with new/delete replacing malloc/free without success either. I have a similar piece of code for allocating a 2-D array. I decided to manage vectors/arrays like that because I am using them a lot, and I also would like to understand a bit deeper memory management with C++. So, I would pretty much like to keep an external function to allocate vectors and arrays for me. What's the catch here to avoid the memory leak? EDIT I have been using the DVECTOR function to allocate user-defined types as well, so that is potentially a problem, I guess, since I don't have constructors being called. Even though in the piece of code before I free the Left_Conserved vector, I also would like to otherwise allocate a vector and left it "open" to be assessed through its pointer by other functions. If using BOOST, it will automatically clean the allocation upon the end of the function, so, I won't get a "public" array with BOOST, right? I suppose that's easily fixed with NEW, but what would be the better way for a matrix? It has just occurred me that I pass the pointer as an argument to other functions. Now, BOOST seems not to be enjoying it that much and compilation exits with errors. So, I stand still with the need for a pointer to a vector or a matrix, that accepts user-defined types, that will be passed as an argument to other functions. The vector (or matrix) would most likely be allocated in an external function, and freed in another suitable function. (I just wouldn't like to be copying the loop and new stuff for allocating the matrix everywhere in the code!) Here is what I'd like to do: template <class T> T **dmatrix(int m, int n){ T **A; A = (T **)malloc(m*sizeof(T *)); A[0] = (T *)malloc(m*n*sizeof(T)); for(int i=1;i<m;i++){ A[i] = A[i-1]+n; } return A; } void Element::setElement(int Ptot, int Qtot){ double **MassMatrix; MassMatrix = dmatrix<myT>(Ptot,Qtot); FillInTheMatrix(MassMatrix); return; }
So, some important concepts discussed here helped me to solve the memory leaking out in my code. There were two main bugs: The allocation with malloc of my user-defined types was buggy. However, when I changed it to new, leaking got even worse, and that's because one my user-defined types had a constructor calling an external function with no parameters and no correct memory management. Since I called that function after the constructor, there was no bug in the processing itself, but only on memory allocation. So new and a correct constructor solved one of the main memory leaks. The other leaking was related to a buggy memory-deallocation command, which I was able to isolate with Valgrind (and a bit a patience to get its output correctly). So, here's the bug (and, please, don't call me a moron!): if (something){ //do stuff return; //and here it is!!! =P } free(); return; And that's where an RAII, as I understood, would avoid misprogramming just like that. I haven't actually changed it to a std::vector or a boost::scoped_array coding yet because it is still not clear to me if a can pass them as parameter to other functions. So, I still must be careful with delete[]. Anyway, memory leaking is gone (by now...) =D
731,032
731,048
Incorporating text files in applications?
Is there anyway I can incorporate a pretty large text file (about 700KBs) into the program itself, so I don't have to ship the text files together in the application directory ? This is the first time I'm trying to do something like this, and I have no idea where to start from. Help is greatly appreciated (:
Depending on the platform that you are on, you will more than likely be able to embed the file in a resource container of some kind. If you are programming on the Windows platform, then you might want to look into resource files. You can find a basic intro here: http://msdn.microsoft.com/en-us/library/y3sk7e6b.aspx With more detailed information here: http://msdn.microsoft.com/en-us/library/zabda143.aspx
731,141
731,239
When is it necessary to implement locking when using pthreads in C++?
After posting my solution to my own problem regarding memory issues, nusi suggested that my solution lacks locking. The following pseudo code vaguely represents my solution in a very simple way. std::map<int, MyType1> myMap; void firstFunctionRunFromThread1() { MyType1 mt1; mt1.Test = "Test 1"; myMap[0] = mt1; } void onlyFunctionRunFromThread2() { MyType1 &mt1 = myMap[0]; std::cout << mt1.Test << endl; // Prints "Test 1" mt1.Test = "Test 2"; } void secondFunctionFromThread1() { MyType1 mt1 = myMap[0]; std::cout << mt1.Test << endl; // Prints "Test 2" } I'm not sure at all how to go about implementing locking, and I'm not even sure why I should do it (note the actual solution is much more complex). Could someone please explain how and why I should implement locking in this scenario?
In general, threads might be running on different CPUs/cores, with different memory caches. They might be running on the same core, with one interrupting ("pre-empting" the other). This has two consequences: 1) You have no way of knowing whether one thread will be interrupted by another in the middle of doing something. So in your example, there's no way to be sure that thread1 won't try to read the string value before thread2 has written it, or even that when thread1 reads it, it is in a "consistent state". If it is not in a consistent state, then using it might do anything. 2) When you write to memory in one thread, there is no telling if or when code running in another thread will see that change. The change might sit in the cache of the writer thread and not get flushed to main memory. It might get flushed to main memory but not make it into the cache of the reader thread. Part of the change might make it through, and part of it not. In general, without locks (or other synchronization mechanisms such as semaphores) you have no way of saying whether something that happens in thread A will occur "before" or "after" something that happens in thread B. You also have no way of saying whether or when changes made in thread A will be "visible" in thread B. Correct use of locking ensures that all changes are flushed through the caches, so that code sees memory in the state you think it should see. It also allows you to control whether particular bits of code can run simultaneously and/or interrupt each other. In this case, looking at your code above, the minimum locking you need is to have a synchronisation primitive which is released/posted by the second thread (the writer) after it has written the string, and acquired/waited on by the first thread (the reader) before using that string. This would then guarantee that the first thread sees any changes made by the second thread. That's assuming the second thread isn't started until after firstFunctionRunFromThread1 has been called. If that might not be the case, then you need the same deal with thread1 writing and thread2 reading. The simplest way to actually do this is to have a mutex which "protects" your data. You decide what data you're protecting, and any code which reads or writes the data must be holding the mutex while it does so. So first you lock, then read and/or write the data, then unlock. This ensures consistent state, but on its own it does not ensure that thread2 will get a chance to do anything at all in between thread1's two different functions. Any kind of message-passing mechanism will also include the necessary memory barriers, so if you send a message from the writer thread to the reader thread, meaning "I've finished writing, you can read now", then that will be true. There can be more efficient ways of doing certain things, if those prove too slow.
731,208
731,370
What's the best use you've had with pointer to members and member functions?
Pointer to members are not used very much but they are really powerful, how have you used them and what's the coolest things you've done? Edit: This is not so much to list things that are possible, for example listing boost::bind and boost::function aren't good. Instead maybe a cool usage with them? I know they're very cool in themselves but that's not what this is about.
I once was needed to operate with criteria data as pure structure to be able to store the list of all criteria in the queue. And I had to bind the structure with the GUI and other filter elements, etc. So I came up with the solution where pointers to members are used as well as pointers to member functions. Let's say you have an struct Criteria { typedef std::string Criteria::* DataRefType; std::string firstname; std::string lastname; std::string website; }; Than you can wrap criteria field and bind with the string representation of the field with class Field { public: Field( const std::string& name, Criteria::DataRefType ref ): name_( name ), ref_( ref ) {} std::string getData( const Criteria& criteria ) { return criteria.*ref_; } std::string name_; private: Criteria::DataRefType ref_; }; Then you can register all the fields to use whenever you want: GUI, serialization, comparison by field names, etc. class Fields { public: Fields() { fields_.push_back( Field( "First Name", &Criteria::firstname ) ); fields_.push_back( Field( "Last Name", &Criteria::lastname ) ); fields_.push_back( Field( "Website", &Criteria::website ) ); } template < typename TFunction > void forEach( TFunction function ) { std::for_each( fields_.begin(), fields_.end(), function ); } private: std::vector< Field > fields_; }; By calling for instance fields.forEach( serialization ); or GuiWindow( Criteria& criteria ): criteria_( criteria ) { fields_.forEach( std::bind1st( std::mem_fun( &GuiWindow::bindWithGui ), this ) ); } void bindWithGui( Field field ) { std::cout << "name " << field.name_ << " value " << field.getData( criteria_ ) << std::endl; };
731,403
731,429
Why am I getting an error when using vfork()?
This is my code... I don't know why I'm get an error segment... could somebody explain the reason to me? #include <iostream> #include <string> // Required by for routine #include <sys/types.h> #include <unistd.h> using namespace std; int globalVariable = 2; main() { string sIdentifier; int iStackVariable = 20; pid_t pID = vfork(); if (pID == 0) // child { // Code only executed by child process sIdentifier = "Child Process: "; globalVariable++; iStackVariable++; cout << "PROCESO NUMERO"<<getpid()<<sIdentifier; // printf("Proceso hijo: PID %d - PPID %d\n", getpid(), getppid()); cout << " Global variable: " << globalVariable; cout << " Stack variable: " << iStackVariable << endl; return (0); } else if (pID < 0) // failed to fork { cerr << "Failed to fork" << endl; return (1); // Throw exception } else // parent { // Code only executed by parent process sIdentifier = "Parent Process:"; } // executed only by parent cout << sIdentifier; cout << " Global variable: " << globalVariable; cout << " Stack variable: " << iStackVariable << endl; return (0); }
Is this of use ? Note the caveats surrounding modification of variables. The vfork() function has the same effect as fork(), except that the behaviour is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or returns from the function in which vfork() was called, or calls any other function before successfully calling _exit() or one of the exec family of functions.
731,574
732,568
Saving a IXMLDOMDocument without end tag
Using MSXML via C++, when I call IXMLDOMDocument::save, empty XML elements will get an end tag, like this: <root> <child name="first"> </child> </root> But I want it saved as this: <root> <child name="first" /> </root> What do I need to do to accomplish that?
DOM itself does that if there are no child nodes but I don't know why in your case it is doing like this. If you want to do explicitly call Pretty Print on the DOM pointer. #include <msxml2.h> bool FormatDOMDocument (IXMLDOMDocument *pDoc, IStream *pStream) { // Create the writer CComPtr <IMXWriter> pMXWriter; if (FAILED (pMXWriter.CoCreateInstance(__uuidof (MXXMLWriter), NULL, CLSCTX_ALL))) { return false; } CComPtr <ISAXContentHandler> pISAXContentHandler; if (FAILED (pMXWriter.QueryInterface(&pISAXContentHandler))) { return false; } CComPtr <ISAXErrorHandler> pISAXErrorHandler; if (FAILED (pMXWriter.QueryInterface (&pISAXErrorHandler))) { return false; } CComPtr <ISAXDTDHandler> pISAXDTDHandler; if (FAILED (pMXWriter.QueryInterface (&pISAXDTDHandler))) { return false; } if (FAILED (pMXWriter ->put_omitXMLDeclaration (VARIANT_FALSE)) || FAILED (pMXWriter ->put_standalone (VARIANT_TRUE)) || FAILED (pMXWriter ->put_indent (VARIANT_TRUE)) || FAILED (pMXWriter ->put_encoding (L"UTF-8"))) { return false; } CComPtr <ISAXXMLReader> pSAXReader; if (FAILED (pSAXReader.CoCreateInstance (__uuidof (SAXXMLReader), NULL, CLSCTX_ALL))) { return false; } if (FAILED (pSAXReader ->putContentHandler (pISAXContentHandler)) || FAILED (pSAXReader ->putDTDHandler (pISAXDTDHandler)) || FAILED (pSAXReader ->putErrorHandler (pISAXErrorHandler)) || FAILED (pSAXReader ->putProperty ( L"http://xml.org/sax/properties/lexical-handler", CComVariant (pMXWriter))) || FAILED (pSAXReader ->putProperty ( L"http://xml.org/sax/properties/declaration-handler", CComVariant (pMXWriter)))) { return false; } // Perform the write return SUCCEEDED (pMXWriter ->put_output (CComVariant (pStream))) && SUCCEEDED (pSAXReader ->parse (CComVariant (pDoc))); }
731,908
731,924
Why does this compile (used in function before initialized)?
Consider this code (using CString because it's familiar and easy to see when not constructed, but nothing special about the class), tested under Visual Studio 2008: CString DoSomething( const CString& sString ) { return sString; } CString sTest1 = DoSomething( sTest1 ); // Compiles (no warnings), fails at runtime CString sTest2( DoSomething( sTest2 ) ); // Doesn't compile CString sTest3; sTest3 = DoSomething( sTest3 ); // Compiles, self-assignment, works As I understand the C++ standard, Test1 can be compiled into Test2 automatically as a compile-time optimization, provided the appropriate constructor is available (which, by default, will be generated to be identical to the first test). Notably, however, the behavior is not the same as Test3, which will work correctly. Now I understand why Test1 does not work, and why Test2 does not compile. What I am curious about is why Test1 compiles in the first place? Is this permitted in the standard, open for interpretation, a flaw in VS2008's compiler, a deficiency in init-before-use static checking, or what? Is there any way to force the compiler to at least give a warning in this case (Test1 appears to compile clean with max warning level under VS2008)? What would be the justification for the C++ specification permitting this construct? Edit: Alternatively, is there any way to force the compiler to compile Test1 as Test2 (and thus trigger the error)? Edit to add verbatim error message for Test2: error C2065: 'sTest2' : undeclared identifier
The behavior you are seeing in sTest1 is undefined in the C++ standard. It's weird and wrong but it compiles on a few compilers. See litb's answer on the following thread for more details: method running on an object BEFORE the object has been initialised?
731,959
731,999
Emacs indentation of the for each statement in C++
I'm trying to get emacs to correctly format the "for each" construct in c++. I want the braces to be lined up with the f in for in both of the following examples: for each(Type a in b) { //^c^s shows substatement-open //... do stuff } for( ; ; ) { //^c^s shows substatement-open //... do stuff } In both cases, using [Ctrl-c Ctrl-s] (or [Ctrl-c Ctrl-o]) shows that both opening { characters are of type substatement-open and when viewing the c-offsets-alist I see that substatement-open is equal to 0. How can I make emacs indent the for each() command similar to how it indents the for(;;) command?
Presumably emacs is not recognising "for each" as c++ syntax (I don't either. Is this a microsoft extension? A preprocessor hack? New for the upcoming standard?). So there is no wonder that it is not formatting it "right". You could hack the mode, or ask the maintainer of the same (I wouldn't expect a possitive response, though, unless this is going to be proper c++ Very Soon Now). From the comments The answers to my parenthetical questions are: The precise form the OP asks about is a Microsoft managed-c++ extension. There is BOOST_FOREACH available now The C++0x stand will include a container-ranged loop with a syntax like for( <type> <loopcounter> : <container> ) and from slink's answer it appears that the mode maintainer is supporting the Microsoft syntax in the latest versions...
732,160
732,175
How can I iterate in reverse over a map in C++?
I'm having trouble iterating in reverse over a map in GCC C++. When I use a reverse iterator, it seems I can't assign anything to it - the compiler complains. I'm working around it with some awkward code using a forward iterator, but it's not very elegant. Any thoughts?
Here's an example of iterating backward through a std::map: #include <iostream> #include <map> #include <string> int main() { std::map<std::string, std::string> m; m["a"] = "1"; m["b"] = "2"; m["c"] = "3"; for (auto iter = m.rbegin(); iter != m.rend(); ++iter) { std::cout << iter->first << ": " << iter->second << std::endl; } } If you are pre-C++11, you'll just need to spell out auto, which is: std::map<std::string, std::string>::reverse_iterator Note that if you're using boost, you can use a range-based for loop with a reverse adapter: #include <boost/range/adaptor/reversed.hpp> for (auto& iter : boost::adaptors::reverse(m)) { std::cout << iter.first << ": " << iter.second << std::endl; }
732,602
732,632
Why is the following program 15% slower when compiled with g++?
Updated: The actual resolution that the compile box which served my compile request was different. In the slower instance I was running code compiled on a SuSE 9 but running on a SuSE 10 box. That was sufficient difference for me to drop it and compare apples to apples. When using the same compile box the results were as follows: g++ was about two percent slower delta real 4 minutes delta user 4 mintues delta system 5 seconds Thanks! gcc v4.3 vs g++ v4.3 reduced to simplest case used nothing but simple flags #include <stdio.h> #include <stdlib.h> int main (int argc, char **argv) { int i=0; int j=0; int k=0; int m=0; int n=0; for (i=0;i<1000;i++) for (j=0;j<6000;j++) for (k=0;k<12000;k++) { m = i+j+k; n=(m+1+1); } return 0; } Is this a known issue? The 15% is very repro. and is across the board for real, system, and user time. I have to wait to post the assembly until tomorrow. Update: I have only tried on one of my compile boxes. I am using SuSE 10.
When compiled with gcc and g++ the only difference I see is within the first 4 lines. gcc: .file "loops.c" .def ___main; .scl 2; .type 32; .endef .text .globl _main g++: .file "loops.c" .def ___main; .scl 2; .type 32; .endef .text .align 2 .globl _main as you can see the only difference is that with g++, the alignment (2) occurs on a word boundary. This tiny difference seems to be making the significant performance difference. Here is a page explaining structure alignment, although it is for ARM/NetWinder it is still applicable as it discusses how alignment works on modern CPUs. You will want to read section 7 specifically "What are the disadvantages of word alignment?" : http://netwinder.osuosl.org/users/b/brianbr/public_html/alignment.html and here is a reference on the .align operation: http://www.nersc.gov/vendor_docs/ibm/asm/align.htm Benchmarks as requested: gcc: john@awesome:~$ time ./loopsC real 0m21.212s user 0m20.957s sys 0m0.004s g++: john@awesome:~$ time ./loopsGPP real 0m22.111s user 0m21.817s sys 0m0.000s I reduced the inner-most iteration to 1200. Results aren't as widespread as I had hoped, but then again the assembly output was generated on windows, and the timings done in Linux. Maybe something different is done behind the scenes in MinGW than it is with gcc for Linux alignment-wise.
732,609
732,641
What are some good tools for measuring memory allocations on Windows?
I have an application that keeps using up more and more memory as time goes by (while actively running), but there are no leaks. So I know the program isn't doing something totally wrong, which would be easy to find. Instead I want to track allocations so I can start tracking down the issue, and on a Mac I'd use Instruments, which gives a detailed profile of what objects have been allocated, and by whom, but on Windows what would I use? Currently I'm working with C/C++ on Windows XP, using VS2005. So any tools for this setup would be great, and hopefully tools that are free or at least provide a few weeks of trial, because it'll take a while to complete any purchase (corporate stuff) if necessary, and I have deadlines. Thanks! Edit: I'm using VLD, so I know the program has no Leaks, but it seems to be hogging more memory than needed, and not returning it, so I need to track allocations, not leaks.
Memory validator would be ideal for you. http://www.softwareverify.com/cpp/memory/index.html
732,687
992,793
Line Segment container for fast Ray intersection? (2D)
I have a ray, I need to find the closest line segment that it hits. I think it's possible to do this in O(log n) time if I sort the line segments first, but I can't remember how to sort them... I think some sort of tree would work best, but how do I sort them by both start and end point? I would also like fast insertions into this data structure if possible. There's lots of code for one ray vs one line segment, but I need something for one ray vs many line segments... I don't know what terms to google for. A link to an appropriate article is good, C++ code is even better. Thanks! :) PS: The line segments are actually the edges of a non-self-intersecting polygon, sorted in CCW order... but I think there may be some advantage to sorting them in a different fashion? This is all 2D. On second thought, I'm not entirely sure this is possible. Some sort of spatial partitioning might help, but otherwise, I can't think of any way to sort the lines so that they could be compared with an arbitrary ray.
You could take a bounding box of the polygon (min-max x,y coordinates) and build a grid inside the box. Then, for each cell, remember all lines that cross the cell. Find an intesection like this: Find out which cell the ray hits first (O(1)) Use Grid traversal algorithm to "draw" a ray through the grid. When you hit non-empty cell, check all its lines, check if intersection is inside the cell and pick the closest intersection. If all intersections are outside the cell, continue (this is O(grid length)). You could also make the grid hierarchical (ie. quadtree - a tree you were asking for), and walk it using the same algorithm. This is done in raytracing in 3D and the time complexity is O(sqrt(N)). Or, use the approach I did in my raytracer: Build a quadtree containing the lines (building quadtree is desribed in the article) - you split nodes (=areas) if they contain too many objects into 4 sub-nodes (sub-areas) Collect all leaf nodes of the quadtree that are hit by the ray: Compute ray-rectangle intersection (not hard) for the root. If the root is hit by the ray, proceed with its children recursively. The cool thing about this is that when a tree node is not hit, you've skipped processing whole subtree (potentially a large rectangular area). In the end, this is equivalent to traversing the grid - you collect the smallest cells on the ray's path, and then test all objects in them for intersection. You just have to test all of them and pick the closest intersection (so you explore all lines on ray's path). This is O(sqrt(N)). In grid traversal, when you find an intersection, you can stop searching. To achieve this with quadtree traversal, you would have to seach the children in the right order - either sort the 4 rect intersections by distance or cleverly traverse the 4-cell grid (an we are back to traversal). This is just a different approach, comparatively same difficult to implement I think, and works well (I tested it on real data - O(sqrt(N))). Again, you would only benefit from this approach if you have at least a couple of lines, when the polygon has 10 edges the benefit compared to just testing all of them would be little I think.
732,893
732,948
Using Borland C++ Code in VC++
Is there a way to access Borland output in VC++, for method calls and other stuff? Thanks
My info may be (way) outdated, but what I had to before was to make sure that Borland output a COFF format OBJ or LIB file to link with VC. The other option is to have Borland output a DLL, and then use that from VC++. Name mangling and calling conventions may cause a pain. I honestly haven't used a Borland compiler in half a decade(even though I used to work there, a decade and half ago), so I'm not sure if a LIB for a Borland compiled DLL will link nicely with VC++. If all else fails, compile a DLL with the Borland compiler, use Dumpbin to find the exports, then LoadLibrary and GetProcAddress to get the function pointers.
732,894
732,910
Access violation with malloc() and glDrawPixels()?
Can anyone see what's wrong with this code? SIZE_BG is 6MB as I am trying to draw a large bitmap image (3366x600). I use malloc to prevent my image from overflowing the stack. I get an access violation error on the call to glDrawPixels(). bgPtr seems to point to the correct data as I checked the first few bytes before calling glDrawPixels and they are correct. bgPtr = (char*)malloc(SIZE_BG); fstream inFile(texFileName, ios::in | ios::binary); inFile.read(bgPtr, SIZE_BG); inFile.close(); //... other code glDrawPixels(3366, 600, GL_BGRA_EXT, GL_UNSIGNED_BYTE, bgPtr+54);
SIZE_BG is 6MB 3366 × 600 is approximately 1.92 million pixels BRGA indicates 4 bytes per pixel so, 3366 × 600 × 4 is just over 7.7MB Therefore, your buffer is too small... glDrawPixels() will read past the end into unallocated memory.
733,056
733,064
Is there a way to get function name inside a C++ function?
I want to implement a function tracer, which would trace how much time a function is taking to execute. I have following class for the same:- class FuncTracer { public: FuncTracer(LPCTSTR strFuncName_in) { m_strFuncName[0] = _T('\0'); if( strFuncName_in || _T('\0') != strFuncName_in[0]) { _tcscpy(m_strFuncName,strFuncName_in); TCHAR strLog[MAX_PATH]; _stprintf(strLog,_T("Entering Func:- <%s>"),m_strFuncName); LOG(strLog) m_dwEnterTime = GetTickCount(); } } ~FuncTracer() { TCHAR strLog[MAX_PATH]; _stprintf(strLog,_T("Leaving Func:- <%s>, Time inside the func <%d> ms"),m_strFuncName, GetTickCount()-m_dwEnterTime); LOG(strLog) } private: TCHAR m_strFuncName[MAX_PATH]; DWORD m_dwEnterTime; }; void TestClass::TestFunction() { // I want to avoid writing the function name maually.. // Is there any macro (__LINE__)or some other way to // get the function name inside a function ?? FuncTracer(_T("TestClass::TestFunction")); /* * Rest of the function code. */ } I want to know if there is any way to get the name of the function from inside of a function? Basically I want the users of my class to simply create an object the same. They may not pass the function name.
VC++ has __FUNCTION__ for undecorated names and __FUNCDNAME__ for decorated names And you can write a macro that will itself allocate an object and pass the name-yelding macro inside the constructor. Smth like #define ALLOC_LOGGER FuncTracer ____tracer( __FUNCTION__ );
733,537
734,061
Should I be using dynamic_cast<T> for copying?
Update 1: Corrected nonsense code! Thanks for comments, I made a hash of the first snippet, oops. Update 2: Also updated question title, as the use of dynamic_cast has been pointed out as not necessary by answers. What I'm trying to achieve here is a deep copy using strong types; I want to be able to copy Class2 to another instance of Class2; however, I also want to use the CopyTo function from the Class1 which is the base. This idea comes from my C# experience, where usually I'd just make the return type generic (see C# snippet). void Class1::CopyTo(Class1 *c1) { // Write data in to c1 from this instance. c1->exampleData = exampleData; } // Class2 inherits Class1 Class2 *Class2::Copy() { Class2 *c2a = new Class2(); CopyTo(c2a); Class2 *c2b = dynamic_cast<Class2*>(c2a); return c2a; } And here's the way I'd so it in C#: public class Class1 { T Copy<T>() where T : Class1 { /* Can't remember the best way to do this in C#; * basically if T was Class2 this would need to create * a new instance of that class, and the same goes for * Class1. */ T copy = createNewInstance(); // Copy the data from this to 'copy'. copy.exampleData = exampleData; return copy; } } Now, compared to the C# snippet, the C++ snippet feel smelly. Is it possible to do this without pointers, or is this way best practice?
I'm not sure what you are trying to achieve because the code still doesn't make much sense. However, I believe the following should approximate what you're trying to do. Note that I don't use heap memory: it's not necessary and it would leak memory. template <typename T> T Class1::Copy() { T instance; CopyTo(&instance); return instance; } This works because you pass a (polymorphic) pointer to instance to the CopyTo method of Class1. Then you could call the code like this: Class2 x1; // Fill x1 Class2 x2 = x1.Copy<Class2>(); However, this code still smells because it's no idiomatic C++: In C++, you would usually write a copy constructor instead. Late-bound Copy methods do exist but they are very rarely needed, and the above is not late bound (but neither is your C# code).
733,717
733,796
Difference between DECLARE_DYNAMIC and DECLARE_DYNCREATE?
Could you please let me know what is difference between DECLARE_DYNAMIC and DECLARE_DYNCREATE? Where exactly we can use them?
The first declares that a class has runtime type info and the second that instances can be created dynamically at runtime. This is described in detail in the MSDN documentation - see links like Run-Time Object Model Services for more info.
733,737
733,791
Are inline virtual functions really a non-sense?
I got this question when I received a code review comment saying virtual functions need not be inline. I thought inline virtual functions could come in handy in scenarios where functions are called on objects directly. But the counter-argument came to my mind is -- why would one want to define virtual and then use objects to call methods? Is it best not to use inline virtual functions, since they're almost never expanded anyway? Code snippet I used for analysis: class Temp { public: virtual ~Temp() { } virtual void myVirtualFunction() const { cout<<"Temp::myVirtualFunction"<<endl; } }; class TempDerived : public Temp { public: void myVirtualFunction() const { cout<<"TempDerived::myVirtualFunction"<<endl; } }; int main(void) { TempDerived aDerivedObj; //Compiler thinks it's safe to expand the virtual functions aDerivedObj.myVirtualFunction(); //type of object Temp points to is always known; //does compiler still expand virtual functions? //I doubt compiler would be this much intelligent! Temp* pTemp = &aDerivedObj; pTemp->myVirtualFunction(); return 0; }
Virtual functions can be inlined sometimes. An excerpt from the excellent C++ faq: "The only time an inline virtual call can be inlined is when the compiler knows the "exact class" of the object which is the target of the virtual function call. This can happen only when the compiler has an actual object rather than a pointer or reference to an object. I.e., either with a local object, a global/static object, or a fully contained object inside a composite."
733,900
733,947
Force garbage collection/compaction with malloc()
I have a C++ program that benchmarks various algorithms on input arrays of different length. It looks more or less like this: # (1) for k in range(4..20): # (2) input = generate 2**k random points for variant in variants: benchmark the following call run variant on input array # (3) Is it possible to reset the whole heap management at (2) to the state it had at (1)? All memory allocated on the heap that was allocated during the program is guaranteed to be freed at (3). I am using g++ 4.3 on Linux. Edit: I understand that there is no real garbage collection in C/C++. I want to force the memory allocation to join adjacent empty chunks of memory it has in its free list at (2).
If you want the test runs to start in the same heap states, you can run them in their own processes created by fork().
733,971
733,977
Password Information
I want to get the various user account passwords which are stored in my computer programatically using Visual C++. Are there any APIs to help me do this?
There is no way to retrieve windows passwords nor passwords to most other programs via Win32 APIs. For Windows passwords you typically have to ask the user to enter their username/password and verify it, all by using LogonUser. For other programs they are usually stored on disk encrypted by the host application.
734,075
734,100
friend class/function in c++
Possible Duplicate: When should you use 'friend' in C++? I see a lot of people recommending a function/class to be made a friend of another class here in SO though there are other alternatives. Shouldn't friend be sparingly used in C++? I feel other options must be considered before deciding on using the friend feature. Opinions/suggestions are welcome.
Without specific examples this is hard to decide. While friend isn't strictly necessary it does have its uses. If, as you claim, there are better alternatives then obviously use them, by simple definition of the word “better”. Or maybe the decision which solution is better isn't that clean-cut after all. Personally, I prefer to avoid it when possible but I prefer to use it over method duplication: for example, I do not like to write a print method just to avoid making operator << a friend because I don't see the benefit of the duplicate method.
734,140
734,304
C# crash when loading C++ dll
My program is written in C# NET 2.0,it's using external functions from a dll written in C++ using Microsoft Visual Studio 2008 SP1. If I remove the dll from the directory the program is placed,the program crashes at the moment it should use the dll.That's normal. But the users that are using my program get the same error at the same place without moving the dll.They all have C++ Redistributable 2008 from >here< Does it happen because I made the program in .NET 2.0 instead of NET 3.5 or it happens ,because the redistributable should be an older version? Edit:Note for me,the program runs fine. >>new thread<<
Its most likely the wrong runtime. Make sure you are distributing the correct one. These will always work on your dev box because the runtimes are in the path. For testing software, I use a windows xp virtual machine. I set up the virtual machine as a completely fresh install, install the components I know that I need (.NET framework, etc.), then run my installer. You will run into a surprising number of setup issues doing this.
734,158
734,175
Does rearranging a conditional evaluation speed up a loop?
Bit of a weird one: I was told a while ago by a friend that rearranging this example for loop from : for(int i = 0; i < constant; ++i) { // code... } to: for(int i = 0; constant > i; ++i) { // code... } would slightly increase performance in C++. I don't see how comparing a constant value to a variable is faster than vice-versa, and some rudimentary tests I ran didn't show any difference in speed between the two implementations. The same was also true of testing this Python while loop: while i < constant: # code... i += 1 vs: while constant > i: # code... i += 1 Am I wrong? Are my simple tests not enough to determine the speed variation? Is this true of other languages? Or is this just a new best practice?
It's more in the line of C++ folklore, hand micro-optimizations that worked once on a particular version of a particular compiler and get passed down ever after as some kind of lore distinguishing the possessor from the common herd. It's rubbish. Profiling is truth.
734,217
734,236
How much of STL is too much?
I am using a lot of STL code with std::for_each, bind, and so on, but I noticed that sometimes STL usage is not good idea. For example if you have a std::vector and want to do one action on each item of the vector, your first idea is to use this: std::for_each(vec.begin(), vec.end(), Foo()) and it is elegant and ok, for a while. But then comes the first set of bug reports and you have to modify code. Now you should add parameter to call Foo(), so now it becomes: std::for_each(vec.begin(), vec.end(), std::bind2nd(Foo(), X)) but that is only temporary solution. Now the project is maturing and you understand business logic much better and you want to add new modifications to code. It is at this point that you realize that you should use old good: for(std::vector::iterator it = vec.begin(); it != vec.end(); ++it) Is this happening only to me? Do you recognise this kind of pattern in your code? Have you experience similar anti-patterns using STL?
Using boost::bind with std::for_each solves this problem in a clean way. Or you can use BOOST_FOREACH. Example of std::for_each: std::for_each(v.begin(), v.end(), boost::bind(&C::f, _1, param)); Example of BOOST_FOREACH: std::list<int> list_int( /*...*/ ); BOOST_FOREACH( int i, list_int ) { // do something with i }
734,227
734,265
Co-mingling low-level C/C++ code
I am planning to write a code library to access some hardware at a low-level (i.e. flipping register bits and such). Previously, I wrote everything as C functions and used extern "C" to make the library compile for both C and C++ code. So, both C and C++ users merely had to include the header file and call the functions as they were. Now, I am thinking of organising things as classes. For example, I can put all the functions to initialise, configure, transmit and receive a UART in a class. This works fine in C++ but how about C? I can't extern "C" an entire class. One thing that I was thinking of: write everything in standard C functions escaped with extern "C". Then, provide a wrapper class for C++, that has a bunch of inline methods that call these 'C' functions. int foo_bar (int *address, int data) {...} // extern C stuff int foo::bar (int *address, int data) { return foo_bar(address, data); } // inline method Is that okay? Any other ideas? Best practices?
There is some precedent for what you're proposing - Microsoft's MFC classes are just C++ wrappers around the C-compatible Windows API. Before you start though, you should have some goal in mind beyond just creating busywork for yourself. The C++ should be easier to work with than the C, or you're not gaining anything.
734,259
734,330
With OpenGL, how can I use gluOrtho2D properly with default projection?
I'm trying to use gluOrtho2D with glutBitmapCharacter so that I can render text on the screen as well as my 3D objects. However, when I use glOrtho2D, my 3D objects dissapear; I assume this is because I'm not setting the projection back to the OpenGL/GLUT default, but I'm not really sure what that is. Anyway, this is the function I'm using to render text: void GlutApplication::RenderString(Point2f point, void* font, string s) { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0.0, WindowWidth, 0.0, WindowHeight); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glDisable(GL_TEXTURE); glDisable(GL_TEXTURE_2D); glRasterPos2f(point.X, point.Y); for (string::iterator i = s.begin(); i != s.end(); ++i) { glutBitmapCharacter(font, *i); } glEnable(GL_TEXTURE); glEnable(GL_TEXTURE_2D); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); } And, the render function is similar to this: glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); glLoadIdentity(); // Do some translation here. // Draw some 3D objects. glPopMatrix(); // For some reason, this stops the above from being rendered, // where the camera is facing (I assume they are still being rendered). Point2f statusPoint(10, 10); RenderString(statusPoint, GLUT_BITMAP_9_BY_15, "Loading...");
Your code looks okay. Most likely you've just messed up the matrix stack somewhere. I suggest that you check if you forgot a glPopMatrix somewhere. To do so you can get the stack depth via glGet(GL_MODELVIEW_STACK_DEPTH). Getters for the other matrix-stacks are available as well. Also you can take a look at the current matrix. Call glGetFloatv(GL_MODELVIEW_MATRIX, Pointer_To_Some_Floats) to get it. You can print out the floats each time you've set up a modelview or projection matrix. That way you should be able to to find out which matrix erratically ends up as the current matrix. That should give you enough clues to find the bug.
734,272
758,840
How to use WinDbg to analyze the crash dump for VC++ application?
How do I use WinDbg for analyzing a dump file?
Here are some general steps that will get you on your way: First, you must change your compiler's settings so that it creates PDB files, even for release builds. Later versions of the Visual C++ compiler do this by default, but in many versions of Visual C++ you must do this yourself. Create program database files, and then keep an archive of those files along with each build of your application. It is critical that every build of your applications has its own set of PDBs. You can't just reuse the same ones you made with build 10 to examining the dumps generated by build 15, for example. Over the life of your project, you will end up with a ton of PDBs, so be prepared for that. Next, you need to be able to identify the exact version of your application which generated the dump file. If you are creating your own MiniDumps (by calling MiniDumpWriteDump() for example), probably the easiest way to do this is to simply make part of the filename of the MiniDump the complete version number of your application. You'll need to have a reasonable version numbering scheme in place for this to work. In my shop, we increment the build number across all branches by one every time the autobuilder creates a build. Now that you have received the dump file from the customer, you know the precise version of the application that created the dump, and you have found the PDB files for this build. Now you need to go through your source control's history and find the source code for this exact version of the software. The best way to do this is to apply 'labels' to your branches every time you make a build. Set the value of the label to the exact version number, and it becomes easy to find in the history. You're almost ready to fire up WinDbg/Visual C++: Get the complete source tree for that version of your application. Put it in a separate place on your hard drive, say c:\app_build_1.0.100 for application version 1.0 build #100. Get the binaries for that exact version of your application and put them somewhere on your hard drive. It might be easiest simply to install that version of your application to get the binaries. Put the PDB files in the same location as the binaries in step 2. Now you have two options for viewing the dump file. You can use Visual Studio or WinDbg. Using Visual Studio is easier, but WinDbg is much more powerful. Most of the time the functionality in Visual Studio will suffice. To use Visual Studio, all you have to do is open the dump file like it is a project. Once opened, "run" the dump file (F5 by default) and if all the paths are set correctly it will take you right to the code that crashed, give you a call stack, etc. To use WinDbg, you have to jump through a couple of hoops: Start WinDbg Open the dump file. (Ctrl + D by default) Tell WinDbg to go get the correct MicroSoft symbol files. Type .symfix. This may take a few moments as it will pull a ton of stuff down from the Internet. Tell WinDbg where the symbols (PDB files) are. Type .sympath+ c:\pdblocation, substituting wherever you put the PDB files for the pathname. Make sure you get the plus sign in there with no whitespace between .sympath and the + sign or else you'll screw up step 3. Tell WinDbg where the source code is. Type .srcpath c:\app_build_1.0.100 substituting the path where you got code from source control for this version of the software. Tell WinDbg to analyze the dump file. Type !analyze -v After a few moments, if everything is configured correctly, WinDbg will take you right to the location of your crash. At this point you have a million options for digging deep into your application's memory space, the state of critical sections, windows, etc. But that is way beyond the scope of this post. Good luck!
734,551
734,899
How to update a dialog box via SetDlgItemText within a function and have it take effect immediately in windows?
If I call SetDlgItemText() to update the value of a dialog text it seems to only be updated when the function returns. I'm using it to update a status message informing the user of the current progress mid function so I would like it to be updated immediately. If this can not be done, is there something else I can do that would perform the same results? Any help would be appreciated. Thanks.
I think Processing function is not allowing to call the OnPaint message of the window to which you are setting the message. You can move the processing function to a thread so that main thread handles the UI messages.
734,802
734,823
Fixed-width integers in C++
Occasionally I need to use fixed-width integers for communication with external devices like PLCs. I also use them to define bitmasks and perform bit manipulation of image data. AFAIK the C99 standard defines fixed-width integers like int16_t. However the compiler I use, VC++ 2008 doesn't support C99 and AFAIK Microsoft is not planning to support it. My question is what is the best practice for using fixed-width integers in C++? I know that VC++ defines non-standard fixed-width integers like __int16, but I am hesitant to use a non-standard type. Will the next C++ standard define fixed-width integers?
Boost has the typedefs for all of the C99 types and more: "Boost integer library"
734,936
734,967
What is the best header structure to use in a library?
Concerning headers in a library, I see two options, and I'm not sure if the choice really matters. Say I created a library, lets call it foobar. Please help me choose the most appropriate option: Have one include in the very root of the library project, lets call it foobar.h, which includes all of the headers in the library, such as "src/some_namespace/SomeClass.h" and so on. Then from outside the library, in the file that I want to use anything to do with the foobar library, just #include <foobar.h>. Don't have a main include, and instead include only the headers we need in the places that I am to use them, so I may have a whole bunch of includes in a source file. Since I'm using namespaces sometimes as deep as 3, including the headers seems like a bit of a chore. I've opted for option 1 because of how easy it is to implement. OpenGL and many other libraries seem to do this, so it seemed sensible. However, the standard C++ library can require me to include several headers in any given file, why didn't they just have one header file? Unless it's me being and idiot, and they're separate libraries... Update: Further to answers, I think it makes sense to provide both options, correct? I'd be pretty annoyed if I wanted to use a std::string but had to include a mass of header files; that would be silly. On the other hand, I'd be irritated if I had to type a mass of #include lines when I wanted to use most of a library anyway. Forward headers: Thanks to all that advised me of forward headers, this has helped me make the header jungle less complicated! :)
stl, boost and others who have a lot of header files to include they provide you with independent tools and you can use them independently. So if you library is a set of uncoupling tools you have to give a choice to include them as separate parts as well as to include the whole library as the one file.