question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,008,534
1,008,542
what does this C++ macro do?
This is for MSVC #define Get64B(hi, lo) ((((__int64)(hi)) << 32) | (unsigned int)(lo)) Specifically, what is the role of the 'operator <<' ? Thanks for your help
<< is the left shift operator. This macro is intended to make a 64-bit value from two 32 bit values, using the first argument as the top 32 bits and the second argument as the bottom 32 bits of the new value.
1,008,726
1,008,914
Win32 Read/Write Lock Using Only Critical Sections
I have to implement a read/write lock in C++ using the Win32 api as part of a project at work. All of the existing solutions use kernel objects (semaphores and mutexes) that require a context switch during execution. This is far too slow for my application. I would like implement one using only critical sections, if possible. The lock does not have to be process safe, only threadsafe. Any ideas on how to go about this?
I don't think this can be done without using at least one kernel-level object (Mutex or Semaphore), because you need the help of the kernel to make the calling process block until the lock is available. Critical sections do provide blocking, but the API is too limited. e.g. you cannot grab a CS, discover that a read lock is available but not a write lock, and wait for the other process to finish reading (because if the other process has the critical section it will block other readers which is wrong, and if it doesn't then your process will not block but spin, burning CPU cycles.) However what you can do is use a spin lock and fall back to a mutex whenever there is contention. The critical section is itself implemented this way. I would take an existing critical section implementation and replace the PID field with separate reader & writer counts.
1,008,957
1,011,849
Interprocess communication on windows
I have a TCL script running on windows. I need to communicate to a old vc++ 6 app running in a different process. I need to have 2 way communication. In Linux I would use dbus, but what IPC strategy should I use for windows?
Tcl on windows has dde support built-in (see docs for the dde command) which could help if the other application supports this. Another option is the TWAPI (Tcl Windows API) extension, which has facilities for sending keyboard and mouse input to another application, see http://twapi.magicsplat.com/input.html .
1,009,091
1,009,207
Decode JPEG to obtain uncompressed data
I want to decode JPEG files and obtain uncompressed decoded output in BMP/RGB format.I am using GNU/Linux, and C/C++. I had a look at libjpeg, but there seemed not to be any good documentation available. So my questions are: Where is documentation on libjpeg? Can you suggest other C-based jpeg-decompression libraries?
The documentation for libjpeg comes with the source-code. Since you haven't found it yet: Download the source-code archive and open the file libjpeg.doc. It's a plain ASCII file, not a word document, so better open it in notepad or another ASCII editor. There are some other .doc files as well. Most of them aren't that interesting though. Unfortunately I cannot recommend any other library besides libjpeg. I tried a couple of alternatives, but Libjpeg always won. Is pretty easy to work with once you have the basics done. Also it's the most complete and most stable jpeg library out there.
1,009,098
1,009,284
Linking with both static and dynamic libraries in MSVC
I am working on a c++ project that links to a static library. However, I want to use intel's TBB, which is only available as a dynamic library. I tried to set this up in visual studio but I can't get it to work. Does anyone have detailed directions to do this if it is possible?
Typically when a library is made available as a dynamic library (.dll), it also comes with a .lib file to link against (as discussed in this question). This can be added to the project's list of inputs the same way that a static library is Project Properties->Configuration Properties->Linker->Input->Additional Dependencies (in VS2008) If a .lib is not available, then you'll have to load the .dll at runtime using Win32 API function LoadLibraryEx and then subsequent calls to GetProcAddress to get the addresses of the functions you need.
1,009,137
1,009,144
stl vector memory management
I am using borland 2006 c++, and have following code. I am using vectors, and have trouble understanding why the destructor is not being called. basically i have a class A class A { private: TObjectList* list; int myid; public: __fastcall A(int); __fastcall ~A(); }; __fastcall A::A(int num) { myid = num; list = new TObjectList(); } __fastcall A::~A() { delete list; } int main(int argc, char* argv[]) { myfunc(); return 0; } void myfunc() { vector<A*> vec; vec.push_back(new A(1)); vec.push_back(new A(2)); } according to what i read, when variable vec goes out of scope in myfunc(), it should destruct its contained elements, so the destructor for A should be called. I have a breakpoint at ~A(), but never gets called, i have tried resize(), erase methods also TIA
vec does destruct its elements when it goes out of scope. The problem here is that vec's elements are the pointers to A objects, not A objects themselves. If you instead did vector<A> vec; vec.push_back(A(1)); vec.push_back(A(2)); ...then things would work as you expect. ETA: note, though, that if you do this you have to define a copy constructor for A. That should involve doing a deep copy of the TObjectList member. Otherwise, when you copy an A object you'll wind up with two objects both pointing to the same TObjectList, and your program will crash when the second object is destroyed.
1,009,150
1,009,195
C++/OpenGL - Rotating a rectangle
For my project i needed to rotate a rectangle. I thought, that would be easy but i'm getting an unpredictable behavior when running it.. Here is the code: glPushMatrix(); glRotatef(30.0f, 0.0f, 0.0f, 1.0f); glTranslatef(vec_vehicle_position_.x, vec_vehicle_position_.y, 0); glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); glVertex2f(0, 0); glTexCoord2f(1.0f, 0.0f); glVertex2f(width_sprite_, 0); glTexCoord2f(1.0f, 1.0f); glVertex2f(width_sprite_, height_sprite_); glTexCoord2f(0.0f, 1.0f); glVertex2f(0, height_sprite_); glEnd(); glDisable(GL_BLEND); glDisable(GL_TEXTURE_2D); glPopMatrix(); The problem with that, is that my rectangle is making a translation somewhere in the window while rotating. In other words, the rectangle doesn't keep the position : vec_vehicle_position_.x and vec_vehicle_position_.y. What's the problem ? Thanks
You need to flip the order of your transformations: glRotatef(30.0f, 0.0f, 0.0f, 1.0f); glTranslatef(vec_vehicle_position_.x, vec_vehicle_position_.y, 0); becomes glTranslatef(vec_vehicle_position_.x, vec_vehicle_position_.y, 0); glRotatef(30.0f, 0.0f, 0.0f, 1.0f);
1,009,165
1,039,103
VS2008 internal compiler error
I'm consistently running into an internal compiler error while attempting to switch from MSVC6 to MSVC 2008. After much work commenting out different parts of the program, I've traced the error to two lines of code in two different CPP files. Both of these CPP files compile successfully, yet somehow have an effect on whether or not the error manifests in other files. Both of those lines involve instantianting several complex, nested templates. They also appear to be the only places in the app that use an abstract class as one of the template parameters. That said, I'm far from certain that the issue involves either abstract classes or templates, it's just the most obvious thing I've noticed. I can't even be sure that these lines are significant at all. Here's what they look like, though: m_phDSAttributes = new SObjDict<RWCString, SIDataSource>(&RWCString::hash); So we've got SObjDict, a templatized dictionary class, SIDataSource, an abstract interface, and the parameter is a pointer to a static member function of RWCString. I've been playing around with the code some, and I can occasionally get the error to move from one CPP file to another (for instance, I changed a bunch of template declarations from using class to typename), but I can't find any rhyme or reason to it. I'm at a loss as to how to debug this issue further. The exact error output by the compiler (with the name of my source file changed) is below. There is no mention of it anywhere on the internet. I'm pretty desperate for any advice on how to proceed. I don't expect someone to say "oh, you just need to do XYZ", but a pointer on how to debug this sort of issue would be greatly appreciated. 1>d:\Dev\webapi.cpp : fatal error C1001: An internal error has occurred in the compiler. 1>(compiler file 'f:\dd\vctools\compiler\utc\src\p2\p2symtab.c', line 5905)
I feel somewhat bad putting an answer on my own question and accepting it, but I guess it's the right thing to do... I solved my problem, at least temporarily. The trick seems to be disabling precompiled headers. I have no idea why that solves the problem, and it's very unfortunate since my build time for the affected project has gone from less than 30 secs to nearly 5 minutes, but at least I can progress forward... If anyone comes up with a more permanent solution, I'd be more than happy to mark their answer as Accepted.
1,009,225
1,009,274
Free C++ lib (Win32) to record microphone
is there any recommendation for a library (c++, Win32, open source) to get the sound from a microphone? Thanks
Try having a look at OpenAL[1] it might be overkill, but should be able to record from microphone as you wanted. There exists some pretty good articles about it on Gamedev.net[2] although I'm afraid none of them tells you how to record from a microphone. You should however be able to find the answer for that in the documentation. :) good luck, [1] http://connect.creativelabs.com/openal/default.aspx [2] http://www.gamedev.net/reference/articles/article2008.asp
1,009,254
1,009,275
Programmatically getting UID and GID from username in Unix?
I'm trying to use setuid() and setgid() to set the respective id's of a program to drop privileges down from root, but to use them I need to know the uid and gid of the user I want to change to. Is there a system call to do this? I don't want to hardcode it or parse from /etc/passwd . Also I'd like to do this programmatically rather than using: id -u USERNAME Any help would be greatly appreciated
Have a look at the getpwnam() and getgrnam() functions.
1,009,335
1,009,434
stl vectors add sequence
Iam using borland 2006 c++ class A { private: TObjectList* list; int myid; public: __fastcall A(int); __fastcall ~A(); }; __fastcall A::A(int num) { myid = num; list = new TObjectList(); } __fastcall A::~A() { } int main(int argc, char* argv[]) { myfunc(); return 0; } void myfunc() { vector<A> vec; vec.push_back(A(1)); } when i add a new object A to the vector, it calls its destructor twice, and then once when vec goes out of scope , so in total 3 times. I was thinking it should call once when object is added, and then once when vec goes out scope.
The expression A(1) is an r-value and constructs a new A value, the compiler may then copy this into a temporary object in order to bind to the const reference that push_back takes. This temporary that the reference is bound to is then copied into the storage managed by vector. The compiler is allowed to elide temporary objects in many situations but it isn't required to do so.
1,009,356
1,009,379
How do I make a file self-update (Native C++)
I'm using Microsoft Visual Studio 2008 with a Windows target deployment. How would I make a file "update itself"? I've already got the "transmitting over a network" part down, but how do I make an executable write over itself? Basically, I want to write an auto-updater for a directory that also includes the auto-updater, and the updater needs to update EVERYTHING in the directory. Maybe a ways to pend the changes to the file for until the file lock is released would work. If I were to do that though, I'd probably follow it up with a hot-patch.
Write a new executable and delete or save a copy of the old one -- you could send a diff over the network and have a third program, the update monitor or whatever, to apply it. It would be just a small script that could be started from the remote app when it realizes an update is available. The updater could rename itself to $UPDATER_OLD_VERSION or whatever, write an updated copy of itself with the appropriate name, and then when the new updater is run you check if there is a file named $UPDATER_OLD_VERSION in the app directory and delete it. All other files could just be updated/overwritten.
1,009,691
1,009,770
Can assignment be done before constructor is called?
A comment to What's wrong with this fix for double checked locking? says: The issue is that the variable may be assigned before the constructor is run (or completes), not before the object is allocated. Let us consider code: A *a; void Test() { a = new A; } To allow for more formal analysis, let us split the a = new A into several operations: void *mem = malloc(sizeof(A)); // Allocation new(mem) A; // Constructor a = reinterpret_cast<A *>(mem); // Assignment Is the comment quoted above true, and if it is, in what sense? Can Constructor be executed after the Assignment? If it can, what can be done against it when guaranteed order is needed because of MT safety?
The issue isn't so much when code executes, but more to do with write-ordering. Let's suppose: A() { member = 7; } Then later: singleton = new A() This results in code that does an allocation, a write to memory (member), and then a write to another memory location (singleton). Some CPU's can re-order writes such that the write to member will not be visible until after the write to singleton - in essence, code running on other CPU's in the system could have a view of memory where singleton is written to, but member is not.
1,009,755
1,009,769
How do I convert something of "string*" to "const string&" in C++?
For example, if I have the following: void foo(string* s) { bar(s); // this line fails to compile, invalid init. error } void bar(const string& cs) { // stuff happens here } What conversions do I need to make to have the call the bar succeed?
Change it to: bar(*s);
1,010,106
1,010,811
How to debug heap corruption errors?
I am debugging a (native) multi-threaded C++ application under Visual Studio 2008. On seemingly random occasions, I get a "Windows has triggered a break point..." error with a note that this might be due to a corruption in the heap. These errors won't always crash the application right away, although it is likely to crash short after. The big problem with these errors is that they pop up only after the corruption has actually taken place, which makes them very hard to track and debug, especially on a multi-threaded application. What sort of things can cause these errors? How do I debug them? Tips, tools, methods, enlightments... are welcome.
Application Verifier combined with Debugging Tools for Windows is an amazing setup. You can get both as a part of the Windows Driver Kit or the lighter Windows SDK. (Found out about Application Verifier when researching an earlier question about a heap corruption issue.) I've used BoundsChecker and Insure++ (mentioned in other answers) in the past too, although I was surprised how much functionality was in Application Verifier. Electric Fence (aka "efence"), dmalloc, valgrind, and so forth are all worth mentioning, but most of these are much easier to get running under *nix than Windows. Valgrind is ridiculously flexible: I've debugged large server software with many heap issues using it. When all else fails, you can provide your own global operator new/delete and malloc/calloc/realloc overloads -- how to do so will vary a bit depending on compiler and platform -- and this will be a bit of an investment -- but it may pay off over the long run. The desirable feature list should look familiar from dmalloc and electricfence, and the surprisingly excellent book Writing Solid Code: sentry values: allow a little more space before and after each alloc, respecting maximum alignment requirement; fill with magic numbers (helps catch buffer overflows and underflows, and the occasional "wild" pointer) alloc fill: fill new allocations with a magic non-0 value -- Visual C++ will already do this for you in Debug builds (helps catch use of uninitialized vars) free fill: fill in freed memory with a magic non-0 value, designed to trigger a segfault if it's dereferenced in most cases (helps catch dangling pointers) delayed free: don't return freed memory to the heap for a while, keep it free filled but not available (helps catch more dangling pointers, catches proximate double-frees) tracking: being able to record where an allocation was made can sometimes be useful Note that in our local homebrew system (for an embedded target) we keep the tracking separate from most of the other stuff, because the run-time overhead is much higher. If you're interested in more reasons to overload these allocation functions/operators, take a look at my answer to "Any reason to overload global operator new and delete?"; shameless self-promotion aside, it lists other techniques that are helpful in tracking heap corruption errors, as well as other applicable tools. Because I keep finding my own answer here when searching for alloc/free/fence values MS uses, here's another answer that covers Microsoft dbgheap fill values.
1,010,297
1,015,009
MFC: CButton highlighting for a group of radio buttons
I know that I can create an integer variable for a group of radio buttons, set it to an integer, and then call UpdateData(FALSE) to make the window highlight the appropriate radio button control. However, I would like to perhaps use a CButton control instead, but I don't know how to set the CButton state so that a particular radio button of the group is checked. Is it even possible to do so for MFC? Thanks in advance.
As I only need to set the states upon startup or reset states, I linked the CButton control with the appropriate id flag for the CButton control before switch them to on. The CButton control can later contain other values as onclicked() handlers are used for me to map selected radio button values properly. void UserControls::DoDataExchange(CDataExchange* pDX) { ... // Mapping the integer variables to the Radio control for proper // displaying // not the id of the first radio button of the group for both of them DDX_Control(pDX, IDC_NOBTL, nobCtrl); DDX_Control(pDX, IDC_UIHARD, uiCtrl); ... }
1,010,539
1,010,640
Changing return type of a function without template specialization. C++
I was wondering if it is possible to change the return type of a function based on the type of variable it is being assigned to. Here's a quick example of what I mean. I want to create a function that parses a variable of int, bool, or float from a string. For example... Int value = parse("37"); Float value = parse("3.14"); Bool value = parse("true"); I understand if I make this function a template, that the variable type must be determined from the argument list which is always going to be a string. Is there any other way of doing this with c++?
This can be done with a conversion function struct proxy { string str; proxy(string const &str):str(str) { } template<typename T> operator T() { return boost::lexical_cast<T>(str); } }; proxy parse(string const &str) { return proxy(str); } Now you just need to do float a = parse("3.1"); And it should work well. Incidentally, you may just use the class directly. I recommend renaming it to conversion_proxy to point to the fact that it's just a proxy to a happening conversion but that it itself doesn't do conversion struct conversion_proxy { string str; conversion_proxy(string const &str):str(str) { } template<typename T> operator T() { return boost::lexical_cast<T>(str); } }; float a = conversion_proxy("3.1");
1,010,783
1,010,785
What encoding does std::string.c_str() use?
I am trying to convert a C++ std::string to UTF-8 or std::wstring without losing information (consider a string that contains non-ASCII characters). According to http://forums.sun.com/thread.jspa?threadID=486770&forumID=31: If the std::string has non-ASCII characters, you must provide a function that converts from your encoding to UTF-8 [...] What encoding does std::string.c_str() use? How can I convert it to UTF-8 or std::wstring in a cross-platform fashion?
std::string per se uses no encoding -- it will return the bytes you put in it. For example, those bytes might be using ISO-8859-1 encoding... or any other, really: the information about the encoding is just not there -- you have to know where the bytes were coming from!
1,010,875
1,010,883
String to Integer Hashing Function with Precision
I want to hash a char array in to an int or a long. The resulting value has to adhere to a given precision value. The function I've been using is given below: int GetHash(const char* zKey, int iPrecision /*= 6*/) { /////FROM : http://courses.cs.vt.edu/~cs2604/spring02/Projects/4/elfhash.cpp unsigned long h = 0; long M = pow(10, iPrecision); while(*zKey) { h = (h << 4) + *zKey++; unsigned long g = h & 0xF0000000L; if (g) h ^= g >> 24; h &= ~g; } return (int) (h % M); } The string to be hashed is similar to "SAEUI1210.00000010_1". However, this produces duplicate values in some cases. Are there any good alternatives which wouldn't duplicate the same hash for different string values.
The very definition of a hash is that it produces duplicate values for some values, due to hash value range being smaller than the space of the hashed data. In theory, a 32-bit hash has enough range to hash all ~6 character strings (A-Z,a-z,0-9 only), without causing a collision. In practice, hashes are not a perfect permutation of the input. Given a 32-bit hash, you can expect to get hash collisions after hashing ~16 bit of random inputs, due to the birthday paradox. Given a static set of data values, it's always possible to construct a hash function designed specifically for them, which will never collide with itself (of course, size of its output will be at least log(|data set|). However, it requires you to know all the possible data values ahead of time. This is called perfect hashing. That being said, here are a few alternatives which should get you started (they are designed to minimize collisions)
1,010,968
1,011,487
see previous definition of 'some symbol'
while programming in c++, Most of the times i get 'some symbol' has already been defined see previous definition of 'some symbol' I think this happens because improper order of headers file included. How can i find out all the definitions of 'some symbol' Thanks in advance, Uday EDIT: I am using visual studio I remember some command some thing like dumpbin /exports (I dont remember exactly) to get all the definition
Translating C++ into an executbale has two steps. In step one, the compiler works linearly through the inputs (typically .cpp files and the headers they include). In step 2, the linker combines the results from step 1. From your description of "symbol defined before", I conclude the problem must occur within a .cpp file, as those are processed linearly. dumpbin /exports works on the output of step 1, which you probably won't have. Header inclusion could be the culprit, as that's an early phase of compilation. You want the preprocessed input. IIRC, you can get that with the /EP switch.
1,011,339
1,112,084
How do you make a HTTP request with C++?
Is there any way to easily make a HTTP request with C++? Specifically, I want to download the contents of a page (an API) and check the contents to see if it contains a 1 or a 0. Is it also possible to download the contents into a string?
I had the same problem. libcurl is really complete. There is a C++ wrapper curlpp that might interest you as you ask for a C++ library. neon is another interesting C library that also support WebDAV. curlpp seems natural if you use C++. There are many examples provided in the source distribution. To get the content of an URL you do something like that (extracted from examples) : // Edit : rewritten for cURLpp 0.7.3 // Note : namespace changed, was cURLpp in 0.7.2 ... #include <curlpp/cURLpp.hpp> #include <curlpp/Options.hpp> // RAII cleanup curlpp::Cleanup myCleanup; // Send request and get a result. // Here I use a shortcut to get it in a string stream ... std::ostringstream os; os << curlpp::options::Url(std::string("http://example.com")); string asAskedInQuestion = os.str(); See the examples directory in curlpp source distribution, there is a lot of more complex cases, as well as a simple complete minimal one using curlpp. my 2 cents ...
1,011,392
1,011,398
< & > are converted to &gt; &lt; etc
I am using MSXMl library to parse xml after I call put_text and then get_xml the output will have < & > converted to &lt; & &gt; How can i get rid of this?
< and > are prohibited to use inside the text and need to be encoded as &gt and &lt. The only way to avoid this is creating a CDATA section for the text containing those. But you really don't need to if you intend to read the XMLT with MS XML - it will decode those symbols just fine and you will get your < and > perfectly fine in the extracted text.
1,011,520
1,011,574
Windows Folder Share API
is there a WIN32 API available to manage folder sharing in Windows? Some links to examples will be helpful. Thanks.
Yes, since Windows 2000 Professional there's a networking API available in netapi32.dll which provides this functionality. Functions like NetShareAdd, NetShareCheck, NetShareDel let you manage the shared files. See http://msdn.microsoft.com/en-us/library/bb525393(VS.85).aspx for more information,
1,011,790
1,011,897
Why does std::string.find(text,std::string:npos) not return npos?
I am doing a series of searches in a string, and somewhere along the line one of the strings will be missed, and my set of searches should fail. I had expected that once the position reached std::string::npos it would stay there, but it does not. Passing std::string::npos to std::string.find seems to start the search at the beginning again std::string str("frederick"); std::string::size_type pos = str.find("der",std::string::npos); TS_ASSERT_EQUALS(pos, std::string::npos); // FAIL, 3 is returned Why is it not being taken to indicate the end of the string? Update: The intention is search for a series of strings in order, and check the result at the end pos = str.find(string1, pos) pos = str.find(string2, pos) pos = str.find(string3, pos) if (pos != std:string::npos) { // All strings found
Looking at the spec, I think that there may be a bug in your implementation. basic_string::find should return the lowest position xpos such that pos <= xpos and xpos + str.size() <= size() and at(xpos + I) == str.at(I) for all elements I controlled by str. basic_string::npos is -1 converted to an unsigned type so must be the largest number representable by that unsigned type. Given that no other position xpos can satisfy even the first part of npos <= xpos and find must return npos on failure, as far as I can see npos is the only valid return value for basic_string::find when passed npos as the second parameter.
1,011,908
1,011,963
Using try/catch in WindowProc MFC
If I use try/catch in WindowProc override of MFC window/view classes there is a performance hit. Why is it so and what is the alternative ? This I caught as a result of profiling. Removing the block makes the function consume much lesser time. I am using MS VS 2008.
In usage-of-try-catch-blocks-in-c Todd Gardner explains that compilers use the "table" approach or the "code" approach to implement exceptions. The "code" approach explains the performance hit.
1,012,305
1,016,508
How do I get total GPRS usage in KBs on a Windows Mobile Device?
Anyone knows how to do this programmatically? I looked at the registry keys but I couldn't find anything. I don't know maybe I missed it. Under the registry key HKLM/Software/Microsoft/shell/cumulativecalltimers/line_0/ there are the values "OutgoingDataPhoneLifeTime" and "OutgoingDataPhoneLifeTimeNumCalls"; but these don't seem to be what I am looking for. They give a value in terms of time.
IFAIK Windows Mobile does not tack this information. You will have to do it yourself if you really want it. I've not done exactly what you want but I know there are only 2 places you could track GPRS information. You either have to use TAPI (which I'm not sure that you could track GPRS information with) or you need to drop down and use the RIL API layer (which is what I beleave the TAPI layer uses).
1,012,571
1,012,604
std::string to float or double
I'm trying to convert std::string to float/double. I tried: std::string num = "0.6"; double temp = (double)atof(num.c_str()); But it always returns zero. Any other ways?
std::string num = "0.6"; double temp = ::atof(num.c_str()); Does it for me, it is a valid C++ syntax to convert a string to a double. You can do it with the stringstream or boost::lexical_cast but those come with a performance penalty. Ahaha you have a Qt project ... QString winOpacity("0.6"); double temp = winOpacity.toDouble(); Extra note: If the input data is a const char*, QByteArray::toDouble will be faster.
1,012,642
1,012,962
How do I set the DPI of a scan using TWAIN in C++
I am using TWAIN in C++ and I am trying to set the DPI manually so that a user is not displayed with the scan dialog but instead the page just scans with set defaults and is stored for them. I need to set the DPI manually but I can not seem to get it to work. I have tried setting the capability using the ICAP_XRESOLUTION and the ICAP_YRESOLUTION. When I look at the image's info though it always shows the same resolution no matter what I set it to using the ICAPs. Is there another way to set the resolution of a scanned in image or is there just an additional step that needs to be done that I can not find in the documentation anywhere? Thanks
I use ICAP_XRESOLUTION and the ICAP_YRESOLUTION to set the scan resolution for a scanner, and it works at least for a number of HP scanners. Code snipset: float x_res = 1200; cap.Cap = ICAP_XRESOLUTION; cap.ConType = TWON_ONEVALUE; cap.hContainer = GlobalAlloc(GHND, sizeof(TW_ONEVALUE)); if(cap.hContainer) { val_p = (pTW_ONEVALUE)GlobalLock(cap.hContainer); val_p->ItemType = TWTY_FIX32; TW_FIX32 fix32_val = FloatToFIX32(x_res); val_p->Item = *((pTW_INT32) &fix32_val); GlobalUnlock(cap.hContainer); ret_code = SetCapability(cap); GlobalFree(cap.hContainer); } TW_FIX32 FloatToFIX32(float i_float) { TW_FIX32 Fix32_value; TW_INT32 value = (TW_INT32) (i_float * 65536.0 + 0.5); Fix32_value.Whole = LOWORD(value >> 16); Fix32_value.Frac = LOWORD(value & 0x0000ffffL); return Fix32_value; } The value should be of type TW_FIX32 which is a floating point format defined by twain (strange but true). I hope it works for you!
1,012,683
1,012,848
std::fstream files more than 2gb
What strategy should I use if I have an implementation of std::fstream with 32-bit std::streampos? If I want to move position I can do it in several steps(10gb - 10 times +1gb). How can I get position? Or should I keep current position in some variable outside fstream? P.S. I can't change the implementation of STL.
Keeping track of the current position yourself is the most straight-forward answer, if you're unable to addle the STL. If your compiler support the long long type, I'd go with that.
1,012,741
1,012,844
Code coverage percentage not good
I have installed on my computer C++Test only with UnitTest license (only Unit Test license) as a Visual Studio 2005 plugin ( cpptest_7.2.11.35_win32_vs2005_plugin.exe ). I have a sample similar to the following: bool MyFunction(... parameters... ) { bool bRet = true; // do something if( some_condition ) { // do something bRet = CallToAFunctionThatCanReturnBothTrueAndFalse.... } else { bRet = false; // do something } if(bRet == false) { // do something } return bRet; } In my case after running the coverage tool I have the following results (for a function similar to the previously mentioned): [LC=100 BC=100 PC=75 DC=100 SCC=100 MCDC=50 (%)] I really don't understand why I don't have 100% coverage when it comes to PathCoverage (PC). Also if someone who has experience with C++Test Parasoft could explain the low MCDC coverage for me that would be great. What should I do to increase coverage? as I'm out of ideas in this case. Directions to (some parts of) the documentation are welcome. Thank you, Iulian
This is a good reference on the various types of code coverage: http://www.bullseye.com/coverage.html. MCDC: To improve MCDC coverage you'll need to look at some_condition. Assuming it's a complex boolean expression, you'll need to look at whether you're exercising the necessary combinations of values. Specifically, each boolean sub-expression needs to be exercised true and false. Path: One of the things mentioned in the link above as being a disadvantage of path coverage is that many paths are impossible to exercise. That may be the case with your example.
1,012,803
1,027,272
Scaling in boost::spirit's assign_a
I am diving into boost::spirit in order to parse a ASCII-based protocoll. I mananged to extract values from the line using rules like this: rule<> Speed = uint_parser<unsigned int,10,3,3>()[assign_a(buffer.speed)]; I also succeed to connect these rules in a meaningful manner. What is missing for a perfect day is the following: The data values are integers that need to be transformed to floating point values using a fixed conversion factor (usually powers of 10). What I do right now is just appying these scalings factors after parsing. However I would really apprechiate to include the scaling factor just inside the rule definition for the field. I imagine something like this: rule<> Speed = uint_parser<unsigned int,10,3,3>()[assign_a(buffer.speed,100)]; Any suggestions? Thanks in advance Arne
One way to do this is to use Boost.Phoenix. Include these headers: #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_object.hpp> // For static_cast_ #include <boost/spirit/include/phoenix_operator.hpp> // For multiplication and then use something like: using namespace boost::phoenix; using namespace boost::phoenix::arg_names; rule<> Speed = uint_parser<unsigned int,10,3,3>()[ ref(buffer.speed) = static_cast_<double>(arg1) * 100 ]; Although, I find phoenix a bit tricky to use and generally just write my own action: struct assign_scaled { double& result; double scale; assign_with_scale(double& r, double scale) : result(r), scale(scale) {} void operator()(unsigned int x) const { result = static_cast<double>(x) * scale; } }; And use it like this: rule<> Speed = uint_parser<unsigned int,10,3,3>()[assign_scaled(buffer.speed, 100)]; This may be more verbose, but I find it easier to maintain.
1,012,849
1,012,911
Using a base-class object to represent its derived-class objects
I need a way for a single variable to represent two kinds of objects derived from the same base class. It's kinda hard to describe but I'll try the best: Say the base class: class Rectangle { float w; float h; const float area() {return w*h;} }; And the two derived classes: class Poker : Rectangle { int style; // Diamond, Club, .... int point; // A~10, J, Q, K }; class BusinessCard : Rectangle { string name; string address; string phone; }; Now is it possible to declare an object, which could be either a poker or a business-card? 'cuz the usage below is illegal: Rectangle* rec; rec = new Poker(); delete rec; rec = new BusinessCard(); Polymorphism might be a way but since it's only good for changing base-class' member attributes, I need this object to be able to represent exactly either of the derived objects. EDIT: Thanks for the all the answers. The public inheritance , the virtual destructor and even the boost::variant typedef are all fantastic hints.
You can do that. The problem is the inheritance modifier for classes is private. Most of the time, private inheritance is not what you want to use. Instead, declare it explicitly as public: class Rectangle { float w; float h; const float area() {return w*h; }; // you missed a semicolon here, btw virtual ~Rectangle() { } // to make `delete` work correctly }; class Poker : public Rectangle // note the public keyword { int style; // Diamond, Club, .... int point; // A~10, J, Q, K }; class BusinessCard : public Rectangle { string name; string address; string phone; }; Then your code snippet should work.
1,013,050
1,013,104
Finite State Machine compiler
What is the best Opensource FSM compiler which can generate c++ code ?
I don't know about the best, but you could look at Ragel: Ragel compiles executable finite state machines from regular languages. Ragel targets C, C++, Objective-C, D, Java and Ruby. Ragel state machines can not only recognize byte sequences as regular expression machines do, but can also execute code at arbitrary points in the recognition of a regular language.
1,013,071
1,013,188
How can I add a description (-> description-column in task manager) to my program (VS 2008, C++)
I have a simple unmanaged c++ project in Visual Studio 2008, and would like to add a description text. Right now I just see the name of the executable in task managers description column (processes tab), but I would like to provide my own text there.
You need to add a VERSIONINFO resource to your project, and set the "FileDescription" property to a string that you want to display. MSDN VERSIONINFO article VS_VERSION_INFO VERSIONINFO FILEVERSION 4,0,0,0 PRODUCTVERSION 4,0,0,0 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x4L FILETYPE 0x1L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904e4" BEGIN VALUE "Comments", "\0" VALUE "CompanyName", "Acme Tea Company\0" VALUE "FileDescription", "Acme Automatic Tea Dispenser\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1252 END END
1,013,131
1,013,205
Generating preprocessed files using bcc32
Does anyone know what the command line option is to generate a preprocessed file using bcc32.exe (version 5.6.4)? I know that using gcc you can use -E to generate .i files.
Do not use bcc32.exe but cpp32.exe. See here for more information on its commandline options or use "cpp32.exe -?".
1,013,245
1,015,125
How can I draw a patternBrush with transparent backround (GDI)?
I can't draw a pattern with a transparent background. This is my snippet : bitmap.CreateBitmap(8, 8, 1, 1, &bits) brush.CreatePatternBrush(&bitmap) hbrush = pCgrCurrentDC->SelectObject(&brush); // set text color TextCol = pCgrCurrentDC->SetTextColor(CgrColourPalRGB); int oldBkgrdMode = pCgrCurrentDC->SetBkMode(TRANSPARENT); //draw polygon pCgrCurrentDC->Polygon(CgrBuffer, n); The doc on msdn doesn't mention anything about transparency. I guess this mode could be used? Or is this a bug ? Thanks!
Mode TRANSPARENT means that background will not be filled before your brush is drawn. But your brush does not contain any transparent pixels in it and it redraws background pixels anyway. Fourth argument in CreateBitmap was set to 1 in your sample. That means bitmap is monochrome. You need to use 32-bit bitmap to use transparency in brushes. GDI supports transparency with some limits. Use GDI+ for full transparency support.
1,013,291
1,013,317
Namespace class and struct
I have a file that looks like this: namespace myName { typedef HRESULT (*PFN_HANDLE)(myName::myStruct); class MyClass{ //... public: BOOL RegisterCallback (PFN_HANDLE foo); //... }; struct myStruct{ //... }; } But I am getting a compile error 'myStruct' is not a member of 'myName'. Can anyone tell me what is going on? It's okay to declare a struct in my header file, right? Is it a namespace issue? I'm sorry to be so dense.
You are trying to use the type name myStruct before you have declared it. Either put the whole struct definition before the typedef, or put this declaration before the typedef: struct myStruct; This is known as a "forward declaration". It tells the compiler that there will later be a type with that name, but doesn't say exactly how that type is defined.
1,013,375
1,013,389
Good online C++ syntax reference?
Do you know of a precise and concise online C++ syntax reference? Please provide the link...
Try http://www.cplusplus.com/reference/ for the library. Try http://www.kuzbass.ru:8086/docs/isocpp/ for the Final Draft International Standard for C++98. Try http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2798.pdf for the Working Draft Standard for C++0X.
1,013,461
1,013,739
Browsing Source Code on an iPhone
I'm the kind of dork who enjoys reading source code in his spare time. I'm also the kind of dork who has an iPhone. What is the best way to read and browse code on such a device? My initial thought is to use something like LXR to generate hyperlinked pages, and upload them to my personal server, but I am interested in better/easier ways. I am primarily reading C and C++ code, but support for other languages would be great. I have no desire to jailbreak my iPhone.
Air Sharing lets you copy over files via WebDav for viewing on your phone. It even syntax colors source code. According to the site, the supperted languages are, "C/C++, Objective C/C++, C#, Java, Javascript, XML, shell scripts, Perl, Ruby, Python, and more".
1,013,658
1,013,709
visual studio - invalid std::string debugger output in Release mode
There's nothing fancy going on in this program, but I get garbage output. Here are the header files I'm including, in case that's relevant. #include <cstdlib> #include <iostream> #include <windows.h> #include <vector> #include <string> #include <sstream> And I'm using Visual Studio 2008 on Windows XP. Note that if I print the string to stdout, it prints "test" perfectly fine.
Sometimes the debugger will have trouble picking up proper values if you've compiled in Release mode. The compiler might swap around operations or move values to registers, etc.
1,013,891
1,013,912
Which is more efficient when initializing a primitive type?
When declaring primitives does it matter if I use the assignment operator or copy constructor? Which one gives the optimal performance, or do most compilers today compile these two statements to the same machine code? int i = 1; int j( 1 );
Same for: int i = 1; int j( 1 ); Not for: Cat d; Cat c1; c1 = d; Cat c2(d);//<-- more efficient
1,013,979
1,013,995
Templated operator<< explicit instantiation and header
Typically for my templated classes, I include declarations in a .hpp file and templated implementation code in a .t.hpp file. I explicitly instantiate the class in a .cpp file: template class MyClass< AnotherClass >; whose object code gets put in a library. The problem is that if I try to print the object with operator<<, which is declared in the .hpp file and defined in the .t.hpp file as: template<class T> std::ostream& operator<<( std::ostream& os, const MyClass<T>& c) { os << "Hello, I am being output."; return os; } I get a linker error saying that the right symbol is undefined. I understand that this is because this templated function is not explicitly instantiated when the class is. Is there a way to get around this other than to include the .t.hpp file any time I want to use operator<< on the class, or to move the templated function code into the .hpp file? Can I explicitly instantiate the function code?
You can explicitly instantiate function templates template std::ostream& operator<<(std::ostream&, const MyClass<int>&); To instantiate a specialization with T = int. The template argument brackets can be omitted if all template arguments can be deduced (like in this case, from the type MyClass<int>. If it can't, for example because the template parameters do not occur in a function parameter type, you have to explicitly specify it template<typename T> void f() { } template void f<int>();
1,014,045
1,014,069
C++ - Why am i getting SIGTRAP during the execution?
While running, my program often stops because of a SIGTRAP. I know, that a SIGTRAP is happening when the compiler finds a breakpoint in the program. But i don't have any breakpoint in my code. (To be sure about it, before the execution, i cleared all the breakpoints..). I'm using Code::Blocks.. Thanks !
Are you running the program from the debugger? It is possible when your binary built with debugging in not up-to-date in regard to source code. Rebuild everything and try again. It happened to me many times.
1,014,101
1,014,114
How to explicitly set taskbar icon?
In Visual Studio I generated a plain old Win32 application and stripped all the resources and generated code so that my application consists of this: #include "stdafx.h" #include "IcoTest.h" int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { ::MessageBox( NULL, L"Testing", L"Test", MB_OK ); } When I run the application, this is what I see: So the question is can I change that default application icon in the taskbar? If so, what code needs to be added to do it? Edit: Here's what I did, and this kind of works but it isn't ideal. The new icon shows up alright, but the taskbar preview window in Vista doesn't work and the system menu doesn't work so I'm just going to leave it alone for now. HWND CreateDummyWindow(HINSTANCE hInstance, int iconId, LPCTSTR taskbarTitle) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = DefWindowProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(iconId)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = 0; wcex.lpszMenuName = 0; wcex.lpszClassName = taskbarTitle, wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(iconId)); ATOM atom = RegisterClassEx(&wcex); HWND wnd = ::CreateWindow( wcex.lpszClassName, taskbarTitle, WS_ICONIC | WS_DISABLED, -1000, -1000, 1, 1, NULL, NULL, hInstance, NULL); return wnd; } int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { HWND wnd = CreateDummyWindow(hInstance, IDI_ICON1, _T("Test") ); ::MessageBox( wnd, _T("Testing"), _T("Test"), MB_OK ); ::DestroyWindow( wnd ); }
The icon shown on the task bar is taken from the window itself. If the only window is the standard Windows MesssageBox, then you'll get some sort of OS default. You have to create your own window and give it an icon, then Windows will use that.
1,014,196
1,014,209
Structured solution without using a jump statement
From Schaums C++ text Removal of goto- says use a flag code segment: const int N2 = 5; int i, j, k; for (i = 0; i < N2; i++) { for (j = 0; j < N2; j++) { for (k = 0; k < N2; k++) if (i + j + k > N2) goto esc; else cout << i + j + k << " "; cout << "* "; } esc: cout << "." << endl; } The solution: const int 5; int i, j, k; bool done = false; for (i = 0; i < N2; i++) { for (j = 0; j < N2 && !done; j++) { for (k = 0; k < N2 && !done; k++) if (i + j + k > N2) done true; else cout << i + j + k << " "; cout << "* "; } cout << "." << endl; done = false; } The output of the structured solution does not produce the same result...as the goto one... I can't see the problem Also, what would be another way to eliminate the goto?- Could I not use a flag and just compliment the condition. Thanks ...
const int 5; int i, j, k; bool done = false; for (i = 0; i < N2; i++) { for (j = 0; j < N2 && !done; j++) { for (k = 0; k < N2 && !done; k++) if (i + j + k > N2) done = true; else cout << i + j + k << " "; if (!done) // <-- Add this line cout << "* "; } cout << "." << endl; done = false; }
1,014,396
1,014,498
Using != with counter controlled loops
Last question for today all...I will get back with tomorrow..I have a lot to follow up on... I am looking in Reilly Java text- talking about counter controlled loop patterns..(does not matter what language..) The author for counter controlled loops (for, while, etc) and with nesting loops...uses the != for test...Now I realize != is used for certain situations with event controlled loops-like sentinel or EOF type of loops- but to me- using it with a counter controlled loop is a bad idea...very prone to errors.. Examples: x = 0; while (x != 100) { y = 0; while (y != 100) { ... y++; } x++; } Would it be better to just say..using the other relational operators... x = 0; while (x < 100) { //or even better some defined constant... y = 0; while (y < 100) { ... y++; } x++; } Which from what I have seen is usually the way presented in texts..classes.etc.. Once again- would all you considered this bad- or just a different way of doing it... Thanks...
as other answers have shown, while(i < 100) is safe*, while(i != 100) is precise**. As an aside, you may want to try while(i++ < 100) or for(i = 0; i < 100; ++i) instead of the simpler while loop you have shown--forgetting to increment the counter at the end of the loop is a real pain. Note that, if i=0, i++ will equal 0, and then increment i for next time, and ++i will increment i and then equal 1, so for while(i++ < 100), the postfix ++ operator is necessary. Also note, that if i was 0 when it got tested in the condition, then it will be 1 in the loop body (for the while example), so if i is an index for an array or something, and not just keeping track of loop iterations, you'd be better to stick with just a for loop (which increments i after each iteration). *: safe here meaning less likely to enter an infinite loop. It is also unsafe in that it can hide potential errors, if the loop isn't trivial **: precise in that if it doesn't do exactly what you expect it to, it will fail, and you will notice. Some other answers have also described how to protect you from errors even more in this kind of loop.
1,014,472
1,014,612
HTTP inputstream class (C++)
I'm currently working on a project that does a lot of HTTP requests for data that it needs. It works by writing all the data into a buffer, then returning that buffer to the caller. It seems that waiting for the entire file to download data that can essentially streamed is a bad idea. Question 1: Is there already a library / public code that can make HTTP and Authenticated HTTP requests that works as a stream? Question 2: If there is no such library, why not? Is there a reason such a thing was never needed?
I'm not aware of an existing library, but it shouldn't be too hard to wrap Curl (or WinInet, if that's your cup of tea) with Boost.Iostreams.
1,014,518
1,014,543
Right way to conditionally initialize a C++ member variable?
I'm sure this is a really simple question. The following code shows what I'm trying to do: class MemberClass { public: MemberClass(int abc){ } }; class MyClass { public: MemberClass m_class; MyClass(int xyz) { if(xyz == 42) m_class = MemberClass(12); else m_class = MemberClass(32); } }; This doesn't compile, because m_class is being created with an empty constructor (which doesn't exist). What is the right way of doing this? My guess is using pointers and instantiating m_class using new, but I'm hoping there is an easier way. Edit: I should have said earlier, but my actual problem has an additional complication: I need to call a method before initializing m_class, in order to set up the environment. So: class MyClass { public: MemberClass m_class; MyClass(int xyz) { do_something(); // this must happen before m_class is created if(xyz == 42) m_class = MemberClass(12); else m_class = MemberClass(32); } }; Is it possible to achieve this with fancy initialization list tricks?
Use the conditional operator. If the expression is larger, use a function class MyClass { public: MemberClass m_class; MyClass(int xyz) : m_class(xyz == 42 ? 12 : 32) { } }; class MyClass { static int classInit(int n) { ... } public: MemberClass m_class; MyClass(int xyz) : m_class(classInit(xyz)) { } }; To call a function before initializing m_class, you can place a struct before that member and leverage RAII class MyClass { static int classInit(int n) { ... } struct EnvironmentInitializer { EnvironmentInitializer() { do_something(); } } env_initializer; public: MemberClass m_class; MyClass(int xyz) : m_class(classInit(xyz)) { } }; This will call do_something() before initializing m_class. Note that you are not allowed to call non-static member functions of MyClass before the constructor initializer list has completed. The function would have to be a member of its base class and the base class' ctor must already be completed for that to work. Also note that the function, of course, is always called, for each separate object created - not only for the first object created. If you want to do that, you could create a static variable within the initializer's constructor: class MyClass { static int classInit(int n) { ... } struct EnvironmentInitializer { EnvironmentInitializer() { static int only_once = (do_something(), 0); } } env_initializer; public: MemberClass m_class; MyClass(int xyz) : m_class(classInit(xyz)) { } }; It's using the comma operator. Note that you can catch any exception thrown by do_something by using a function-try block class MyClass { static int classInit(int n) { ... } struct EnvironmentInitializer { EnvironmentInitializer() { static int only_once = (do_something(), 0); } } env_initializer; public: MemberClass m_class; MyClass(int xyz) try : m_class(classInit(xyz)) { } catch(...) { /* handle exception */ } }; The do_something function will be called again next time, if it threw that exception that caused the MyClass object fail to be created. Hope this helps :)
1,014,538
1,014,818
Static class members in shared library
I have a class like class K { static int a; static int b; } I would like to create a shared library (dll) containing this class K. In a cpp file compliled in the library I call int K::a = 0; int K::b = 0; to instantiate the static variables. The dll does compile without errors, but when I use the library, I get the unresolved external symbol error for the members K::a and K::b. In the main program where I want to use it, I include the same header with the declaration of the class K, the only difference is that for the library I use class __declspec( dllexport ) K { ... } and for the main program class K { ... } Probably I am doing more than one mistake so my questions would be, how can I tell the linker to share the static member class in the library? use the static class members instantiated in the library in the main program? PS. I use Visual Studio 2008...
One should use __declspec( dllimport ) in the header in the main application. So here is the solution. The header file (included in both the library and the main application) is: #ifdef COMPILE_DLL #define DLL_SPEC __declspec( dllexport ) #else #define DLL_SPEC __declspec( dllimport ) #endif class DLL_SPEC K { static int a; static int b; } The cpp file in the library contains: int K::a = 0; int K::b = 0; To compile the library one has to define the macro COMPILE_DLL, for the main application it shouldn't be defined.
1,014,550
1,014,567
mfc copy certain sections of a CString
Let's say I have a CString variable carrying the string "Bob Evans". I want to copy from position 4 until the end of the original CString to a new CString, but I am having trouble finding semantics examples for this: CString original("Bob Evans"); // Below is what I'm trying to do // CString newStr = original.copy(4, original.GetLength()); I have also thought about copying the variable original to a STL C++ string, but achieving this isn't all that easy either in terms of the conversion. What would be your advice regarding this? I could make the string to be stored in a STL string to begin with, but this would be one of the last resort as I didn't want to restructure a lot of code just to store the data in STL string instead of CString. Thanks in advance.
newStr = original.Mid(4);
1,014,584
1,014,820
Force Java to call my C++ destructor (JNI)
I thought this question would have been asked before, but I couldn't find it here... I've used SWIG to create a JNI wrapper around a C++ class. All works great except that Java never seems to call the class's finalize(), so, in turn, my class's destructor never gets called. The class's destructor does some final file I/O, so unfortunately, this isn't just a minor memory leak. Searching through Google, there doesn't seem to be a way to force Java to GC and destroy an object. True? I know I could manipulate my SWIG file and create a java function that would call the C++ destructor, but this class is used by end users in several different platforms/languages, so the addition of a Java-only will create an inconsistency that our tech writers aren't going to like.
You can't force GC with System.gc(). Also it is not guaranteed that there will ever be a GC run for example if your app runs only for a short time and then your finalizer won't run at all (the JVM does not run it when exiting). You should create a close() or destroy() or whatever function for your class and when you finished using an instance of this class call it, preferably from a finally block, like. MyClass x = null; try{ x = new MyClass(); x.work(); } finally { if (x!=null) x.close(); }
1,014,627
1,014,715
error PRJ0019: A tool returned an error code from "Copying DLL..."
Visual studio is giving the error PRJ0019: A tool returned an error code from "Copying DLL...". The console window includes the output: 'CopyDLL.cmd' is not recognized as an internal or external command. Here is some background as to why I don't know about the tool which is copying. Someone left the company a year ago and forgot to check in their latest version of code for a MS Visual Studio 2008 project using C# and C+_. Now we need to fix the program, but can't find the code and I've been assigned with trying to clean the mess up.
You should check the Custom Build Step (Project Properties->Configuration Properties->Custom Build Step) for all of the projects and all of the files. It may be easier to open the *.vcproj files in a text editor and check the tags under individual files in the project. Look for any tags that have a non-empty CommandLine attribute.
1,014,632
1,014,671
Clean up your #include statements?
How do you maintain the #include statements in your C or C++ project? It seems almost inevitable that eventually the set of include statements in a file is either insufficient (but happens to work because of the current state of the project) or includes stuff that is no longer needed. Have you created any tools to spot or rectify problems? Any suggestions? I've been thinking about writing something that compiles each non-header file individually many times, each time removing an #include statement. Continue doing this until a minimal set of includes is achieved. To verify that header files are including everything they need, I would create a source file that all it does is include a header file and try to compile it. If the compile fails, then the header file itself is missing an include. Before I create something though, I thought I should ask here. This seems like a somewhat universal problem.
To verify that header files are including everything they need, I would creating a source file that all it does is include a header file and try to compile it. If the compile fails, then the header file itself is missing an include. You get the same effect by making the following rule: that the first header file which foo.c or foo.cpp must include should be the correspondingly-named foo.h. Doing this ensures that foo.h includes whatever it needs to compile. Furthermore, Lakos' book Large-Scale C++ Software Design (for example) lists many, many techniques for moving implementation details out of a header and into the corresponding CPP file. If you take that to its extreme, using techniques like Cheshire Cat (which hides all implementation details) and Factory (which hides the existence of subclasses) then many headers would be able to stand alone without including other headers, and instead make do with just forward declaration to opaque types instead ... except perhaps for template classes. In the end, each header file might need to include: No header files for types which are data members (instead, data members are defined/hidden in the CPP file using the "cheshire cat" a.k.a. "pimpl" technique) No header files for types which are parameters to or return types from methods (instead, these are predefined types like int; or, if they're user-defined types, then they're references in which case a forward-declared, opaque type declaration like merely class Foo; instead of #include "foo.h" in the header file is sufficient). What you need then is the header file for: The superclass, if this is a subclass Possibly any templated types which are used as method parameters and/or return types: apparently you're supposed to be able to forward-declare template classes too, but some compiler implementations may have a problem with that (though you could also encapsulate any templates e.g. List<X> as implementation details of a user-defined type e.g. ListX). In practice, I might make a "standard.h" which includes all the system files (e.g. STL headers, O/S-specific types and/or any #defines, etc) that are used by any/all header files in the project, and include that as the first header in every application header file (and tell the compiler to treat this "standard.h" as the 'precompiled header file'). //contents of foo.h #ifndef INC_FOO_H //or #pragma once #define INC_FOO_H #include "standard.h" class Foo { public: //methods ... Foo-specific methods here ... private: //data struct Impl; Impl* m_impl; }; #endif//INC_FOO_H //contents of foo.cpp #include "foo.h" #include "bar.h" Foo::Foo() { m_impl = new Impl(); } struct Foo::Impl { Bar m_bar; ... etc ... }; ... etc ...
1,014,860
1,014,895
Stroustrup swan book Vector Problem
I'm using Stroustrup's swan book. I have run into a problem getting output from a vector. I followed the text example from sec. 4.6.3 on page 121. I managed to get the source compiled and am able to execute it. After typing in a list of whitespace separated words, the program hangs and does not list the elements of the vector as it should. I realize not every element will be outputted if it is repeated, but i receive no output at all. I have compiled and run this using the g++ 4.3.2 compiler on Linux and using the Visual C++ express 2008 compiler on windows. Both produce the same result. Thank you for taking time to read this. Here is my source: #include "Supporting_files/std_lib_facilities.h" int main() { vector<string> words; string temp; cout << "Enter a list of words: "; while(cin>>temp) words.push_back(temp); cout << "Number of words: " << words.size() << endl; sort(words.begin(),words.end()); for(int i=0;i<words.size();++i) if(i==0||words[i-1]!=words[i]) cout << words[i] << "\n"; }
while(cin>>temp) only ends when it hits an end of file. Use control-D to send an end of file into the terminal.
1,015,276
1,015,295
C++ Container / Iterator Dependency Problem
I'm working on an container class that looks something like this: class hexFile { public: HANDLE theFile; unsigned __int64 fileLength; hexFile(const std::wstring& fileName) { theFile = CreateFile(fileName.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL); if (theFile == INVALID_HANDLE_VALUE); { throw std::runtime_error(eAsciiMsg("Could not open file!")); } BY_HANDLE_FILE_INFORMATION sizeFinder; GetFileInformationByHandle(theFile, &sizeFinder); fileLength = sizeFinder.nFileSizeHigh; fileLength <<= 32; fileLength += sizeFinder.nFileSizeLow; }; ~hexFile() { CloseHandle(theFile); }; hexIterator begin() { hexIterator theIterator(this, true); return theIterator; }; hexIterator end() { hexIterator theIterator(this, false); return theIterator; }; }; And an iterator class to match that looks like this: class hexIterator : public std::iterator<std::bidirectional_iterator_tag, wchar_t> { hexFile *parent; public: bool highCharacter; __int64 filePosition; hexIterator(hexFile* file, bool begin); hexIterator(const hexIterator& toCopy); ~hexIterator(); hexIterator& operator++() { return ++this; } hexIterator& operator++(hexIterator& toPlus); hexIterator& operator--() { return --this; } hexIterator& operator--(hexIterator& toMinus); hexIterator& operator=(const hexIterator& toCopy); bool operator==(const hexIterator& toCompare) const; bool operator!=(const hexIterator& toCompare) const; wchar_t& operator*(); wchar_t* operator->(); }; My problem is... both classes need to implemented in terms of the other. I'm unsure how to reference the container inside the iterator, for example, because when the iterator is defined, the container hasn't been defined yet. How might one accomplish this? Billy3
Forward declare one before the other. You can use references to a forward declared class in the declaration of another class, so this should work: class hexFile; // forward class hexIterator : ,,, { ... }; class hexFile { ... };
1,015,494
1,016,831
Can I create a software watchdog timer thread in C++ using Boost Signals2 and Threads?
I am running function Foo from somebody else's library in a single-threaded application currently. Most of the time, I make a call to Foo and it's really quick, some times, I make a call to Foo and it takes forever. I am not a patient man, if Foo is going to take forever, I want to stop execution of Foo and not call it with those arguments. What is the best way to call Foo in a controlled manner (my current environment is POSIX/C++) such that I can stop execution after a certain number of seconds. I feel like the right thing to do here is to create a second thread to call Foo, while in my main thread I create a timer function that will eventually signal the second thread if it runs out of time. Is there another, more apt model (and solution)? If not, would Boost's Signals2 library and Threads do the trick?
You can call Foo on a second thread with a timeout. For example: #include <boost/date_time.hpp> #include <boost/thread/thread.hpp> boost::posix_time::time_duration timeout = boost::posix_time::milliseconds(500); boost::thread thrd(&Foo); if (thrd.timed_join(timeout)) { //finished } else { //Not finished; }
1,016,307
1,016,332
List Iterator Remove()
I have a list iterator that goes through a list and removes all the even numbers. I can use the list iterator to print out the numbers fine but I cannot use the list's remove() and pass in the dereferenced iterator. I noticed that when the remove() statement is in effect, *itr gets corrupted? Can somebody explain this? #include <iostream> #include <list> #define MAX 100 using namespace std; int main() { list<int> listA; list<int>::iterator itr; //create list of 0 to 100 for(int i=0; i<=MAX; i++) listA.push_back(i); //remove even numbers for(itr = listA.begin(); itr != listA.end(); ++itr) { if ( *itr % 2 == 0 ) { cout << *itr << endl; listA.remove(*itr); //comment this line out and it will print properly } } }
There are a few issues with your code above. Firstly, the remove will invalidate any iterators that are pointing at the removed elements. You then go on to continue using the iterator. It is difficult to tell which element(s) remove would erase in the general case (although not in yours) since it can remove more than one. Secondly, you are probably using the wrong method. Remove will iterate through all of the items in the list looking for any matching elements - this will be inefficient in your case because there is only one. It looks like you should use the erase method, you probably only want to erase the item at the position of the iterator. The good thing about erase is it returns an iterator which is at the next valid position. The idiomatic way to use it is something like this: //remove even numbers for(itr = listA.begin(); itr != listA.end();) { if ( *itr % 2 == 0 ) { cout << *itr << endl; itr=listA.erase(itr); } else ++itr; } Finally, you could also use remove_if to do the same as you are doing: bool even(int i) { return i % 2 == 0; } listA.remove_if(even);
1,016,463
1,016,554
setting _HAS_ITERATOR_DEBUGGING to 0
How can i set _HAS_ITERATOR_DEBUGGING to 0 I tried setting using #define _HAS_ITERATOR_DEBUGGING 0 at the start of the main.cpp I tried in setting preprocessor definition :( but with no success Thanks in advance Uday
Sorry It was my mistake I had to write this in preprocessor defnition __HAS __ITERATOR __DEBUGGING=0; __SECURE_SCL=0; not __HAS __ITERATOR __DEBUGGING 0; __SECURE _SCL 0;
1,016,496
1,016,502
Why C++ allows arithmetic or enumeration values to be implicitly converted to boolean?
C++ standard says in section 4.12, An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false any other value is converted to true. Which means that the following code is valid, if(5) std::cout << "WOW!"; It is syntactically valid but semantically it doesn't make any sense. My question is why C++ is allowing such strange things? AFAIK, it is not making any advantage rather than making confusion.
I think it's historical, and a by product of how C used to evaluate bool like concepts... C didn't use to have a boolean type, and in the 'down to the metal' paradigm of C, pointers and numeric types, etc. that were set to NULL were also implicitly false. If you think of it as 'nothing/zero == false' and 'anything else == true' it actually does make sense.
1,017,185
1,017,255
Returning struct from a function, how can I check that it is initialized?
I have the following struct in C++: struct routing_entry { unsigned long destSeq; // 32 bits unsigned long nextHop // 32 bits unsigned char hopCount; // 8 bits }; And I have the following function: routing_entry Cnode_router_aodv::consultTable(unsigned int destinationID ) { routing_entry route; if ( routing_table.find(destinationID) != routing_table.end() ) route = routing_table[destinationID]; return route; // will be "empty" if not found } "routing_table" is a stl::map defined as follows: map< unsigned long int, routing_entry > routing_table; My question now is, when using the consultTable function, I want to check that the return value is actually initialized, some how like in Java pseudocode (because I come from the Java camp): Route consultTable(int id) { Route r = table.find(id); return r; } then checking if r == null
There are a few problems here. The most urgent may be what happens when the destination ID is not found. Since you have no constructor on the routing_entry and you are not default initialising, it will have undefined values. // the data inside route is undefined at this point routing_entry route; One way to handle this is to default initialise. This works by instructing the compiler to fill the structure with zeros. This is kind of a trick borrowed from C but it works well here. routing_entry route={0}; You mention you are coming from Java, unlike in Java, structure and class members are not 0 initialised, so you should really handle that somehow. Another way is to define a constructor: struct routing_entry { routing_entry() : destSeq(0) , nextHop(0) , hopCount(0) { } unsigned long destSeq; // 32 bits unsigned long nextHop; // 32 bits unsigned char hopCount; // 8 bits }; Also note that in C++, the size of the integer and char members is not defined in bits. The char type is 1 byte (but a byte is a not defined, but usually 8 bits). The longs are usually 4 bytes these days but can be some other value. Moving on to your consultTable, with the initialisation fixed: routing_entry Cnode_router_aodv::consultTable(unsigned int destinationID ) { routing_entry route={0}; if ( routing_table.find(destinationID) != routing_table.end() ) route = routing_table[destinationID]; return route; // will be "empty" if not found } One way to tell might be to check if the structure is still zeroed out. I prefer to refactor to have the function return bool to indicate success. Additionally, I always typedef STL structures for simplicity, so I'll do that here: typedef map< unsigned long int, routing_entry > RoutingTable; RoutingTable routing_table; Then we pass in a reference to the routing entry to populate. This can be more efficient for the compiler, but probably that is irrelevant here - anyway this is just one method. bool Cnode_router_aodv::consultTable(unsigned int destinationID, routing_entry &entry) { RoutingTable::const_iterator iter=routing_table.find(destinationID); if (iter==routing_table.end()) return false; entry=iter->second; return true; } You would call it like this: routing_entry entry={0}; if (consultTable(id, entry)) { // do something with entry }
1,017,755
1,017,851
C++ static const variable and destruction
I have encountered a strange behavior with a simple C++ class. classA.h class A { public: A(); ~A(); static const std::string CONST_STR; }; classA.cpp #include "classA.h" #include <cassert> const std::string A::CONST_STR("some text"); A::A() { assert(!CONST_STR.empty()); //OK } A::~A() { assert(!CONST_STR.empty()); //fails } main.cpp #include <memory> #include <classA.h> std::auto_ptr<A> g_aStuff; int main() { //do something ... g_aStuff = std::auto_ptr<A>(new A()); //do something ... return 0; } I'd expect access violations or anything similar, but I'd never expect that the content of the static const string could change. Does anyone here have a good explanation what happens in that code? thanks, Norbert
I'd expect access violations or anything similar, but I'd never expect that the content of the static const string could change. Undefined behaviour: it is undefined. If CONST_STR has been destroyed, then you are not guaranteed a hardware exception if you access it. It might crash, but then again its address might end up containing data which looks like an empty string: its destructor might clear pointers or whatever. In this case, you say that the A instance is also stored in a global smart pointer, which is assigned in main(). So the CONST_STR has been constructed when it is accessed in the A constructor, but quite possibly is destroyed before the smart pointer is destroyed. We'd need the whole program to say for sure. [Edit: you've done that. Since CONST_STR and g_aStuff are defined in different compilation units, their relative order of construction is not defined by the standard. I'm guessing that CONST_STR is being destroyed first.]
1,017,814
1,017,833
#error WINDOWS.H already included. MFC apps must not #include <windows.h>
I am getting #error WINDOWS.H already included. MFC apps must not #include windows.h But i dont know how do i find out because of which file this is happening Thanks
Try turning on "Show Includes" in the projects settings (C/C++ -> Advanced). This show give you an indication of what header files are included and in what order - you should be able to trace back from there
1,017,824
1,018,425
C++ CGI and MySQL problem (mysql++)
I'm trying to use c++ in cgi programs and everything is ok if i don't use mysql. Without mysql my site is generated in about 1-2 ms, but if I add only one variable or function from mysql++ library, site is generated in ~35 ms! (with php it's about 15 - 25 ms all time) I suppose it's a problem with dll loading ( there are two, and mysql dll is about 2 MB! ). So, how can I use mysql without such performance decrease? Chris
Maybe you could have a look fastcgi, the aim of fastcgi is to prevent from having to launch the executable for each request, the executable is always running and each request is transmitted through a socket to your cgi. fastcgi provides a library to easily do this in several languages. You then have to configure your web server, for example mod_fastcgi for Apache.
1,017,965
1,017,987
Is there any tool that improves intellisense in vc++ (vs2008)?
Is there any free tool that improves Intellisense and provides code snippet in vc++ 2008? Please don't post commercial tools
No, not that I am aware of. Can you explain what you would like to see improved in the intellisense engine? It's possible some of the behavior you are seeing is a bug that we may be able to help you work around if you can detail what's going on.
1,018,005
1,018,065
Method for making a variable size struct
I need to craft a packet that has a header, a trailer, and a variable length payload field. So far I have been using a vector for the payload so my struct is set up like this: struct a_struct{ hdr a_hdr; vector<unsigned int> a_vector; tr a_tr; }; When I try to access members of the vector I get a seg fault and a sizeof of an entire structs give me 32 (after I've added about 100 elements to the vector. Is this a good approach? What is better? I found this post Variable Sized Struct C++ He was using a char array, and I'm using a vector though.
The solution in the other SO answer is c-specific, and relies on the peculiarities of c arrays - and even in c, sizeof() won't help you find the "true" size of a variable size struct. Essentially, it's cheating, and it's a kind of cheating that isn't necessary in C++. What you are doing is fine. To avoid seg faults, access the vector as you would any other vector in C++: a_struct a; for(int i = 0; i < 100; ++i) a.a_vector.push_back(i); cout << a.a_vector[22] << endl; // Prints 22
1,018,189
1,018,322
Problems implementing the "Observer" pattern
I have met an interesting problem while implementing the Observer pattern with C++ and STL. Consider this classic example: class Observer { public: virtual void notify() = 0; }; class Subject { public: void addObserver( Observer* ); void remObserver( Observer* ); private: void notifyAll(); }; void Subject::notifyAll() { for (all registered observers) { observer->notify(); } } This example can be found in every book on design patterns. Unfortunately, real-life systems are more complex, so here is the first problem: some observers decide to add other observers to the Subject on being notified. This invalidates the "for" loop and all the iterators, that I use. The solution is rather easy - I make a snapshot of the registered observers list and iterate over the snapshot. Adding new observers does not invalidate the snapshot, so everything seems ok. But here comes another problem: observers decide to destroy themselves on being notified. Even worse, one single observer can decide to destroy all other observers (they are controlled from the scripts), and that invalidates both the queue and a snapshot. I find myself iterating over de-allocated pointers. My question is how should I handle the situations, when observers kill each other? Are there any ready-to-use patterns? I always thought that "Observer" is the easiest design pattern in the world, but now it seems it is not that easy to implement it correctly... Thank you, everyone for your interest. Let us have a decisions summary: [1] "Don't do it" Sorry, but it is a must. Observers are controlled from the scripts and are garbage-collected. I cannot control the garbage collection to prevent their de-allocation; [2] "Use boost::signal" The most promising decision, but I cannot introduce boost on the project, such decisions must be made by the project leader only (we are writing under Playstation); [3] "Use shared__ptr" That will prevent observers from de-allocation. Some sub-systems may rely on memory pool cleanup, so I don't think I can use shared_ptr. [4] "Postpone observer deallocation" Queue observers for removal while notifying, then use the second cycle to delete them. Unfortunately, I cannot prevent the deallocation, so I use a trick of wrapping observer with some kind of "adaptor", keeping actually the list of "adaptors". On destructor, observers unassign from their adaptors, then I take my second cycle to destroy empty adaptors. p.s. is it ok, that I edit my question to summarize all the post? I am noob on StackOverflow...
Very interesting issue. Try this: Change remObserver to null out the entry, rather than just removing it (and invalidating the list iterators). Change your notifyAll loop to be: for (all registered observers) { if (observer) observer->notify(); } Add another loop at the end of notifyAll to remove all null entries from your observer list
1,018,389
1,018,554
how to use URLDownloadToFile on a IE8 box (no crash would be nice)?
I'got a C++ app (similar to this one) that downloads files using URLDownloadToFile method (defined in urlmon.dll). Until IE8, it was possible to abort a download by returning E_ABORT in the progress callback. On a system on which IE8 has been installed, doing so crashes the program, with an error report generated. Do anyone know any alternative method to cancel a download launched via URLDownloadToFile ?
Joel Had an issue like this. He gave up on it and cheated (cheating meaning cancelling a transfer caused the transfer to no longer be visible to the user, but still keep going). WinInet had a bug...
1,018,438
1,018,476
Tool for analyzing C++ sources (MSVC)
I need a tool which analyzes C++ sources and says what code isn't used. Size of sources is ~500mb
PC-Lint is good. If it needs to be free/open source your choices dwindle. Cppcheck is free, and will check for unused private functions. I don't think that it looks for things like uninstantiated classes like PC-Lint.
1,018,550
1,018,570
When to make a object delete itself?
Callback* p = new Callback; function(p); If I want to delete the callback object, when and how to delete that? If it gets deleted early, then the callback might fail with segmentation fault.
The best solution for this is to used a smart pointer. You initialize the pointer with the callback and pass it to the function. when the function or whatever process is done, the callback will be deleted automatically by the smart pointer. A good smart pointer implementation is boost::shared_ptr<>
1,018,800
1,019,020
Cost of throwing C++0x exceptions
What are the performance implications of throwing exceptions in C++0x? How much is this compiler dependent? This is not the same as asking what is the cost of entering a try block, even if no exception is thrown. Should we expect to use exceptions more for general logic handling like in Java?
#include <iostream> #include <stdexcept> struct SpaceWaster { SpaceWaster(int l, SpaceWaster *p) : level(l), prev(p) {} // we want the destructor to do something ~SpaceWaster() { prev = 0; } bool checkLevel() { return level == 0; } int level; SpaceWaster *prev; }; void thrower(SpaceWaster *current) { if (current->checkLevel()) throw std::logic_error("some error message goes here\n"); SpaceWaster next(current->level - 1, current); // typical exception-using code doesn't need error return values thrower(&next); return; } int returner(SpaceWaster *current) { if (current->checkLevel()) return -1; SpaceWaster next(current->level - 1, current); // typical exception-free code requires that return values be handled if (returner(&next) == -1) return -1; return 0; } int main() { const int repeats = 1001; int returns = 0; SpaceWaster first(1000, 0); for (int i = 0; i < repeats; ++i) { #ifdef THROW try { thrower(&first); } catch (std::exception &e) { ++returns; } #else returner(&first); ++returns; #endif } #ifdef THROW std::cout << returns << " exceptions\n"; #else std::cout << returns << " returns\n"; #endif } Mickey Mouse benchmarking results: $ make throw -B && time ./throw g++ throw.cpp -o throw 1001 returns real 0m0.547s user 0m0.421s sys 0m0.046s $ make throw CPPFLAGS=-DTHROW -B && time ./throw g++ -DTHROW throw.cpp -o throw 1001 exceptions real 0m2.047s user 0m1.905s sys 0m0.030s So in this case, throwing an exception up 1000 stack levels, rather than returning normally, takes about 1.5ms. That includes entering the try block, which I believe on some systems is free at execution time, on others incurs a cost each time you enter try, and on others only incurs a cost each time you enter the function which contains the try. For a more likely 100 stack levels, I upped the repeats to 10k because everything was 10 times faster. So the exception cost 0.1ms. For 10 000 stack levels, it was 18.7s vs 4.1s, so about 14ms additional cost for the exception. So for this example we're looking at a pretty consistent overhead of 1.5us per level of stack (where each level is destructing one object). Obviously C++0x doesn't specify performance for exceptions (or anything else, other than big-O complexity for algorithms and data structures). I don't think it changes exceptions in a way which will seriously impact many implementations, either positively or negatively.
1,018,830
1,018,856
How to write binary data to a file so that it can be read fast back?
I need to write a file format that writes out data to a file and can read it back. It should be able to read the data back fairly fast, which should involve blitting a large block of data into a std::vector (since their storage is always implemented contiguously). However, when writing the file, I have no idea how to enforce constraints on alignment and size of ints and other types. How should this be done? I'm using gcc on buntu linux on Q6600 (x86). Just as an example: struct Vertex { float point [3]; float normal [3]; float texcoord [2]; } Later on, the data is stored in a std::vector<Vertex>. I have thought about using __attribute__ and packing / aligning it so that it will be more portable across different platforms. edit: I've already made a specification, and I intend to use it. The largest bits of data are the Vertex and Indices, so those will be read as big blocks, and for example (one part of a larger spec): A VertexGroup is a group of vertices who share a characteristic. They can only hold one material at a time, so there should be many of them contained in a mesh. <uint> thisid # Of this VertexGroup <string> name <uint> materialId # A material <uint> vertexCount for (vetexCount): <3xfloat> point <3xfloat> normal <2xfloat> texcoord <uint> triangleCount for (triangleCount): <3xuint> indices
This will depend on your compiler and platform. As far as I know, there is no way to enforce this in a completely cross-compiler and cross-platform manner, without defining lots of macros of your own. However, both VC++ and GCC (the big two) support the #pragma pack directive, which will allow you to define the alignment and packing for your struct. See http://msdn.microsoft.com/en-us/library/2e70t5y1.aspx or http://gcc.gnu.org/onlinedocs/gcc/Structure_002dPacking-Pragmas.html. With that in mind, you can use #pragma pack to define how your structure is aligned, then fread() or similar to simply blit the bytes from the file to memory. You may want to prefix the list with the list length so that you can allocate the memory for the whole list at once, then load the entire file using a single I/O call.
1,018,872
1,018,891
Compiling DX 9.0c app against March09SDK => Cannot run with older DX 9.0c DLLs => Problem :)
I'm unable to do a scenario from subject. I have DirectX 9 March 2009 SDK installed, which is 9, "sub"-version c, but "sub-sub"-version is 41, so libs (d3dx9.lib d3d9.lib) are linking exports to dxd3d_41.dll. What happens when I try to run my app on machine which has DX9.0c but not redistributable from march 2009 is now obvious :), it fails because it cannot find dxd3d_41.dll. Which is standard solution for this problem? How Am I supposed to compile my app to be supported by all machines having DX 9.0c? Is that even achievable? Thanx
You need to install the runtime that matches the SDK you use to compile. The only way to force this to work on ALL machines with DirectX9c installed is to use an old SDK (the first 9.0c SDK). However, I strongly recommend avoiding this. You are much better off just using March 09, and install the March runtimes along with your application installation.
1,019,510
1,022,044
Custom styles for custom widgets in Qt
Does anybody have experience with custom styled, custom widgets in Qt? (I am using Qt 4.5) The problems looks like this: I want to develop some custom controls that are not based entirely on existing drawing primitives and sub-controls. Since the entire application should be skinnable, I want to rely on custom styles, possible on style sheets as well. What I need to configure for those new controls are the following: additional metrics additional palette entries additional style options Digging on internet and documentation, I found out that I need to derive a new style class from one the QStyle sub-classes, and override polish method for adding new palette entries, and drawControl (and the other draw methods) for painting logic for custom control and custom parts. I have two issues that bother me: Currently, there are different style classes for different styles, already implemented in Qt. (e.g. QMotifStyle, QWindowsStyle), each with different settings. Through inheritance, I would need to re-implement the painting and additional setup logic for each style, in order to properly integrate in all these styles. Do I have another alternative? I am still confused about how can style sheets be used with these custom styles. Can anybody point to a place where I can find more information than the one provided by Qt documentation? (The samples in Qt don't help me too much).
The style sheet problem will not be solved, as it will not on custom classes. The extra goodies added to a custom style will not be understood and taken care by already existing classes. This is because C++ is a static language and there is no (clean and sane) way to monkey-patch the run-time classes. A potential solution is to use a proxy style which wraps a certain instance of standard QStyle subclasses. Depending on how much you want to achieve with it, you can refer to two articles: Cross-platform code and styles and Look 'n' Feel Q & A. If I were you, I would not go with the QStyle approach. Afterall, you create custom widgets (e.g. FooSomething) so you can as well add create completely different custom styles (e.g. FooStyle), it does not even need to mimic QStyle. Of course then you still need to replicate similar functionalities, e.g. to support style sheet.
1,020,443
1,020,450
making numerous pointers NULL at the same time
This is a C++ class that I have made with n number of pointers. class SomeClass { private: int* ptr1; int* ptr2; ... int* ptrn; private: // constructors, destructors, and methods }; During the initialization stage, I want to make all those pointers point to NULL (or make pointers point to NULL by default when they are declared) rather than doing so: void SomeClass::MakePtrNull() { ptr1 = NULL; ptr2 = NULL; ... ptrn = NULL; } Is there any easy method of accomplishing this goal? I'm just wondering if there are any ways of avoiding typing n lines of ptr = NULL; in my function. Thanks in advance. ADDED based on the answers that I have received so far: Unfortunately, those pointers have to be separate, as they are used for different purposes. I made the names of the pointers as such just to make a point of what I'm trying to do, but each pointer has a completely different purpose. I guess I would have to make them point to NULL as I have done already. Thanks for your answers.
Why don't you use an array or a vector rather than creating n individually named pointers? Then you can do the nulling in a short for loop.
1,020,820
1,020,886
Comparing structures in C vs C++
I want to compare C++ class/structure objects. In C, most of the time, one knows exact size of the struct by adding up the sizes of individual fields (assuming that compiler does not add padding). Hence one can use memcmp() function on two object to compare them very fast. I am not sure if the same works for C++. This is because a class also has function definitions and maybe some other hidden things (some RTTI info perhaps? A virtual function table even?) A quick program with a simple structure containing int and char members and a function showed that size of the structure was sizeof(int)+sizeof(char). I have a one big struct class with simple int, char etc data types (but a large number of them). I want to compare objects from time to time. I cannot overload the == operator as that will make them compare each field by field. In C, I can compare in one go using memcmp(). Any suggestions for C++? Can I use memcmp() directly? I dont want memcmp() to fail because some other value like virtual function pointer table is different (but all the fields are actually equal) (I'm using g++)
Be wary on numerous counts... The values in any padding is indeterminate and hence not comparable. If your machine is little-endian, comparing integer fields will produce one answer; if your machine is big-endian, it will produce another answer. Most people regard -1 as smaller than 0, but memcmp() will do byte-wise unsigned comparison, and will therefore treat -1 as bigger than 0. Any pointers are inherently not comparable relevantly by memcmp(). You cannot compare float or double using memcmp(). On the whole, you are seeking a non-sensible optimization.
1,020,924
1,020,932
Build errors w/ GLee (GL Easy Extension Library)
Using Code::Blocks w/ mingw, and trying to use GLee for some OpenGL on windows. I'm getting the following build errors: GLee.c|60|undefined reference to `_wglGetProcAddress@4' GLee.c|10748|undefined reference to `_wglGetProcAddress@4' GLee.c|10751|undefined reference to `_wglGetCurrentDC@0' GLee.c|10797|undefined reference to `_glGetString@4' GLee.c|10910|undefined reference to `_glGetString@4' GLee.c|10976|undefined reference to `_glGetString@4' And I'm just including GLee likes so (with GLee.c, not the .dll): #include "GLee.h" According to Ben Woodhouse, GLee is "written in pure ANSI C, so any C or C++ compiler should work. You can include the source files in your projects directly or compile them into a library", so I should be having no problems. Google didn't give me much on this, so I'm hoping some OpenGL vets (or anyone familiar with GLee) out there can point me in the right direction.
It looks like you need to link your application against the OpenGL libraries (specifically Opengl32.lib) which will provide the functions that you are missing. Perhaps the OpenGL FAQ might be of help in figuring this out.
1,020,964
1,021,114
calling managed c# component from unmanaged c++ code, how do i define config
I want to call a C# component from an unmanaged c++ service. I need to set config items expected by the C# component. What name should be config be and where should it be located. eg. parentfolder\cplusplusservice.exe anotherfolder\csharp.dll i need csharp.dll.config or its equivalent. Thanks,
The .config file needs to be named the same as the application's name. When the unmanaged code first calls into the managed code an AppDomain is created that AppDomain controls which config file is loaded and from where. You will need to manually copy the .config file to the output directory and name it after the application name or create a post-build to do so. Basically the same rules that apply to where .config files need to be for pure managed apps apply to unmanaged apps that load managed code.
1,021,138
1,021,269
Differences between dynamic memory and "ordinary" memory
What are some of the technical differences between memory that is allocated with the new operator and memory that is allocated via a simple variable declaration, such as int var? Does c++ have any form of automatic memory management? In particular, I have a couple questions. First, since with dynamic memory you have to declare a pointer to store the address of the actual memory you work with, doesn't dynamic memory use more memory? I don't see why the pointer is necessary at all unless you're declaring an array. Secondly, if I were to make a simple function such as this: int myfunc() { int x = 2; int y = 3; return x+y; } ...And call it, would the memory allocated by the function be freed as soon as it's scope of existence has ended? What about with dynamic memory?
Note: This answer is way too long. I'll pare it down sometime. Meanwhile, comment if you can think of useful edits. To answer your questions, we first need to define two areas of memory called the stack and the heap. The stack Imagine the stack as a stack of boxes. Each box represents the execution of a function. At the beginning, when main is called, there is one box sitting on the floor. Any local variables you define are in that box. A simple example int main(int argc, char * argv[]) { int a = 3; int b = 4; return a + b; } In this case, you have one box on the floor with the variables argc (an integer), argv (a pointer to a char array), a (an integer), and b (an integer). More than one box int main(int argc, char * argv[]) { int a = 3; int b = 4; return do_stuff(a, b); } int do_stuff(int a, int b) { int c = a + b; c++; return c; } Now, you have a box on the floor (for main) with argc, argv, a, and b. On top of that box, you have another box (for do_stuff) with a, b, and c. This example illustrates two interesting effects. As you probably know, a and b were passed-by-value. That's why there is a copy of those variables in the box for do_stuff. Notice that you don't have to free or delete or anything for these variables. When your function returns, the box for that function is destroyed. Box overflow int main(int argc, char * argv[]) { int a = 3; int b = 4; return do_stuff(a, b); } int do_stuff(int a, int b) { return do_stuff(a, b); } Here, you have a box on the floor (for main, as before). Then, you have a box (for do_stuff) with a and b. Then, you have another box (for do_stuff calling itself), again with a and b. And then another. And soon, you have a stack overflow. Summary of the stack Think of the stack as a stack of boxes. Each box represents a function executing, and that box contains the local variables defined in that function. When the function returns, that box is destroyed. More technical stuff Each "box" is officially called a stack frame. Ever notice how your variables have "random" default values? When an old stack frame is "destroyed", it just stops being relevant. It doesn't get zeroed out or anything like that. The next time a stack frame uses that section of memory, you see bits of old stack frame in your local variables. The heap This is where dynamic memory allocation comes into play. Imagine the heap as an endless green meadow of memory. When you call malloc or new, a block of memory is allocated in the heap. You are given a pointer to access this block of memory. int main(int argc, char * argv[]) { int * a = new int; return *a; } Here, a new integer's worth of memory is allocated on the heap. You get a pointer named a that points to that memory. a is a local variable, and so it is in main's "box" Rationale for dynamic memory allocation Sure, using dynamically allocated memory seems to waste a few bytes here and there for pointers. However, there are things that you just can't (easily) do without dynamic memory allocation. Returning an array int main(int argc, char * argv[]) { int * intarray = create_array(); return intarray[0]; } int * create_array() { int intarray[5]; intarray[0] = 0; return intarray; } What happens here? You "return an array" in create_array. In actuality, you return a pointer, which just points to the part of the create_array "box" that contains the array. What happens when create_array returns? Its box is destroyed, and you can expect your array to become corrupt at any moment. Instead, use dynamically allocated memory. int main(int argc, char * argv[]) { int * intarray = create_array(); int return_value = intarray[0]; delete[] intarray; return return_value; } int * create_array() { int * intarray = new int[5]; intarray[0] = 0; return intarray; } Because function returning does not modify the heap, your precious intarray escapes unscathed. Remember to delete[] it after you're done though.
1,021,210
1,021,220
Programming slim C++ programs (like uTorrent) for Windows
I've always admired the original uTorrent program. It looked great, was less than 64kb, was extremely fast and had all the features I needed. Unfortunately the program is closed source (and becoming more bloated by the day) so I come to Stackoverflow for inspiration. What methods do you recommend in writing fast, memory efficient and elegant programs on Windows? While C# (and the whole .NET concept) are cool ideas I am more interested in 'purist' answers and the challenge of writing efficient, fast software for the Windows platform, much like the original uTorrent client. I don't mind allocating my own memory, doing my own garbage collection and creating my own data structures. Recommendations on books, articles, libraries, IDEs (even efficient ways of getting more caffeine into my system) welcome.
The Windows Template Library is geared towards what you want to do. It's a light-weight, template-based C++ wrapper for the Win32 API. With it, you don't have to go through the pain of direct Win32 coding, but it doesn't add a lot of overhead like MFC.
1,021,331
1,021,340
How to tell std::set to 'refresh' its ordering?
If the value of an element in a set changes the ordering may be no longer correct. As illustrated in this little program: #include <algorithm> #include <iostream> #include <set> #include <string> struct Comp { bool operator()(const std::string * lhs, const std::string * rhs) { return *lhs < *rhs; } }; int main() { typedef std::set<std::string*, Comp> MySet; MySet mySet; std::string * a = new std::string("a"); mySet.insert(a); std::string * c = new std::string("c"); mySet.insert(c); std::string * b = new std::string("b"); mySet.insert(b); for (MySet::iterator it = mySet.begin(); it != mySet.end(); ++it) { std::cout << *(*it) << std::endl; } // Ouput has correct order: // a // b // c *b = "z"; std::cout << std::endl; std::string * d = new std::string("d"); mySet.insert(d); for (MySet::iterator it = mySet.begin(); it != mySet.end(); ++it) { std::cout << *(*it) << std::endl; } // Output no longer ordered correctly: // a // d // z // c return 0; } How can I tell the set to 'refresh' its internal sorting?
Very similar subject here (though not quite a duplicate, because you're storing pointers to mutable objects with a custom comparison): what happens when you modify an element of an std::set? Basically, don't do what you're trying to do. Instead, when you want to modify an object that a set holds a pointer to, remove the pointer first, then modify the object, then re-insert the pointer.
1,021,357
1,021,385
Wrapping #includes in #ifndef's - adds any value?
I have inherited C/C++ code base, and in a number of .cpp files the #include directives are wrapped in #ifndef's with the headers internal single include #define. for example #ifndef _INC_WINDOWS #include <windows.h> #endif and windows.h looks like #ifndef _INC_WINDOWS #define _INC_WINDOWS ...header file stuff.... #endif // _INC_WINDOWS I assume this was done to speed up the compile/preprocess of the code. I think it's ugly and a premature optimisation, but as the project has a 5 minute build time from clean, I don't want to makes things worse. So does the practice add any value or speed things up lots? Is it OK to clean them up? Update: compiler is MSVC (VS2005) and platform is Win32/WinCE
It's worth knowing that some implementations have #pragma once and/or a header-include-guard detection optimisation, and that in both cases the preprocessor will automatically skip opening, reading, or processing a header file which it has included before. So on those compilers, including MSVC and GCC, this "optimisation" is pointless, and it should be the header files responsibility to handle multiple inclusion. However, it's possible that this is an optimisation for compilers where #include is very inefficient. Is the code pathologically portable, and <windows.h> refers not to the well-known Win32 header file, but to some user-defined header file of the same name? It's also possible that the header files don't have multiple-include guards, and that this check is actually essential. In which case I'd suggest changing the headers. The whole point of headers is as a substitute for copy-and-pasting code about the place: it shouldn't take three lines to include a header. Edit: Since you say you only care about MSVC, I would either: do a mass edit, time the build just to make sure the previous programmer doesn't know something I don't. Maybe add #pragma once if it helps. Use precompiled headers if all this really is slowing things down. Ignore it, but don't use the guards for new files or for new #includes added to old files. Depending on whether I had more important things to worry about. This is a classic Friday-afternoon job, I wouldn't spend potentially-productive time on it ;-)
1,021,521
1,021,541
How does STL algorithm work independent of Iterator type?
How does STL algorithm work independent of Iterator type?
Really, they just work. They use some pretty basic properties of templates, sometimes called static polymorphism. If you're familiar with the term, it is essentially a form of ducktyping. (If it looks like a duck, and it quacks like a duck, it must be a duck) The trick is simple. Here's a very simple example: template <typename T> void say_hello(const T& t) { t.hello(); } The say_hello function doesn't care which type its argument is. It doesn't have to derive from an interface or make any other kind of "promises" about what it is. All that matters is that the type works in this context. All we do with the type is call its hello function. Which means that this code will compile for any type that has a hello member function. The STL algorithms work similarly. Here's a simple implementation of std::for_each: template <typename iter_type, typename func_type> void for_each(iter_type first, iter_type last, func_type f){ for (iter_type cur = first; cur != last; ++cur) { f(*cur); } } This code will compile whenever the template types live up to the requirements placed on them; iter_type must have the pre-increment ++-operator. It must have a copy constructor, and it must have the != operator, and it must have the *-dereference-operator. func_type must implement the function-call operator, taking an argument of the same type as you get by dereferencing an object of type iter_type. If I call for_each with types that satisfy these requirements, the code will compile. iter_type can be any type that satisifies these requirements. There is nothing in the code that says "this shall work with vector iterators and list iterators and map iterators". But as long as vector, list or map iterators implement the operators we use, it'll work.
1,021,626
1,021,639
C++: Could Polymorphic Copy Constructors work?
Consider: class A { public: A( int val ) : m_ValA( val ) {} A( const A& rhs ) {} int m_ValA; }; class B : public A { public: B( int val4A, int val4B ) : A( val4A ), m_ValB( val4B ) {} B( const B& rhs ) : A( rhs ), m_ValB( rhs.m_ValB ) {} int m_ValB; }; int main() { A* b1 = new B( 1, 2 ); A* b2 = new A( *b1 ); // ERROR...but what if it could work? return 0; } Would C++ be broken if "new A( b1 )" was able to resolve to creating a new B copy and returning an A? Would this even be useful?
Do you need this functionality, or is this just a thought experiment? If you need to do this, the common idiom is to have a Clone method: class A { public: A( int val ) : m_ValA( val ) {} A( const A& rhs ) {} virtual A *Clone () = 0; int m_ValA; }; class B : public A { public: B( int val4A, int val4B ) : A( val4A ), m_ValB( val4B ) {} B( const B& rhs ) : A( rhs ), m_ValB( rhs.m_ValB ) {} A *Clone() { return new B(*this); } int m_ValB; }; int main() { A* b1 = new B( 1, 2 ); A* b2 = b1->Clone(); return 0; }
1,021,793
1,021,809
How do I forward declare an inner class?
I have a class like so... class Container { public: class Iterator { ... }; ... }; Elsewhere, I want to pass a Container::Iterator by reference, but I don't want to include the header file. If I try to forward declare the class, I get compile errors. class Container::Iterator; class Foo { void Read(Container::Iterator& it); }; Compiling the above code gives... test.h:3: error: ‘Iterator’ in class ‘Container’ does not name a type test.h:5: error: variable or field ‘Foo’ declared void test.h:5: error: incomplete type ‘Container’ used in nested name specifier test.h:5: error: ‘it’ was not declared in this scope How can I forward declare this class so I don't have to include the header file that declares the Iterator class?
This is simply not possible. You cannot forward declare a nested structure outside the container. You can only forward declare it within the container. You'll need to do one of the following Make the class non-nested Change your declaration order so that the nested class is fully defined first Create a common base class that can be both used in the function and implemented by the nested class.
1,021,875
1,021,931
How to generate C++ Dynamic Objects names?
I'd like to generate a number of objects (in C++) based on the amount/number the user enters. Now I've somewhere heard that it has to be done using pointer tricks, creating a pointer to an array of the Object type required, and then dynamically increasing the size of array ( at runtime ). Isn't there a workaround of directly using names like Object1, Object2..... ObjectX instead of having Classname *Object[] and then using the array index to get the object ? In either case, it'd be great if someone could clarify on the issue. Thanks !
So far no-one has explained why your thinking is flawed. C++ is a compiled language, and it goes to great lengths to turn the source program into efficient machine code. For this reason, the names you give variables are available to the program only at compile time, when you turn it from source into an executable file. Afterwards, when you want to create objects dynamically, those kinds of information are no longer available. The program only knows about the machine addresses where operands to machine instructions are located.
1,021,962
1,021,993
How to test a C++ library usability in configure.in?
I'm working on a C++ project on GNU/Linux and I'm looking for a way to test the existence and usability of IBM Informix's library with the Autotools - namely, editing a configure.in. I don't have experience with Autotools, so basically I'm picking up from the project's configure.in et al. scripts and copying&changing where I feel needs to be changed. IOW, I've been adapting from the existing text in configure.in. So far I've been using successfully the AC_CHECK_LIB in configure.in to test whether a certain library both exists and is usable. But this only seems to work with libraries with functions, not e.g. classes. Namely, this fails when testing Informix's libifc++.so library: AC_CHECK_LIB(ifc++, ITString, INFORMIX_LIB="-L$INFORMIX_LIB_LOCATION/c++ -lifc++ -L$INFORMIX_LIB_LOCATION -L$INFORMIX_LIB_LOCATION/dmi -L$INFORMIX_LIB_LOCATION/esql -lifdmi -lifsql -lifasf -lifgen -lifos -lifgls -lifglx $INFORMIX_LIB_LOCATION/esql/checkapi.o -lm -ldl -lcrypt -lnsl", echo "* WARNING: libifc++.so not found!" INFORMIX_INC="" INFORMIX_LIB="" ) I've also tried using other combinations, like ITString::ITString, etc. I haven't found a "pure" function in Informix's API (i.e., one that isn't contexted in a C++ class). So I'm hoping that either there's a way to use AC_CHECK_LIB in this context, or there's another autoconf/configure.in "command" for this specific use. Thanks in advance for your feedback.
There might be a cleaner way of achieving this, but I think your problem is that C++ methods get "mangled" to allow additional information about the method (argument & return types etc) to be encoded. For example; the method int A::foo(void) will get mangled to something like __ZN1A3fooEv. So you need to find the mangled name of a method in the library. You can do this by using the nm command on Unix-like OSs: $ nm libifc++.so | grep ITString It's worth mentioning that the exact mangling format varies across different compilers; and so by embedding a certain compiler's mangled symbol in your configure.in it may not work on other platforms - YMMV. Note: you can use the c++filt utility to demangle a name back to it's human-readable form; so for the example I gave previously: $ c++filt __ZN1A3fooEv A::foo() See Name Mangling in C++ on Wikipedia for more information.
1,022,072
1,022,088
Win32 Console app vs. CLR Console app
I'm working on a C++ project that I don't intend to develop or deploy using .NET libraries or tools, which means it would make sense for me to create it using a Visual Studio Win32 Console application. However, I've heard that the debugging abilities when using a CLR application under Visual Studio are much more powerful. So I have a few questions: Is it true that having a CLR app vs. a Win32 app adds capabilities to your development process even if you don't utilize any .NET libraries or other resources? If so, would I still be able to develop/compile the project as a CLR project to take advantage of these even though I'd be developing a pure C++ project using STL, etc. and not taking advantage of any .NET functionality? Or would such a project require fundamental differences that would make it non-trivial to revert back, meaning I should stick with a Win32 console app?
Bottom line answer, if you are never intending to use the CLR or any .Net objects in your application, just use a normal Win32 C++ library. Doing anything else will cause you pain down the road. Now, to answer the original question about debugging, yes debugging with the CLR has certain advantages over debugging a normal C++ app. Starting with Visual Studio 2005, both C# and VB.Net began to focus on making the variable display in the locals / autos /watch window much more valuable. It was mainly done through the introduction of .Net attributes such as DebuggerDisplay, DebuggerTypeProxy and the visualizer framework. If you don't use any .Net types though, you will get none of these benefits. The C++ expression evaluator does not take advantage of any of these. It has it's own methods of customizing type display. But it's not as featureful (or potentially dangerous) as the attribute style because it doesn't allow for code to run in the debugee process. That's not to say debugging C++ provides a poor experience. It is merely different and there are better displays for many STL container types. Debugging a CLR app also has certain disadvantegs. For instance, debugging optimized code is near impossible at times because the JITer will hide local variables, parameters and often "this". Debugging a similarly constructed C++ app can also be frustrating but you can always grab the registers and dissamebly to see what's going on. Doing the same for a CLR app is difficult at best.
1,022,449
1,022,464
How to change an executable's properties? (Windows)
When I create a .exe, I can right click it and go to properties->details. Then I get a list like: File Description | Type | Application File Version | Product Name | Product Version | Copyright | Size | 18.0 KB Date Modified | 6/16/2009 8:23 PM Language | How do I change these properties? (And on a side note, is there a way to change the icon?)
If you are using C/Win32 you can add something like this to your project encapsulated in a *.rc (resource) file: VS_VERSION_INFO VERSIONINFO FILEVERSION 0,0,0,2 PRODUCTVERSION 0,0,0,2 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L #else FILEFLAGS 0x0L #endif FILEOS 0x4L FILETYPE 0x1L FILESUBTYPE 0x0L { BLOCK "StringFileInfo" { BLOCK "040904b0" { VALUE "Comments", "comment\0" VALUE "CompanyName", "comment\0" VALUE "FileDescription", "base file\0" VALUE "FileVersion", "0.0.0.2 TP\0" VALUE "InternalName", "testTP\0" VALUE "LegalCopyright", "none\0" VALUE "OriginalFilename", "test.exe\0" VALUE "ProductName", "test\0" VALUE "ProductVersion", "0.0.0.2 TP\0" } } BLOCK "VarFileInfo" { VALUE "Translation", 0x409, 1200 } }
1,022,487
1,022,500
How to create a temporary text file in C++?
I'm trying to create a temporary text file in C++ and then delete it at the end of the program. I haven't had much luck with Google. Could you tell me which functions to use? The answers below tell me how to create a temp file. What if I just want to create a file (tmp.txt) and then delete it? How would I do that?
Maybe this will help FILE * tmpfile ( void ); http://www.cplusplus.com/reference/clibrary/cstdio/tmpfile/ Open a temporary file Creates a temporary binary file, open for update (wb+ mode -- see fopen for details). The filename is guaranteed to be different from any other existing file. The temporary file created is automatically deleted when the stream is closed (fclose) or when the program terminates normally. See also char * tmpnam ( char * str ); Generate temporary filename A string containing a filename different from any existing file is generated. This string can be used to create a temporary file without overwriting any other existing file. http://www.cplusplus.com/reference/clibrary/cstdio/tmpnam/
1,022,623
1,022,676
C++ Shared Library with Templates: Undefined symbols error
I'm trying to link to a shared library with a template class, but it is giving me "undefined symbols" errors. I've condensed the problem to about 20 lines of code. shared.h template <class Type> class myclass { Type x; public: myclass() { x=0; } void setx(Type y); Type getx(); }; shared.cpp #include "shared.h" template <class Type> void myclass<Type>::setx(Type y) { x = y; } template <class Type> Type myclass<Type>::getx() { return x; } main.cpp #include <iostream> #include "shared.h" using namespace std; int main(int argc, char *argv[]) { myclass<int> m; cout << m.getx() << endl; m.setx(10); cout << m.getx() << endl; return 0; } This is how I compile the library: g++ -fPIC -c shared.cpp -o shared.o g++ -dynamiclib -Wl,-dylib_install_name -Wl,libshared.dylib -o libshared.dylib shared.o And the main program: g++ -c main.cpp g++ -o main main.o -L. -lshared Only to get the following errors: Undefined symbols: "myclass<int>::getx()", referenced from: _main in main.o _main in main.o "myclass<int>::setx(int)", referenced from: _main in main.o If I remove the 'template' stuff in shared.h/cpp, and replace them with just 'int', everything works fine. Also, if I just copy&paste the template class code right into main.cpp, and don't link to the shared library, everything works as well. How can I get a template class like this to work through a shared library? I'm using MacOS 10.5 with GCC 4.0.1.
In addition to the other answers, you can explicitly instantiate template classes. This is only useful if you know beforehand what types the template parameters may assume. You instantiate the template with all these types in the library. For your example to compile, just add the following to the end of shared.cpp: // Instantiate myclass for the supported template type parameters template class myclass<int>; template class myclass<long>; This instantiates the template with Type=int and places the instantiated code in the shared library. Add as many explicit instantiations as you need, for all the types you need. Again, if you want to be able to instantiate the template with any arbitrary Type parameter, then you must add the definitions to the header file, so that the compiler knows the source code of the template when instantiating it in other compilation units.
1,022,971
1,023,110
What classes of applications or problems do you prefer Python to strictly OO Languages?
I've got a pretty strong background in C-style languages. And have worked on several different types of projects. I have just started taking a serious look at Python after reading Programming Collective Intelligence. I understand that Python can solve any problem that C# can, and vice-versa. But I am curious to know from those who use both regularly, when they choose one over the other. Removing other factors, like coworkers experience, etc. When do you choose to create an application in Python instead of a static typed, purely OO language like C# or Java? Edit: I was afraid we were going to get off topic a bit with this question. Python is an object oriented language. But, as is stated below it may not be the preferred language when your application will have a very heavy business domain, etc. I am aware that Python uses objects extensively, and that even functions are objects, something that is not true in all of the "OO" languages I brought up earlier. Despite my poor choice of words in the question (almost no languages fit nicely into two or three word descriptions, and it is really difficult to point out differences in languages without it appearing that you are talking down to a certain class of developer.), I am still very interested in what you have to say about when you prefer Python to other languages.
My motto is (and has long been) "Python where I can, C++ where I must" (one day I'll find opportunity to actually use Java, C#, &c &C, in a real-world project, but I haven't yet, except for a pilot project in Java 1.1, more tha ten years ago...;-) -- Javascript (with dojo) when code has to run in the client's browser, and SQL when it has to run in the DB server, of course, but C++ and Python are my daily bread on the "normal" servers and clients I develop, and that's the case in all parts of Google I've been working in in 4+ years (there are many parts using Java, too, I just never happened to work there;-). Hmmm, there's pure C when I'm working on the Python core and related extensions, too, of course;-). Neither Python nor C++ are "strictly OO" -- they're multi-paradigm, and therein lies a good part of their strength in the hands of programmers who are highly skilled at OO and other paradigms, such as functional, generic, declarative, and so forth. I gather C# has pulled in some of each of these too (sometimes surpassing C++, e.g. by offering lambdas), and even Java has had to succumb to some (at least generic) to a tiny extent, so surely it's clear that "one size fits all" doesn't -- multi-paradigm programming is alive and well!-) C++ (like C) forces me to control all memory carefully (our internal c++ style guide forbids the use of "smart pointers" that amount to poor implementations of garbage collection!-), which multiplies my work a lot, but helps ensure I'm not using one bit of memory more than strictly needed at any time: so, C++ (or C when needed) is the choice when memory is tight and precious. Otherwise, the extremely high productivity of Python (and Ruby or Javascript aren't all that different, if that's what you are used to) makes it preferable. I'm sure there IS a niche in-between for a language that's garbage collected but mostly static, like Java (or C# before it started piling on more and more features, including dynamic ones in 4.0, I hear), or else those languages and cognate ones wouldn't be so widespread -- I've just never found myself inhabiting that peculiar niche, as yet.
1,023,236
1,023,251
stringstream bug in VC9? "Cannot access private member"
std::string str; std::stringstream strm(str); I get this error: Error 11 error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' : cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>' c:\program files\microsoft visual studio 9.0\vc\include\sstream 517 If I use istringstream, same happens. Compiler: Visual C++ 2008.
Sounds like you are trying to copy a stream. This is not possible as the copy constructors are private.
1,023,368
1,023,380
How to add prebuilt library to a VC++ solution?
It's pretty easy to use a library in VC++ 2008 if you create a project for it and build it alongside the other projects in your solution, but what if the library has too complex of a build process and must be compiled separately via makefile? My library is like that, and while I've had no problem compiling it on the command line, I have no clue what to do with the resulting header files and .lib file. I've put them all in one directory and added its path to my main project's Additional Include Directories, so it finds the header files just fine. I've also added the relevant info to Additional Library Directories and Additional Dependencies. Perhaps there's another setting I'm forgetting to set besides these three? I'd appreciate all the help I can get. Thanks. EDIT Here are the syntax errors I'm getting: http://pastebin.com/m72ece684
Okay, based on those errors, it has nothing to do with finding your .lib files, it's choking on the header files. Edit: It looks like somewhere in windows.h, there is a macro definition for X942_DH_PARAMETERS which is breaking your dl_group.h. Instead of putting your botan headers at top, but windows.h at top, and then right before you #include the botan headers add this line: #undef X942_DH_PARAMETERS Or as I just discovered, that macro is defined in wincrypt.h, and if you add NOCRYPT to your preprocessor definitions it won't include that file. Since you're using a third party crypto library you probably don't need wincrypt.
1,023,474
1,023,552
Where inside injected DLL to loop?
So I've got an application that starts another application with my DLL injected (with Detours). The entry point is DllMain. I can't do much from DllMain, and certainly cannot loop. So how do I call my DLL monitor functions every x seconds? I read you cannot create a thread from DllMain (at least until it returns) and its true because it crashed me. So I tried creating it in the attach thread event and it crashed me. So now what I'm trying to do is inject it again (incase Detours fails) so I can get the module handle. Then I get the address of an initializer function which creates my thread. I get the module handle fine, but I don't think I can get the function address. I made the function empty, and it still crashed me. So it doesn't even get as far as calling the function. Visual Studio said I have no read access. So what am I suppose to do? What do you do to loop your DLL functions when you don't own the attached program (exe). //Application.exe STARTUPINFO si = {sizeof(STARTUPINFO)}; PROCESS_INFORMATION pi = {0}; DetourCreateProcessWithDll(filename, NULL, NULL, NULL, TRUE, CREATE_DEFAULT_ERROR_MODE | CREATE_SUSPENDED, NULL, path, &si, &pi, detoured, hook, NULL); processID = pi.dwProcessId; hDll = InjectDLL(processID, hook); if(hDll != NULL) { STARTER Starter = (STARTER)GetProcAddress(hDll, "Starter"); if(Starter != NULL) Starter(); } ResumeThread(pi.hThread); The function Starter is extern C exported and looks fine inspected (it's ordinal 1). I have no idea what could possibly be wrong, and merely hope someone out there has had experience with this topic and crashing. Here's the DLL code: //Hook.h extern "C" { void __declspec(dllexport) Starter(void); } //Hook.cpp void Starter(void) { } Thanks
You can't do it that way because the DLL is injected into a different process and you're trying to execute the function in the address space of your hooking process. What you'll have to do is call CreateRemoteThread, passing in the address that you get from GetProcAddress in the lpStartAddress parameter. This will create a new thread on the remote process, and execute the function in the address space of that process, in the context of the new thread. BTW, technically you should be able to create a new thread in DllMain/DLL_PROCESS_ATTACH, as long as you're not doing any synchronizing with other threads, though it's not recommended. I'm not sure what issues might exist if doing this when the DLL is being injected though.
1,023,511
1,023,554
Multiple interfaces inhertience. Casting from one to another
Consider the following set of classes/Interfaces: class IFish{ public: virtual void eat() = 0; } class IFriendly{ public: virtual void protect() = 0; } class IAggresive{ public: virtual void attack(Point inDest) = 0; } class CDolphin : public IFish, IFriendly{ eat... protect.... } class CShark : public IFish, IAggresive{ eat.... attack... } Now I am having the following class void CDiver { Void shouldRunAway(IFish* fish) { //??? } } My question is , can "shouldRunAway" extract from the fish argument whether it is an IAggresive or IFreindly (if it is any of these at all...) is there some kind of casting that can help out?
Expanding on what Drakosha posted, you would dynamic_cast the IFish pointer into an IAggressive pointer and check if it is NULL or not. Like this; #include <iostream> class IFish { public: virtual void eat() = 0; }; class IFriendly { public: virtual void protect() = 0; }; class IAggressive { public: virtual void attack() = 0; }; class Dolphin : public IFish, public IFriendly { public: virtual void eat() { std::cout << "Dolphin::eat()\n"; } virtual void protect() { std::cout << "Dolphin::protect()\n"; } }; class Shark : public IFish, public IAggressive { public: virtual void eat() { std::cout << "Shark::eat()\n"; } virtual void attack() { std::cout << "Shark::attack()\n"; } }; class Diver { public: void shouldRunAway( IFish *fish ) { if ( dynamic_cast<IAggressive *>( fish ) != NULL ) { std::cout << "Run away!\n"; } else { std::cout << "Don't run away.\n"; } } }; int main( int argc, char *argv[] ) { Dolphin dolphin; Shark shark; Diver diver; diver.shouldRunAway( &dolphin ); diver.shouldRunAway( &shark ); return 0; }
1,023,608
1,023,629
a C++ program to remove comments
I'm trying to create a program that takes a text file of c++ code and outputs another file with that code, minus any comments that it contains. Assuming that rFile and wFile are defined as follows: ifstream rFile; // File stream object for read only ofstream wFile; // File stream object for write only rFile.open("input.txt", ios::in); wFile.open("output.txt", ios::out); My first thought was simply go through the text and do the equivalent of pen-up(logo reference) when a (slightly improved) peek() identifies /* and pen down when it sees */. Of course after seeing // it would "pen-up" until it reaches \n. The problem with this approach is that the output.txt doesn't include any of the original spaces or newlines. This was the code (I didn't even try removing comments at this stage): while (!rFile.eof()) { rFile>>first; //first is a char wFile<<first; } So then I tried getting each line of code separately with getline() and then adding an endl to the wFile. It works so far, but makes things so much more complicated, less elegant and the code less readable. So, I'm wondering if anyone out there has any pointers for me. (no pun intended!) N.B. This is part of a larger homework assignment that I've been given and I'm limited to using only C++ functions and not C ones.
UPDATE: Someone else mentioned this, but I think get is probably a better function to use, than ">>". Original post: The solution is to read the input character-by-character, rather than using getline(). You can read the characters in using ">>", and output them using "<<". That way you don't have to use "endl" at all. The line terminator and space characters will be read in as individual characters. When you see the start of a comment, you can then just stop outputting characters until you eat the appropriate comment terminator. You also need to make sure to treat "\r\n" as a single terminator when processing the end of a "//" token.
1,023,638
1,147,546
Correct order for including both <cstdio> and <stdio.h>?
I need to use system-specific functions, e.g. ftello() (defined in stdio.h as per POSIX standard). I also need to use standard C++ features, e.g. std::sprintf() (defined in cstdio, as per ISO C++ standard). AFAIK, including only <cstdio> doesn't guarantee defining non-standard-C++ stuff, so I guess I have to include both. I've read a long time ago that (for example) with gcc there may be problems with the include file order. So, what is the correct order for including both <cstdio> and <stdio.h>? I'm looking for a solution which is as cross-platform as possible (at least for gcc, suncc, intel C++/linux and mingw).
OK, after some more reasearch I finally came to a conclusion that including the C++ header first, C header later is the correct thing to do. For example, consider the following C++0x header (from gcc): /usr/include/c++/4.3/tr1_impl/cstdint: // ... #define __STDC_LIMIT_MACROS #define __STDC_CONSTANT_MACROS #include_next <stdint.h> // ... What it does is that it defines two C99 macros, and only then includes the C99 stdint.h header. The reason is that in C99, some of the features of stdint.h are optional, and only available if those macros are defined. However, in C++0x, all stdint.h features are mandatory. Now, if I included the C99 stdint.h first, cstdint later, I wouldn't get the mandatory C++0x features because of the header guards in stdint.h. One could argue that this is the compiler vendor's fault, but that would be incorrect. stdint.h is a system-bundled header (from glibc in this case), which is a C99 header and doesn't know anything about C++0x (it can be an old system, after all) or gcc. The compiler can't really fix all the system headers (in this case to always enable those features in C++ mode), yet it has to provide C++0x support on these systems, so the vendor uses this workaround instead.
1,023,881
1,023,956
Ruby blocks, java closures in C++
I am developing a program where I find myself doing this like this a lot: void Model::SetCollideMode( const std::string &m ) { Body *body; std::map<std::string, Body* >::iterator iter; for (iter=this->bodies.begin(); iter!=this->bodies.end(); iter++) { body = iter->second; body->SetCollideMode( m ); } } I have several methods like that in several object that basically apply a property to all its children. Coming from Ruby world I am dying to do something like: for_all_bodies{ body->SetCollideMode(m) } There is anyway to make this code more closures like or in other way improve it? I am conscious of how C++ works, that it is stack based and there is no context information to create a perfect closure like functionality (this need a VM?) but at least improve over the current repeat this code 100 times kind of programming.
There are several approaches, none of them perfect. First, the "conventional" approach would be to define a functor to do what you need: struct SetCollideModeFunc { SetCollideModeFunc(const std::string& m) : m(m) {} void operator()(std::pair<std::string, Body*>& p) { Body* b = p.second; b->SetCollideMode(m); } const std::string& m; }; void Model::SetCollideMode( const std::string &m ) { std::for_each(bodies.begin(), bodies.end(), SetCollideModeFunc(m)); } This doesn't save you a lot of code, but it does allow you to separate the iteration from the operation that you want to apply. And if you need to set collidemode multiple times, you can reuse the functor, of course. A shorter version is possible with the Boost.Lambda library, which would allow you to define the functor inline. I can't remember the exact syntax, as I don't use Boost.Lambda often, but it'd be something like this: std::for_each(bodies.begin(), bodies.end(), _1.second->SetCollideMode(m)); In C++0x, you get language support for lambdas, allowing syntax similar to this without having to pull in third-party libraries. Finally, Boost.ForEach might be an option, allowing syntax such as this: void Model::SetCollideMode(const std::string &m) { BOOST_FOREACH ((std::pair<std::string, Body*> p), bodies) // note the extra parentheses. BOOST_FOREACH is a macro, which means the compiler would choke on the comma in the pair if we do not wrap it in an extra () { p.second->SetCollideMode(m); } }
1,024,062
1,024,165
What's a good beginner setup for C++/Python on OSX?
I'm looking for a good setup for learning C++ and eventually Python on Mac OSX. As I'm going use C++ I don't want to use XCode, as (I understand) this is primarily used with Objective-C. I have a small bit of experience in Java and MATLAB programming, and math is probably not going to be my main problem. I was thinking on an approach looking something like this: Work through Accelerated C++. Write a couple of small math-programs; something like the Mandelbrot set, a PDE-solver, or a graphing-app. This would be done using a widget toolkit. Write a small game with really crappy graphics. This is probably going to be a rip-off of Jetmen Revival or Space Invaders ;-) (When I'm fed up with the game not working), work my way through Core Python. Repeat steps 2 and 3 in Python. I'm thinking about going with Eclipse and GTK+ / X11. Any thoughts on IDE's and GUI toolkits? Preferably open source, and definitely free. And what do you think about the 5 steps? Any help would be much appreciated - thanks in advance!
When choosing an IDE, it's very much a matter of taste, so the best choice is probably to try out several for a day or two each. Eclipse and XCode are both popular choices that surely are excellent in their own ways. I can't help you with the widgets, as I know very little about that. GTK+ is a popular framework, but the native OS X support wasn't ready last time I checked, but development is ongoing so this could have changed. Qt is less popular, but is nowadays completely open source, so the licensing issues it used to have are solved now, so you might want to look into that as well. wxWidgets are popular in Python and I found it easy to use, but I don't know if it's as good as the other ones, but it may very well be. As for the five steps, it makes much more sense to do them in Python first. Python is easy to learn and master, especially if you are NOT tainted by C/C++. C/C++ programmers often has to unlearn things, as there are so many things you must do and think of that you don't have to bother with in Python. With Python you can concentrate on learning the libraries and tools, instead of having to learn how to not shoot yourself in the foot with C++. Learn C++ afterwards, and you'll have a nicer smoother learning curve, and enjoy yourself more.
1,024,341
1,024,346
Does this line declare a function? C++
I was reading litb's question about SFINAE here and I was wondering exactly what his code is declaring. A simpler (without the templates) example is below: int (&a())[2]; What exactly is that declaring? What is the role of the &? To add to my confusion, if I declare the following instead int b()[2]; I get an error about declaring a function that returns an array, while the first line has no such error (therefore, one would think the first declaration is not a function). However, if I try to assign a a = a; I get an error saying I'm attempting to assign the function a... so now it is a function. What exactly is this thing?
There's these awesome programs called cdecl and c++decl. They're very helpful for figuring out complicated declarations, especially for the byzantine forms that C and C++ use for function pointers. tyler@kusari ~ $ c++decl Type `help' or `?' for help c++decl> explain int (&a())[2] declare a as function returning reference to array 2 of int c++decl> explain int b()[2] declare b as function returning array 2 of int a returns a reference, b does not.