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
494,064
494,077
C++ Visual Studio Compilation error
I get the following compilation error fatal error C1189: #error : ERROR: Use of C runtime library internal header file. I absolutely have no idea about it. can anyone throw some light on it? The complete error: C:\Program Files\Microsoft Visual Studio 8\VC\ce\include\crtdefs.h(100) : fatal error C1189: #error : ERROR:...
You've probably got crt/src in your include directory search path. The headers in there are used to build the C Runtime - they aren't intended for use in user programs (even though they may have the same names as files that are intended to be included). If you look in the header that's causing the problem, you'll prob...
494,448
494,492
The procedure entry point _wsplitpath_s could not be locating in the dynamic link library msvcrt.dll
Recently upgrade a MFC++ Project which includes .NET assemblies from Visual Studio 2005 to 2008. Now whenever its installed it displays the following message: The procedure entry point _wsplitpath _s could not be locating in the dynamic link library msvcrt.dll I've install Microsoft Visual C++ 2008 SP1 Redistributa...
Following URLs may be of interest to you... http://msdn.microsoft.com/en-us/library/bb166245.aspx http://blogs.msdn.com/jameslau/archive/2008/02/13/upgrading-vs-2005-packages-to-vs-2008-a-more-advanced-guide.aspx http://blogs.msdn.com/quanto/archive/2008/02/19/migrating-vs-2005-packages-to-vs-2008.aspx http://blogs.msd...
494,530
543,419
Why does MIcroQuill Smartheap throw "mem_bad_pointer" errors after I embed perl?
I am embedding perl in a C++ application that uses Smartheap. Regardless of whether I compile the perl to use its own malloc or the system's I get a bunch of error mem___bad_pointer dialogs. It seems to work fine when I just click "ok" and ignore the errors, but obviously I need to actually solve the problem. Do I ma...
Without seeing the code it is hard to debug the problem. Perhaps you are allocating memory using both smartheap and the regular memory manager. this can be caused when you allocat memory in a dll build without smart heap. Depending on your code, the allocation could be fine and you may be writing outside the allcoated...
494,571
494,585
Controlling object creation
I have a class whose object must be created on the heap. Is there any better way of doing this other than this: class A { public: static A* createInstance(); //Allocate using new and return static void deleteInstance(A*); //Free the memory using delete private: //Constructor and destructor are private so that th...
This is pretty much the standard pattern for making the object heap-only. Can't really be simplified much, except that you could just make the destructor private without forcing the use of a factory method for creation.
494,597
494,630
C++ member variable aliases?
I'm pretty sure this is possible, because I'm pretty sure I've seen it done. I think it is awesome, but I will gladly accept answers along the lines of "this is a terrible idea because ____". Say we have a basic struct. struct vertex { float x, y, z; }; Now, I want to implement aliases on these variables. vertex p...
What I would do is make accessors: struct Vertex { float& r() { return values[0]; } float& g() { return values[1]; } float& b() { return values[2]; } float& x() { return values[0]; } float& y() { return values[1]; } float& z() { return values[2]; } float operator [] (unsigned i) const { r...
494,629
495,404
Building Boost for static linking (MinGW)
I'm building Boost (I'm using System and FileSystem) for MinGW using bjam: bjam --toolset=gcc stage And it builds fine, but I want to be able to statically link to it (I have to have a single file for the final product) so I tried: bjam --link=static --toolset=gcc stage But I get the same output. Any ideas? edit seco...
I think link is a property as opposed to an option for bjam. That means that there should be no -- before it. This is my command line for building only static libraries (visual c++ though): bjam install --toolset=msvc variant=release link=static threading=multi runtime-link=static Mapping that to your original build c...
494,653
495,277
How can I use the TRACE macro in non-MFC projects?
I want to use the TRACE() macro to get output in the debug window in Visual Studio 2005 in a non-MFC C++ project, but which additional header or library is needed? Is there a way of putting messages in the debug output window and how can I do that?
Build your own. trace.cpp: #ifdef _DEBUG bool _trace(TCHAR *format, ...) { TCHAR buffer[1000]; va_list argptr; va_start(argptr, format); wvsprintf(buffer, format, argptr); va_end(argptr); OutputDebugString(buffer); return true; } #endif trace.h: #include <windows.h> #ifdef _DEBUG bool _trace(TC...
495,021
495,056
Why can templates only be implemented in the header file?
Quote from The C++ standard library: a tutorial and handbook: The only portable way of using templates at the moment is to implement them in header files by using inline functions. Why is this? (Clarification: header files are not the only portable solution. But they are the most convenient portable solution.)
Caveat: It is not necessary to put the implementation in the header file, see the alternative solution at the end of this answer. Anyway, the reason your code is failing is that, when instantiating a template, the compiler creates a new class with the given template argument. For example: template<typename T> struct Fo...
495,452
495,486
Cancel a DeferWindowPos
I am doing a series of window resizing using the DeferWindowPos functionality. Suppose I already opened the DeferWindowPos handle, and called DeferWindowPos a few time, and now I want to cancel everything: not call EndDeferWindowPos. I tried CloseHandle( hDWP ), but it does not work (crash). If I simply return from...
The only reference to any kind of "abort" functionality I see is this: If any of the windows in the multiple-window- position structure have the SWP_HIDEWINDOW or SWP_SHOWWINDOW flag set, none of the windows are repositioned. This is coming from here.
495,795
495,899
How do I use a third-party DLL file in Visual Studio C++?
I understand that I need to use LoadLibrary(). But what other steps do I need to take in order to use a third-party DLL file? I simply jumped into C++ and this is the only part that I do not get (as a Java programmer). I am just looking into how I can use a Qt Library and tesseract-ocr, yet the process makes no sense t...
As everyone else says, LoadLibrary is the hard way to do it, and is hardly ever necessary. The DLL should have come with a .lib file for linking, and one or more header files to #include into your sources. The header files will define the classes and function prototypes that you can use from the DLL. You will need th...
495,922
495,951
What is the best way to implement a heartbeat in C++ to check for socket connectivity?
Hey gang. I have just written a client and server in C++ using sys/socket. I need to handle a situation where the client is still active but the server is down. One suggested way to do this is to use a heartbeat to periodically assert connectivity. And if there is none to try to reconnect every X seconds for Y peri...
If you're using TCP sockets over an IP network, you can use the TCP protocol's keepalive feature, which will periodically check the socket to make sure the other end is still there. (This also has the advantage of keeping the forwarding record for your socket valid in any NAT routers between your client and your server...
496,034
496,076
Most efficient replacement for IsBadReadPtr?
I have some Visual C++ code that receives a pointer to a buffer with data that needs to be processed by my code and the length of that buffer. Due to a bug outside my control, sometimes this pointer comes into my code uninitialized or otherwise unsuitable for reading (i.e. it causes a crash when I try to access the dat...
a thread-safe solution would be nice I'm guessing it's only IsBadWritePtr that isn't thread-safe. just doing a memcpy inside an exception handler This is effectively what IsBadReadPtr is doing ... and if you did it in your code, then your code would have the same bug as the IsBadReadPtr implementation: http://blogs...
496,204
496,230
How do I write binary data for 7z archive format?
I've been pouring over the format description and source code for the 7z archive format, but I'm still having trouble writing a valid container. I assume I can create an empty container... anyway here's my start: std::ofstream ofs(archivename.c_str(), std::ios::binary|std::ios::trunc); Byte signature[6] = {'7', 'z',...
don't know the format of 7z, but I notice when you write down offset, size and crc that these will be written to the file in little-endian format (I assume you have a little-endian CPU). Edit: An probably worse, you are missing the & before major, minor, offset, size and crc, i.e. you are casting the actual values to a...
496,214
502,367
How to use T4 code generation templates with VS C++ projects?
T4 template files are automatically recognizable by the IDE under C# projects, but I have no clue on how they can be integrated into C++ projects (other than using make files). Any ideas?
T4 Template files can be integrated into C++ projects, but it's a bit more work than with a C#/VB project. Create a new text file in your C++ project and give it a .tt extension. Then write your template as normal. A C++ project then needs further work to get it to transform the templates. The quick and dirty way I ...
496,304
496,608
Calling Ruby class methods from C++
I'm trying to call a class method from C++. I've tried all combinations of rb_intern I could think of to make it work, but I've gotten nothing. Example class class CallTest def go (do something here) end end Trying to call in C++: rb_funcall(?, rb_intern("go"), 0); What goes in the ? space? I know if I use ...
First off, go is, as you've defined it, not a class method, but an instance method. As an object oriented language, all ruby methods require a receiver, that is, an object that the method is invoked on. For instance methods, the receiver is an instance of the class, for class methods, the receiver is the class object ...
496,305
496,347
Widget wag = *new Widget()
I just came across a C++ SDK that makes heavy use of this really weird *new pattern. I dont understand why they do it like that at all. What's the point of constructing objects with *new, e.g. Widget wag = *new Widget();? Update: Interesting, they are actually doing XPtr<T> p = *new T; - must be the semantics of some...
It constructs a new object and then makes a copy of it. The pointer to the original object is discarded, so there may be a memory leak. There isn't necessarily a memory leak, though. It could be that Widget maintains a list of all its instances, and it updates that list in its constructor and destructor. There might be...
496,440
496,450
C++ virtual function from constructor
Why the following example prints "0" and what must change for it to print "1" as I expected ? #include <iostream> struct base { virtual const int value() const { return 0; } base() { std::cout << value() << std::endl; } virtual ~base() {} }; struct derived : public base { virtual const in...
Because base is constructed first and hasn't "matured" into a derived yet. It can't call methods on an object when it can't guarantee that the object is already properly initialized.
496,473
496,494
Why does the g++ 4.0 version of map<T>::erase(map::<T> iterator) not return a iterator?
I'm porting a medium-sized C++ project from Visual Studio 2005 to MacOS, XCode / GCC 4.0. One of the differences I have just stumbled across has to do with erasing an element from a map. In Visual Studio I could erase an element specified by an iterator and assign the return value to the iterator to get the position of...
No. You have to increment the iterator before erasing. Like this m_ResourceMap.erase(itor++); The iterator is invalidated by the erase, so you can't increment it afterwards.
496,664
497,158
C++ Dynamic Shared Library on Linux
This is a follow-up to Dynamic Shared Library compilation with g++. I'm trying to create a shared class library in C++ on Linux. I'm able to get the library to compile, and I can call some of the (non-class) functions using the tutorials that I found here and here. My problems start when I try to use the classes that...
myclass.h #ifndef __MYCLASS_H__ #define __MYCLASS_H__ class MyClass { public: MyClass(); /* use virtual otherwise linker will try to perform static linkage */ virtual void DoSomething(); private: int x; }; #endif myclass.cc #include "myclass.h" #include <iostream> using namespace std; extern "C" MyClass*...
497,179
498,034
How does one get the instance of a Ruby class running in the current RB file? (Embedding Ruby in C++)
I have embedded Ruby inside my C++ application. I have generated the bindings using SWIG. Basically, I run the ruby file and then Ruby takes over and calls my C++ class. Based on my previous question, I would like to get the current instance of the class that is defined in the ruby file back to the C++ class so that I ...
The C api for ruby does its best to preserve ruby's functional nature, so rb_eval_string_protect() returns the VALUE of the last line of the script given, and rb_funcall() returns the VALUE of the last line of the method invoked. So the trick is really to think of it as how would you get that instance value in pure r...
497,347
2,089,909
How do I find out whether a ResourceManager contains a key without calling ResourceManager.GetString() and catching the exception?
So I have a ResourceManager that points to a resource file with a bunch of strings in it. When I call GetString() with a key that doesn't exist in the file, I get a System.Resources.MissingManifestResourceException. I need to find out whether the Resource contains the specified key without using exception handling to c...
Note that by default, it appears that a new .net project's Resources.resx is going to be in the Properties folder, so you'll need to create the ResourceManager like this: rm = new ResourceManager("MyNamespace.Properties.MyResource", assembly); Alternatively, by getting frustrated and deleting/recreating Resources.resx...
497,408
497,497
Template typedef error
Can anyone explain why this code gives the error: error C2039: 'RT' : is not a member of 'ConcreteTable' (at least when compiled with VS2008 SP1) class Record { }; template <class T> class Table { public: typedef typename T::RT Zot; // << error occurs here }; class ConcreteTable : public Table<ConcreteTable> { ...
That's because the class ConcreteTable is not yet instantiated when instantiating Table, so the compiler doesn't see T::RT yet. I'm not really sure how exactly C++ standard handles this kind of recursion (I suspect it's undefined), but it doesn't work how you'd expect (and this is probably good, otherwise things would ...
497,428
504,907
How do I import an RSA Public Key from .NET into OpenSSL
I have a .NET program and a Borland Win32 program that need to pass some cryptographically secure information. The plan right now is to have the .NET app create a public/private key pair, store the public key on disk and keep the private key in memory for as long as the .NET program is running. The Borland app will th...
In the .NET program create a new RSACryptoServiceProvider. Export the public key as RSAParameters and write the Modulus and Exponent values to disk. Like this: RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(4096); //4096 bit key RSAParameters par = rsa.ExportParameters(false); // export the public key Fil...
497,630
11,609,941
Safely override C++ virtual functions
I have a base class with a virtual function and I want to override that function in a derived class. Is there some way to make the compiler check if the function I declared in the derived class actually overrides a function in the base class? I would like to add some macro or something that ensures that I didn't accide...
Since g++ 4.7 it does understand the new C++11 override keyword: class child : public parent { public: // force handle_event to override a existing function in parent // error out if the function with the correct signature does not exist void handle_event(int something) override; };
497,659
520,282
Can I add x-headers to a Lotus Notes email message without COM?
Trying to add a custom header item to a Lotus Notes email item, from the context of a Notes Client Extension before the mail is sent from the Lotus Notes client app. Is this possible? I'm looking along the lines of using something in the NSFItemSetText family of functions if at all possible, as opposed to the lotus scr...
You can add headers using the MailAddHeaderItem function, which is in mailsrv.h If your using NSFItemSetText you might have code based on the SENDMEMO example. Have a Look at the SENDMAIL example which references using MailAddHeaderItemByHandle. The examples are included in the C api toolkit which you can download her...
497,766
497,800
What is the difference between c++0x concepts and c# constraints?
C++0x introduces concepts, that let you define, basically, a type of a type. It specifies the properties required of a type. C# let you specify constraints of a generic with the "where" clause. Is there any semantic difference between them? Thank you.
One thing to keep in mind is that C++ templates and C# generics are not exactly the same. See this answer for more details on those differences. From the page you linked to explaining C++0x concepts, it sounds like the idea is that in C++ you want to be able to specify that the template type implements certain properti...
497,786
497,869
Why would anybody use C over C++?
Although people seem to like to complain about C++, I haven't been able to find much evidence as to why you would want to choose C over C++. C doesn't seem to get nearly as much flak and if C++ has all these problems why can't you just restrict yourself to the C subset? What are your thoughts/experience?
Joel's answer is good for reasons you might have to use C, though there are a few others: You must meet industry guidelines, which are easier to prove and test for in C You have tools to work with C, but not C++ (think not just about the compiler, but all the support tools, coverage, analysis, etc) Your target develop...
498,106
498,130
How do I compile a Visual Studio project from the command-line?
I'm scripting the checkout, build, distribution, test, and commit cycle for a large C++ solution that is using Monotone, CMake, Visual Studio Express 2008, and custom tests. All of the other parts seem pretty straight-forward, but I don't see how to compile the Visual Studio solution without getting the GUI. The sc...
I know of two ways to do it. Method 1 The first method (which I prefer) is to use msbuild: msbuild project.sln /Flags... Method 2 You can also run: vcexpress project.sln /build /Flags... The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script. Note ...
498,169
498,196
Qt and VC++ 6.0 IDE?
First of all I was wondering if I should use Qt and Windows together. If so should I use VC++ 6.0 IDE or another one?
I'm of the opinion that no one should be using VC++ 6.0 for anything at this point. Your better off just getting the express version of 2008 if your worried about cost.
498,319
543,452
Visual Studio: Intellisense Problems and Linux Compatibility
Two somewhat unrelated questions: Sometimes when I am working on a C++ project in Visual Studio 2008 Express, intellisense just does not want to "work" even though it really should. Auto completion box does not show and status bar says something along the lines of: "Intellisense: No further information is available". ...
Intellisense failing is usually because of a "corrupt" ncb file. The usual solution is to delete it. Reportly the next version VS 2010 will not be using ncb files anymore.
498,433
498,442
Resolving "only static const integral data members can be initialized within a class" compilation error
The following for creating a Global Object is resulting in compilation errors. #include "stdafx.h" #include <iostream> using namespace System; using namespace std; #pragma hdrstop class Tester; void input(); class Tester { static int number = 5; public: Tester(){}; ~Tester(){}; void setN...
Just start addressing the errors one by one. A lot of the errors are just cascaded from the initial errors, so it looks like there are a lot of problems when there's only a couple. Just start from the top: 1>.\test.cpp(15) : error C2864: 'Tester::number' : only static const integral data members can be initialized with...
498,455
498,483
Best way to iterate through a container
What are the Advantages/Drawbacks of these two ways of iterating through a container / which one do you prefer and why: for (MyClass::iterator i = m.begin(), e = m.end() ; i != e ; i++) { // ... } or for (MyClass::iterator i = m.begin() ; i != m.end() ; i++) { // ... } Subsidiary question: i++ or ++i? Why?
If the iterator is non-trivial (ie. not a pointer), ++i is definitely faster as it doesn't involves a copy to a temporary, which may or may not be optimized out. The first form is a little faster but could be wrong if you erase or insert things in the loop. For simple iteration over a container I use #define foreach BO...
498,526
498,559
Native vs. Protothreads, what is easier?
I just stumbled on Protothreads. They seems superior to native threads since context switch are explicit. My question is. Makes this multi-threaded programming an easy task again? (I think so. But have I missed something?)
They're not "superior" - they're just different and fit another purpose. Protothreads are simulated, and hence aren't real threads. They won't run on multiple cores, and they will all block on a single system call (socket recv() and such). Hence you shouldn't see it as a "silver bullet" that solves all multithreading p...
498,582
499,187
Smart pointers with a library written in C
I'm using C++ with the OpenCV library, which is a library image-processing although that's not relevant for this question. Currently I have a design decision to make. OpenCV, being a C library, has its data structures (such as CvMat) declared as structs. To create them, you use functions like cvCreateMat, and to relea...
The auto_ptr are really designed for RAII on C++ class with constructs/destructors you are pushing their uses here to things they probably should not be used for (but can). Anyway don'y you want to be able to use your C++ object as if it was a normal stack variable without dynamically allocating each time? The standa...
498,757
498,821
Factory method returning an concrete instantiation of a C++ template class
I have a class template <unsigned int N> class StaticVector { // stuff }; How can I declare and define in this class a static factory method returning a StaticVector<3> object, sth like StaticVector<3> create3dVec(double x1, double x2, double x2); ?
"How can I declare and define in this class" In what class? You've defined a class template, not a class. You can't call a static function of a class template itself, you have to call a particular version of the static function that's part of a real class. So, do you want the template (and hence all instantiations of i...
498,783
498,793
Instantiating a queue as a class member in C++
Suppose I need to have a class which wraps a priority queue of other objects (meaning the queue is a member of the class), and additionally gives it some extra functions. I am not quite sure what the best way is to define that vector and, mainly, how to instantiate it. Currently I have something like this in the header...
Just write: SomeClass::SomeClass(): queue() { } C++ knows to call the constructor automatically from there with no arguments.
498,835
498,842
A question related to deriving standard exception classes
/* user-defined exception class derived from a standard class for exceptions*/ class MyProblem : public std::exception { public: ... MyProblem(...) { //special constructor } virtual const char* what() const throw() { //what() function ... } }; ... void f() { ... //create an exceptio...
Empty braces in "throw()" means the function does not throw.
499,016
499,066
Erase all members of a class
Yesterday I read some code of a colleague and came across this: class a_class { public: a_class() {...} int some_method(int some_param) {...} int value_1; int value_2; float value_3; std::vector<some_other_class*> even_more_values; /* and so on */ } a_class a_instances[10]; void some_f...
This is a widely accepted method for initialization for C structs. In C++ it doesn't work ofcourse because you can't assume anything about vectors internal structure. Zeroing it out is very likely to leave it in an illegal state which is why your program crashes.
499,106
499,122
What does template <unsigned int N> mean?
When declaring a template, I am used to having this kind of code: template <class T> But in this question, they used: template <unsigned int N> I checked that it compiles. But what does it mean? Is it a non-type parameter? And if so, how can we have a template without any type parameter?
It's perfectly possible to template a class on an integer rather than a type. We can assign the templated value to a variable, or otherwise manipulate it in a way we might with any other integer literal: unsigned int x = N; In fact, we can create algorithms which evaluate at compile time (from Wikipedia): template <i...
499,153
499,159
Passing a qualified non-static member function as a function pointer
I have a function in an external library that I cannot change with the following signature: void registerResizeCallback(void (*)(int, int)) I want to pass in a member function as the callback, as my callback needs to modify instance variables. Obviously this isn't possible with a simple: registerResizeCallback(&Window...
Check "[33.2] How do I pass a pointer-to-member-function to a signal handler, X event callback, system call that starts a thread/task, etc?" at the C++ FAQ Lite: Don't. Because a member function is meaningless without an object to invoke it on, you can't do this directly ... As a patch for existing software, use a top...
499,236
499,250
A Question on Template Specialization and the Resulting Code Duplication
To specialize a class template, one has to redefine all of the member functions in the underlying base template (i.e. the unspecialized class template) even if they are expected to remain mostly unchanged. What are some of the accepted methods and "best practices" to avoid this code duplication? Thanks.
You can fully specialize a member selectively: template<int N> struct Vector { int calculate() { return N; } }; // put into the .cpp file, or make inline! template<> int Vector<3>::calculate() { return -1; } You do a full specialization. Meaning you cannot partial specialize it: template<int N, int P> struct Vect...
499,450
499,474
On Linux, is the command-line program mktemp less safe than the C-function mkstemp?
Both operations create an empty file and return the filename but mkstemp leaves the file open in exclusive mode and gives you the handle. Is there a safety benefit to the C-function? Does this imply that there is a safety hole in the command-line version? As an aside, it is interesting that there are several related ...
As you can easily see from mktemp(1) source code, it essentially does nothing but calling mkstemp(3). Exclusive mode in Linux means that function will fail if the file already exists, it does not guarantee locking. Other process can delete this file, create it again and fill it with data, despite the file handle being ...
499,636
499,654
How to create a std::ofstream to a temp file?
Okay, mkstemp is the preferred way to create a temp file in POSIX. But it opens the file and returns an int, which is a file descriptor. From that I can only create a FILE*, but not an std::ofstream, which I would prefer in C++. (Apparently, on AIX and some other systems, you can create an std::ofstream from a file de...
I think this should work: char *tmpname = strdup("/tmp/tmpfileXXXXXX"); ofstream f; int fd = mkstemp(tmpname); f.attach(fd); EDIT: Well, this might not be portable. If you can't use attach and can't create a ofstream directly from a file descriptor, then you have to do this: char *tmpname = strdup("/tm...
499,713
500,934
Transforming an object between two coordinate spaces
So I'm reading the "3D Math Primer For Graphics And Game Development" book, coming from pretty much a non-math background I'm finally starting to grasp vector/matrix math - which is a relief. But, yes there's always a but, I'm having trouble understand the translation of an object from one coordinate space to another....
You should read how to change basis and think in vector, not arrays but the math ones :P
499,780
499,796
Is PThread a good choice for multi-platorm C/C++ multi-threading program?
Been doing mostly Java and smattering of .NET for last five years and haven't written any significant C or C++ during that time. So have been away from that scene for a while. If I want to write a C or C++ program today that does some multi-threading and is source code portable across Windows, Mac OS X, and Linux/Unix ...
Well, pthreads is the old posix standard for writing threaded programs. Its the lowest level threading routines, so its a good choice for cross-platform threading. However, there are alternatives: boost::thread - an STL style threading library Intel's Thread Building Blocks OpenMP - both these are a higher-level way...
500,006
500,008
What is the purpose of anonymous { } blocks in C style languages?
What is the purpose of anonymous { } blocks in C style languages (C, C++, C#) Example - void function() { { int i = 0; i = i + 1; } { int k = 0; k = k + 1; } } Edit - Thanks for all of the excellent answers!
It limits the scope of variables to the block inside the { }.
500,182
500,189
c++: header function not being linked properly from library into exe
I have a header file in a library (alibrary.lib). The library is a static library (.lib) and it links properly to exe. Now, I have a class: Vector3d. class Vector3d { void amethod() { blah } }; Vector3d cross(const Vector3d &v0, const Vector3d &v1) { float x,y,z; x = v0.y*v1.z-v0.z*...
If you define a free (not a member of a class) function, it has to be defined in a .cpp file separately compiled, or in a header and marked inline. So in your case, you can get away making it compile by this: inline Vector3d cross(const Vector3d &v0, const Vector3d &v1) { float x,y,z; x = v0.y*v1.z-v0.z*v1...
500,244
500,251
Is there a favored idiom for mimicing Java's try/finally in C++?
Been doing Java for number of years so haven't been tracking C++. Has finally clause been added to C++ exception handling in the language definition? Is there a favored idiom that mimics Java's try/finally? Am also bothered that C++ doesn't have an ultimate super type for all possible exceptions that could be thrown - ...
By making effective use of destructors. When an exception is thrown in a try block, any object created within it will be destroyed immediately (and hence its destructor called). This is different from Java where you have no idea when an object's finalizer will be called. UPDATE: Straight from the horse's mouth: Why ...
500,362
500,367
Alternative Keyword Representations
The C++ standard (ISO/IEC 14882:03) states the following (2.11/2): Furthermore, the alternative representations shown in Table 4 for certain operators and punctuators (2.5) are reserved and shall not be used otherwise: and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq I have tried using these wit...
Yes, you can use them as alternative to name tokens. For example: struct foo { // defines a destructor compl foo() { } }; Your example would work too. It would however store an one into i. If you want to use bitwise not, you use compl (~): int i = compl 0;
500,387
500,500
Keeping track of an objects local coordinate space
Ok, so - this is heavily related to my previous question Transforming an object between two coordinate spaces, but a lot more direct and it should have an obvious answer. An objects local coordinate space, how do I "get a hold of it"? Say that I load an Orc into my game, how do I know programatically where it's head, l...
Actually, it is about transforming between coordinate spaces. Ok, you understand that you can have a Matrix that does Translation or Rotation. (Or scaling. Or skew. Etc.) That you can multiply such a Matrix by a point (V) to get the new (translated/rotated/etc) point. E.g.: Mtranlate = [ 1 0 0 Tx ] * V = [ Vx ]...
500,456
500,496
Pure Virtual Method VS. Function Pointer
Recently I've been designing a Thread class library, I've made a Thread abstract class like the following: class Thread { public: run() { /*start the thread*/ } kill() { /*stop the thread*/ } protected: virtual int doOperation(unsigned int, void *) = 0; }; Real thread classes would inherit this abstract cl...
First, be sure to read the link Michael Burr provided, as it contains good information. Then, here is C++ish pseudo-code for it: int wrapperDoOperation(int v, void *ctx) { Thread *thread = (Thread *)ctx; return thread->doOperation(v); } class Thread { public: run() { startThread("bla", wrapperDoOp...
500,493
500,495
C++ equivalent of java's instanceof
What is the preferred method to achieve the C++ equivalent of java's instanceof?
Try using: if(NewType* v = dynamic_cast<NewType*>(old)) { // old was safely casted to NewType v->doSomething(); } This requires your compiler to have rtti support enabled. EDIT: I've had some good comments on this answer! Every time you need to use a dynamic_cast (or instanceof) you'd better ask yourself whether...
500,656
500,743
C++ using scoped_ptr as a member variable
Just wanted opinions on a design question. If you have a C++ class than owns other objects, would you use smart pointers to achieve this? class Example { public: // ... private: boost::scoped_ptr<Owned> data; }; The 'Owned' object can't be stored by value because it may change through the lifetime of the object....
It's a good idea. It helps simplify your code, and ensure that when you do change the Owned object during the lifetime of the object, the previous one gets destroyed properly. You have to remember that scoped_ptr is noncopyable, though, which makes your class noncopyable by default until/unless you add your own copy co...
500,663
531,160
How to determine the supported thread model of an out-of-process COM server?
Question: How to find the threading models supported by a predefined out-of-process (EXE-based) Server: Using oleview? Or any other valid methods? Note: Attempting to connect to the above described server to receive event notifications
I'm afraid the question is wrong. Threading models (STA, MTA, etc) are a necessary evil that apply only to in-process COM objects, where objects and clients need to coexist in the same process and somehow they must prevent stepping on each other's toes (a fun and lengthy topic). Out-of-process (EXE) COM servers live in...
500,748
500,765
What is static_case operator in C++?
I've heard of static_cast operator Recently I've come across static_case, for instance: *ppv = static_case<IUnknown> What does this mean?
It's a typo : there is no static_case, only static_cast, dynamic_cast, const_cast and reinterpret_cast. You can see on google that the docs where you find "static_case" have typos and use static_cast and static_case like if it was the same word. To be sure, just try to use static_case in available compilers.
501,060
501,136
How to efficiently implement an event loop?
COM Object (Server) sends event notification successfully to COM Client Without: ATL MFC How to efficiently get the main thread to wait/sleep (infinitely) until COM Server notifies the COM Client of a particular event?
With event objects. The main thread calls CreateEvent() in its initialisation to create an auto-reset event object. The main thread then enters an event loop in which it calls MsgWaitForMultipleObjects() repeatedly. (here is an example of a message loop.) And you generally do need to check for window messages, even if...
501,163
501,182
A question about auto_ptr
template<class Y> operator auto_ptr_ref<Y>() throw() { return auto_ptr_ref<Y>(release()); } It is part of implementation of class auto_ptr in standard library. What does this means to do? Why there is an "auto_ptr_ref" between "operator" and "()"?
That is the conversion operator in action, casting from auto_ptr to auto_ptr_ref<Y>.
501,486
3,984,156
Getting GDB to save a list of breakpoints
OK, info break lists the breakpoints, but not in a format that would work well with reusing them using the --command as in this question. Does GDB have a method for dumping them into a file acceptable for input again? Sometimes in a debugging session, it is necessary to restart GDB after building up a set of breakpoin...
As of GDB 7.2 (2011-08-23) you can now use the save breakpoints command. save breakpoints <filename> Save all current breakpoint definitions to a file suitable for use in a later debugging session. To read the saved breakpoint definitions, use the `source' command. Use source <filename> to restore the saved bre...
501,774
501,792
Adding C++ template classes to a list
I have a template class, C_Foo<T>, which is specialised in a number of ways. struct Bar_Base { ... }; struct Bar_1 : public Bar_Base { ... }; struct Bar_2 : public Bar_Base { ... }; struct Bar_3 : public Bar_Base { ... }; class C_Foo<T> { ... }; class C_Foo_1 : public C_Foo<Bar_1> { ... }; class C_Foo_2 : public C_Fo...
You can do that, if the function does not depend on the template parameter: // note: not a template class C_Foo_Common { public: virtual void do_stuff() = 0; }; template<typename T> class C_Foo : public C_Foo_Common { virtual void do_stuff() { // do stuff... } }; vector<C_Foo_Common *> v; v.push...
501,816
501,828
Why does cout print char arrays differently from other arrays?
I'm using C++ to understand how exactly pointers work. I have this piece of code using arrays, which I'm using just to understand how the equivalent works with pointers. int main() { int arr[10] = {1,2,3}; char arr2[10] = {'c','i','a','o','\0'}; cout << arr << endl; cout << arr2 << endl; } Howe...
It's the operator<< that is overloaded for const void* and for const char*. Your char array is converted to const char* and passed to that overload, because it fits better than to const void*. The int array, however, is converted to const void* and passed to that version. The version of operator<< taking const void* ju...
501,899
501,908
In Inheritance: Can I override base class data members?
Let's say I have two classes like the following: Class A { public: .. private: int length; } Class B: public Class A { public: .. private: float length; } What I would like to know is: Is overriding of base class data members allowed? If yes, is it a good practice? If no, what is the best way to extend the type o...
You can use templatized members i.e., generic members instead of overriding the members. You can also declare a VARIANT(COM) like union. struct MyData { int vt; // To store the type union { LONG lVal; BYTE bVal; S...
501,962
501,971
Erasing items from an STL list
I want to make a function which moves items from one STL list to another if they match a certain condition. This code is not the way to do it. The iterator will most likely be invalidated by the erase() function and cause a problem: for(std::list<MyClass>::iterator it = myList.begin(); it != myList.end(); it++) { if(...
Erase returns an iterator pointing to the element after the erased one: std::list<MyClass>::iterator it = myList.begin(); while (it != myList.end()) { if(myCondition(*it)) { myOtherList.push_back(*it); it = myList.erase(it); } else { ++it; } }
502,022
502,040
How to find mantissa length on a particular machine?
I'm wanting to find the number of mantissa digits and the unit round-off on a particular computer. I have an understanding of what these are, just no idea how to find them - though I understand they can vary from computer to computer. I need this number in order to perform certain aspects of numerical analysis, like ...
I would think that whatever language you were using would specify how floats were stored. I know Java does this by use of a specific IEEE standard (754, I think). If it's not specified, I would think you could just do your own check by adding 0.5 to 1 to see if the actual number changes. If it does, then add 0.25 to 1,...
502,278
502,280
Create GUID menu item missing in Visual C++
I do not see "Create GUID" option under the menu item Tools -> . I am using Visual Studio 2005 . Do I have to install anything for that .
It's likely missing because the profile you chose does not include that particular option. Try the following Tools -> Import and Export Settings Select "Reset all Settings" and hit Next Select "No, just reset settings, overwriting my current settings" and hit Next Select "General Development Settings" and hit Finish...
502,430
502,467
Passing "const" variable to method in Java
Is there an equivalent in Java to the passing on const references in C++? Isn't leaving out the "constness" misleading in regard to the method signature?
No, there isn't. Java "final" is not an exact equivalent of C++ "const". The following (delayed initialization of a final variable) works in Java: final double x; int w = 1; if (w > 2) { x = 0.5; } else { x = - 0.5; } but it doesn't work in C++ with "final" replaced by "const". Using "final" on a variable in t...
502,435
502,459
Should I wrap all my c++ code in its own namespace?
I come from a c# background where everything has its own namespace, but this practice appears to be uncommon in the c++ world. Should I wrap my code in it's own namespace, the unnamed namespace, or no namespace?
Many C++ developers do not use namespaces, sadly. When I started with C++, I didn't use them for a long time, until I came to the conclusion that I can do better using namespaces. Many libraries work around namespaces by putting prefixes before names. For example, wxWidgets puts the characters "wx" before everything. ...
502,443
503,545
Prime numbers program
I'm currently trying out some questions just to practice my programming skills. ( Not taking it in school or anything yet, self taught ) I came across this problem which required me to read in a number from a given txt file. This number would be N. Now I'm suppose to find the Nth prime number for N <= 10 000. After I f...
#include <cstdio> #include <iostream> #include <cstdlib> #include <fstream> using namespace std; int main() { ifstream trial; trial.open("C:\\Users\\User\\Documents\\trial.txt"); int prime, e; trial>>prime; ofstream write; write.open("C:\\Users\\User\\Documents\\answer.txt"); int num[10000], currentPrime, c, primePr...
502,640
504,125
Disable/Enable Ribbon Buttons for MFC Feature Pack
I am using the MFC Feature Pack and I have some buttons on a ribbon bar, instances of CMFCRibbonButton. The problem is that I would like to enable and disable some of them in certain conditions, but at runtime. How can I do this? because there is no specific method for this...I heard that a solution would be to attach/...
When you create the CMFCRibbonButton object you have to specify the associated command ID (see the documentation for the CMFCRibbonButton constructor here). Enabling and disabling of ribbon buttons is then done using the usual command update mechanism in MFC, using the CCmdUI class. For example, if you have a ribbon bu...
502,856
502,862
What's the difference between size_t and int in C++?
In several C++ examples I see a use of the type size_t where I would have used a simple int. What's the difference, and why size_t should be better?
From the friendly Wikipedia: The stdlib.h and stddef.h header files define a datatype called size_t which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t. The actual type of size_t is platform-dependent; a commo...
503,030
504,745
What function was used to code these passwords in AFX?
I am trying to work out the format of a password file which is used by a LOGIN DLL of which the source cannot be found. The admin tool was written in AFX, so I hope that it perhaps gives a clue as to the algorithm used to encode the passwords. Using the admin tool, we have two passwords that are encoded. The first is "...
Well, I did a quick cryptanalysis on it, and so far, I can tell you that each password appears to start off with it's ascii value + 26. The next octet seems to be the difference between the first char of the password and the second, added to it's ascii value. The 3d letter, I haven't figured out yet. I think it's sa...
503,401
879,569
How to debug file change notifications obtained by FindFirstChangeNotification?
So, the question is: I get some notifications I don't want to get. But I don't know for what file/dir I got them. Is there a way to know why given notification was fired? If you think about ReadDirectoryChangesW, please include a meaningful code sample.
If you would like Windows to tell you what specific file or subdirectory changed, you will need to use ReadDirectoryChangesW. The asynchronous mode is fairly simple if you use a completion routine. On the other hand, you will probably get better performance by using the slightly more complicated I/O completion ports a...
503,421
506,128
How can I get the current users permission groups?
I have a Qt/C++ project and an old VB6 project. The user base might not have permissions to HKEY_LOCAL_MACHINE due to lack of administrator rights but I need to update a registry entry. How can I get a list of the groups to which a user belongs?
I have this is_admin program bookmarked. It's a good example of how to do this.
503,526
503,575
Image Processing Library for C++
I need a library that can detect objects in an image (uses edge detection). This is NOT related to captchas. I am working on an MTGO bot that uses OCR and that works in any screen resolution. In order for it to port to any screen resolution my idea is to scan down narrow range on a results page (the cards that a player...
If you don't know of the OpenCV collection of examples, then they could help you in the right direction... there's also Camellia which doesn't use "edge detection" per-se but could get the results you need with a bit of work.
503,664
503,861
Member functions for derived information in a class
While designing an interface for a class I normally get caught in two minds whether should I provide member functions which can be calculated / derived by using combinations of other member functions. For example: class DocContainer { public: Doc* getDoc(int index) const; bool isDocSelected(Doc*) const; int g...
In general, you should probably prefer free functions. Think about it from an OOP perspective. If the function does not need access to any private members, then why should it be given access to them? That's not good for encapsulation. It means more code that may potentially fail when the internals of the class is modif...
503,833
504,432
What is the best way to implement smart pointers in C++?
I've been evaluating various smart pointer implementations (wow, there are a LOT out there) and it seems to me that most of them can be categorized into two broad classifications: 1) This category uses inheritance on the objects referenced so that they have reference counts and usually up() and down() (or their equival...
"What is the best way to implement smart pointers in C++" Don't! Use an existing, well tested smart pointer, such as boost::shared_ptr or std::tr1::shared_ptr (std::unique_ptr and std::shared_ptr with C++ 11) If you have to, then remember to: use safe-bool idiom provide an operator-> provide the strong exception ...
503,866
505,961
timer class in linux
I need a timer to execute callbacks with relatively low resolution. What's the best way to implement such C++ timer class in Linux? Are there any libraries I could use?
If you're writing within a framework (Glib, Qt, Wx, ...), you'll already have an event loop with timed callback functionalities. I'll assume that's not the case. If you're writing your own event loop, you can use the gettimeofday/select pair (struct timeval, microsecond precision) or the clock_gettime/nanosleep pair (...
503,916
503,953
Extract element from 2 vectors?
I have 2 vector of with one has vec1{e1,e2,e3,e4} and the other one with vec2 {e2,e4,e5,e7} How to effectively get three vector from above vectors such that 1.has elements that is available only in vec1 similarly 2 has only vec2 elements and 3.with common elements
std::set_intersection should do the trick, if both vectors are sorted: http://msdn.microsoft.com/en-us/library/zfd331yx.aspx std::set_intersection(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), std::back_inserter(vec3)); A custom predicate can be used for the comparison too: std::set_intersection(vec1.begin(), ve...
504,257
504,418
Public and private access for the same member functions
I have a class (class A) that is designed to be inherited by other classes written by other people. I also have another class (class B), that also inherits from A. B has to access some A's member functions that shouldn't be accessed by other inheriting classes. So, these A's member functions should be public for B, but...
What you say is: there are two sets of subclasses of A. One set should have access, the other set shouldn't. It feels wrong to have only one brand of subclasses (i.e. B) 'see' A's members. If what you mean is: only we can use this part of functionality, while our clients can't, there are other resorts. (Functionality...
505,021
505,047
Get bytes from std::string in C++
I'm working in a C++ unmanaged project. I need to know how can I take a string like this "some data to encrypt" and get a byte[] array which I'm gonna use as the source for Encrypt. In C# I do for (int i = 0; i < text.Length; i++) buffer[i] = (byte)text[i]; What I need to know is how to do the same but using unm...
If you just need read-only access, then c_str() will do it: char const *c = myString.c_str(); If you need read/write access, then you can copy the string into a vector. vectors manage dynamic memory for you. You don't have to mess with allocation/deallocation then: std::vector<char> bytes(myString.begin(), myString.e...
505,024
505,068
Writing string (REG_SZ) values to the registry in C++
I've got most of the code for writing a value to the windows registry, however when I change the path to a dummy key and value that I've set up for testing it fails. My code is below: HKEY hKey; LPCTSTR sk = TEXT("SOFTWARE\TestSoftware"); LONG openRes = RegOpenKeyEx(HKEY_LOCAL_MACHINE, sk, 0, KEY_ALL_ACCE...
I feel silly. The solution is that need to properly escape the slash in the string as follows: LPCTSTR sk = TEXT("SOFTWARE\\TestSoftware"); Hopefully someone finds this useful...
505,151
2,017,166
CUDA + Visual Studio = suppressed output window
Normally, when I use Visual Studio to do a build, I see warnings and errors shown in the output pane, e.g. 1>------ Build started: Project: pdcuda, Configuration: Release x64 ------ Compiling... foo.cpp Linking... foo.obj : error LNK2001: unresolved external symbol "foo" ========== Build: 0 succeeded, 1 failed, 0 up-to...
Final solution: reinstall the OS.
505,261
505,308
How to create threads in VC++
I tend to use POSIX Threads, when programming in C, under Linux. Without MFC Question: How would I then create threads in VC++? Find more information on threads under win32? Edit: Brief illustrations I LOVE stackoverflow - best resource for students! Regards
You should not use the raw Win32 CreateThread() API. Use the C runtime's _beginthreadex() so the runtime has an opportunity to set up its own thread support.
505,476
505,519
Why does c_str() print the string twice?
So... when I go: cout<<stringName<<endl; I get: NT But when I go: cout<<stringName.c_str()<<endl; I get: NTNT Why?
A quick test with the following code: #include <string> #include <iostream> using namespace std; int main(void) { string str = "NT"; cout << str.c_str() << endl; return 0; } produces one instance of NT so it looks like you probably have another output call somewhere.
505,593
505,603
Efficiently wait for a flag state change without blocking resources?
Thread to wait infinitely in a loop until a flag state change, then call function. pseudo code illustration: while (true) { while (!flag) { sleep(1); } clean_upfunction(); } Currently: Using the multithreaded versions of the C run-time libraries only No: MFC Question: Is there a more e...
For Windows (which you have this tagged for), you want to look at WaitForSingleObject. Use a Windows Event (with CreateEvent), then wait on it; the other thread should call SetEvent. All native Windows, no MFC or anything else required.
505,627
505,631
tracking after cluster group status c++
I would like to write a cluster aware application that will track after the status of a cluster group. to be more specific, I'd like to probe after the group's Owner. The application should know if the local machine is the owner of the group or not and behave accordingly. can I probe the registry for that? if yes, wher...
Read up on the Cluster API. I'm not going to write up an entire walk-through, but using the API you can get all (or virtually all) of the information exposed by the OS tools, and then some.
505,647
505,672
Interprocess communication between 32- and 64-bit apps on Windows x64
We'd like to support some hardware that has recently been discontinued. The driver for the hardware is a plain 32-bit C DLL. We don't have the source code, and (for legal reasons) are not interested in decompiling or reverse engineering the driver. The hardware sends tons of data quickly, so the communication protocol ...
If this is a real driver (kernel mode), you're SOL. Vista x64 doesn't allow installing unsigned drivers. It this is just a user-mode DLL, you can get a fix by using any of the standard IPC mechanisms. Pipes, sockets, out-of-proc COM, roughly in that order. It all operates on bus speeds so as long as you can buffer ...
505,863
505,984
How do I zip a directory of files using C++?
I'm working on a project using C++, Boost, and Qt. I understand how to compress single files and bytestreams using, for example, the qCompress() function in Qt. How do I zip a directory of multiple files, including subdirectories? I am looking for a cross-platform (Mac, Win, Linux) solution; I'd prefer not to fire off...
I have found the following two libraries: ZipIOS++. Seems to be "pure" C++. They don't list Windows explicitly as a supported platform. So i think you should try your luck yourself. QuaZIP. Based on Qt4. Actually looks nice. They list Windows explicitly (Using mingw). Apparently, it is a C++ wrapper for [this] librar...
505,939
505,967
VS2005 C++ compiler problem including <comdef.h> in MFC application
I am having some trouble converting an old project from VS6 to VS2005. At one place in the code it uses the type variant_t so it includes comdef.h for this purpose. comdef.h then includes comutil.h which generates these errors for me: c:\program files\microsoft visual studio 8\vc\include\comutil.h(978) : error C2535: '...
Does your own code do something like this: #define long int
506,358
506,508
excelApp.CreateDispatch() returns a zero value : failure
I have the following piece of code in Visual C++ 2005 : : class _Application:public COleDispatchDriver {....}; _Application excelApp; excelApp.CreateDispatch((LPCTSTR)_T("Excel.Application"))) But the call to excelApp.CreateDispatch((LPCTSTR)_T("Excel.Application"))) returns a zero value indicating a failure . Coul...
I got the answer people : I just had to call CoInitialize(0) before the above piece of code . and then CoUninitialize() after all are done . Cool it was ....
506,441
506,491
Keeping the GUI separate
I have a program that (amongst other things) has a command line interface that lets the user enter strings, which will then be sent over the network. The problem is that I'm not sure how to connect the events, which are generated deep inside the GUI, to the network interface. Suppose for instance that my GUI class hier...
Short of having some global pub/sub hub, you aren't going to get away from passing something up or down the hierarchy. Even if you abstract the listener to a generic interface or a controller, you still have to attach the controller to the UI event somehow. With a pub/sub hub you add another layer of indirection, but ...
506,496
506,509
Strange behavior in constructor
I have a class made up of several fields, and I have several constructors. I also have a constructor that doesn't take any parameters, but when I try to use it: int main { A a; } The compiler generates an error, while if I use it like this: int main { A a(); } It's ok. What's that? Thank you
The first main uses A's default constructor. The second one declares a function that takes no parameters and returns an A by value, which probably isn't what you intend. So what does the definition of A look like and what is the error that the compiler generates? Oh, and you need to provide a parameter list in the decl...
506,518
506,590
Is there any guarantee of alignment of address return by C++'s new operation?
Most of experienced programmer knows data alignment is important for program's performance. I have seen some programmer wrote program that allocate bigger size of buffer than they need, and use the aligned pointer as begin. I am wondering should I do that in my program, I have no idea is there any guarantee of alignmen...
The alignment has the following guarantee from the standard (3.7.3.1/2): The pointer returned shall be suitably aligned so that it can be converted to a pointer of any complete object type and then used to access the object or array in the storage allocated (until the storage is explicitly deallocated by a call...
506,522
507,302
Mysterious relative path library dependency
After loading an existing MFC application in Visual Studio 2008, I am left with one linking error: LINK : fatal error LNK1104: cannot open file '..\..\xpressmp\lib\xprm_rt.lib' I have looked "everywhere", but I can't figure out where the relative path is set. The lib file is located in C:\xpressmp\lib, and I have adde...
It sounds like one of a couple possibilities to me: The library itself is setting the lib include path via a #pragma comment(lib, ...) directive; search library headers to see if that's the case You have a project for the library included in your solution which your main project is dependent on, and the relative libra...
506,898
506,905
What are the common misuse of using STL containers with iterators?
What are the common misuse of using STL containers with iterators?
Forgetting that iterators are quite often invalidated if you change the container by inserting or erasing container members. For many great tips on using STL I highly recommend Scott Meyers's book "Effective STL" (sanitised Amazon link)
507,043
507,047
Virtual function invocation from constructor
Maybe I am wrong, but this seems to be a very basic question. Suddenly my inheritance chain stopped working. Writing a small basic test application proved that it was me that was wrong (so I can't blame the compiler). I have a base class, with the default behavior in a virtual function. A child class derives from that ...
You are calling a virtual method in the constructor, which is not going to work, as the child class isn't fully initialized yet. See also this StackOverflow question.
507,249
507,397
Is there a way to monitor heap usage in C++/MacOS?
I fear that some of my code is causing memory leaks, and I'm not sure about how to check it. Is there a tool or something for MacOS X? Thank you
Apple has a good description of how to use MallocDebug on OS X on their developer pages. document on finding leaks in general enabling debug features of malloc in particular.
507,446
507,511
GCC 4.0: "no matching function to call" in template function
I am wondering why the following contrived example code works perfectly fine in Visual Studio 2005, but generates an error in GCC ("no matching function to call" when calling Interpolate() as shown below). Also, how do I work around this? It seems that the error message is just a generic message because GCC did not ha...
I don't think you need the template there at all in the function definition, since it is defined inline with the class TMyPointTemplate Interpolate(const TMyPointTemplate &OtherPoint)const { should do. And when you do use the template for defining the function not inline, I think you need the class keyword in there li...
507,477
1,493,765
How to convert a float to a string regardless of regional settings?
My product is targeted to a Portuguese audience where the comma is the decimal symbol. I usually use CString::Format to input numbers into strings, and it takes into account the computer's regional settings. While in general this is a good approach, I'm having problems in formatting SQL queries, for instance: CString s...
Here's what I did. CString FormatQuery(LPCTSTR pszFormat, ...) { CString szLocale = setlocale(LC_NUMERIC, NULL); setlocale(LC_NUMERIC, "English"); va_list args; va_start(args, pszFormat); CString szFormatted; int nSize = (_vscprintf(pszFormat, args) + 1) * sizeof(char); _vsnprintf_s(szForma...
507,560
508,081
Adding resource file to VC6 dll
I have a number of VC 6.0 projects (dsps) which build into dlls which don't have resource files. Any idea how to add resources into an existing project? The project is due for a major release shortly and I want to add a fileversion to those dlls currently lacking one. The dlls will be recompilied before release so I'm ...
Just add a VERSIONINFO block to the resource file for the DLL. Open the .rc file, and use "Insert/Resource.../Version" and you'll get a new VERSIONINFO resource with a bunch of defaults. If the project does not already have a resource file, you can add one using "File/New.../Resource Script". If you want to roll your ...
507,884
507,905
What is the nicest way to find a specific string in vector?
For instance. I have some structure: s_Some{ std::string lable; s_some_junk some_junk; }; And a vector: std::vector<s_Some> mSome; And then I fill this vector with a lot of s_Somes. I need to find an iterator for a single s_Some in this vector, which has a specific lable. So far I just iterate through all of thi...
Option 1) If you are compelled to use the std::vector, but once the vector is filled it stays unchanged, then you could sort the vector and use the binary search. The only cost would be the sorting then and there will be no additional overhead. Searching time is logarithmic O(logN). Option 2) If you have the freedom an...