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 ...
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 l...
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...
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 Depend...
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;...
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 h...
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); g...
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...
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 affecte...
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 doc...
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 programma...
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() { vecto...
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 temporar...
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-update...
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 i...
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 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 ...
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 cr...
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++ (mention...
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 part...
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 UserCon...
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....
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...
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 you...
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 lo...
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 p...
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 remem...
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 fi...
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 ...
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 > perfec...
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 a...
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 ...
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...
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 t...
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 = winOpacit...
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_XRESOLUTI...
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 ...
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 ...
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, ...
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 f...
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::phoen...
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 s...
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 ~Re...
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 poi...
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 0...
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(TRANS...
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 t...
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 t...
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 s...
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 ...
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...
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 operato...
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 ...
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, ...
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: ...
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 << "* "; } ...
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...
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...
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 lib...
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 = M...
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(xy...
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 t...
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 { stat...
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, o...
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...
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 fi...
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 ...
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 CommandL...
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...
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 whic...
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...
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_E...
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 ...
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?...
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 o...
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,...
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...
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_...
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 thi...
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...
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 mi...
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 a...
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 w...
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 s...
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, ...
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...
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 fr...
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 ...
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 *cur...
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 e...
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 alignme...
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 no...
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...
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, ...
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 solu...
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 pointe...
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 ...
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 u...
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 refer...
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 appl...
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...
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 t...
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, memor...
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; }...
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 th...
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.... #en...
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 "optimisati...
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 ...
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 ); ...
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 val...
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 { voi...
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 bas...
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 di...
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 fil...
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 w...
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 mangl...
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 power...
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 n...
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 d...
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 { ...
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 cr...
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...
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: // ...
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 kno...
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, ...
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 istringstrea...
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 co...
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...
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 i...
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 crea...
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, IA...
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: virt...
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("inpu...
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....
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 bo...
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_nex...
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 ); ...
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)...
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...
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 t...
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 ab...
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 refere...