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 |
|---|---|---|---|---|
99,479 | 99,485 | Visual C++/Studio: Application configuration incorrect? | My C(++) program, written and compiled using Visual C(++)/Visual Studio, runs fine on my own machine, but refuses to run on another machine. The error message I get is "This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem."
| If you write a C++ program, it links dynamically to the C Runtime Library, or CRT for short. This library contains your printf, your malloc, your strtok, etcetera. The library is contained in the file called MSVCR80.DLL. This file is not by default installed on a Windows system, hence the application cannot run.
The so... |
99,510 | 99,532 | Does several levels of base classes slow down a class/struct in c++? | Does having several levels of base classes slow down a class? A derives B derives C derives D derives F derives G, ...
Does multiple inheritance slow down a class?
| Non-virtual function-calls have absolutely no performance hit at run-time, in accordance with the c++ mantra that you shouldn't pay for what you don't use.
In a virtual function call, you generally pay for an extra pointer lookup, no matter how many levels of inheritance, or number of base classes you have.
Of course t... |
99,552 | 99,575 | Where do "pure virtual function call" crashes come from? | I sometimes notice programs that crash on my computer with the error: "pure virtual function call".
How do these programs even compile when an object cannot be created of an abstract class?
| They can result if you try to make a virtual function call from a constructor or destructor. Since you can't make a virtual function call from a constructor or destructor (the derived class object hasn't been constructed or has already been destroyed), it calls the base class version, which in the case of a pure virtu... |
99,623 | 99,787 | How to draw in the nonclient area? | I'd like to be able to do some drawing to the right of the menu bar, in the nonclient area of a window.
Is this possible, using C++ / MFC?
| Charlie hit on the answer with WM_NCPAINT. If you're using MFC, the code would look something like this:
// in the message map
ON_WM_NCPAINT()
// ...
void CMainFrame::OnNcPaint()
{
// still want the menu to be drawn, so trigger default handler first
Default();
// get menu bar bounds
MENUBARINFO menuInfo ... |
100,221 | 100,530 | Tools for finding unused function declarations? | Whilst refactoring some old code I realised that a particular header file was full of function declarations for functions long since removed from the .cpp file. Does anyone know of a tool that could find (and strip) these automatically?
| You could if possible make a test.cpp file to call them all, the linker will flag the ones that have no code as unresolved, this way your test code only need compile and not worry about actually running.
|
100,444 | 100,501 | How to set breakpoints on future shared libraries with a command flag | I'm trying to automate a gdb session using the --command flag. I'm trying to set a breakpoint on a function in a shared library (the Unix equivalent of a DLL) . My cmds.gdb looks like this:
set args /home/shlomi/conf/bugs/kde/font-break.txt
b IA__FcFontMatch
r
However, I'm getting the following:
shlomi:~/progs/bugs-e... | Replying to myself, I'd like to give the answer that someone gave me on IRC:
(gdb) apropos pending
actions -- Specify the actions to be taken at a tracepoint
set breakpoint -- Breakpoint specific settings
set breakpoint pending -- Set debugger's behavior regarding pending breakpoints
show breakpoint -- Breakpoint spec... |
100,596 | 1,657,329 | Best resources for converting C/C++ dll headers to Delphi? | A rather comprehensive site explaining the difficulties and solutions involved in using a dll written in c/c++ and the conversion of the .h header file to delphi/pascal was posted to a mailing list I was on recently, so I thought I'd share it, and invite others to post other useful resources for this, whether they be l... | Over at Rudy's Delphi Corner, he has an excellent article about the pitfalls of converting C/C++ to Delphi. In my opinion, this is essential information when attempting this task. Here is the description:
This article is meant for everyone who
needs to translate C/C++ headers to
Delphi. I want to share some of the... |
100,854 | 100,929 | Reuse define statement from .h file in C# code | I have C++ project (VS2005) which includes header file with version number in #define directive. Now I need to include exactly the same number in twin C# project. What is the best way to do it?
I'm thinking about including this file as a resource, then parse it at a runtime with regex to recover version number, but may... | You can achieve what you want in just a few steps:
Create a MSBuild Task - http://msdn.microsoft.com/en-us/library/t9883dzc.aspx
Update the project file to include a call to the task created prior to build
The task receives a parameter with the location of the header .h file you referred. It then extracts the version... |
101,046 | 146,788 | Oracle OCI array fetch of simple data types? | I cannot understand the Oracle documentation. :-(
Does anybody know how to fetch multiple rows of simple data from Oracle via OCI?
I currently use OCIDefineByPos to define single variables (I only need to do this for simple integers -- SQLT_INT/4-byte ints) and then fetch a single row at a time with OCIStmtExecute/OCIS... | You can use OCIDefineArrayOfStruct to support fetching arrays of records. You do this by passing the base of the array to OCIDefineByPos, and use OCIDefineArrayOfStruct to tell Oracle about the size of the records (skip size). I believe that you then call OCIFetch telling it to fetch the array size.
An alternative is... |
101,267 | 102,747 | Is there any way to define a constant value to Java at compile time | When I used to write libraries in C/C++ I got into the habit of having a method to return the compile date/time. This was always a compiled into the library so would differentiate builds of the library. I got this by returning a #define in the code:
C++:
#ifdef _BuildDateTime_
char* SomeClass::getBuildDateTime() {
... | I would favour the standards based approach. Put your version information (along with other useful publisher stuff such as build number, subversion revision number, author, company details, etc) in the jar's Manifest File.
This is a well documented and understood Java specification. Strong tool support exists for c... |
101,329 | 101,583 | If classes with virtual functions are implemented with vtables, how is a class with no virtual functions implemented? | In particular, wouldn't there have to be some kind of function pointer in place anyway?
| Non virtual member functions are really just a syntactic sugar as they are almost like an ordinary function but with access checking and an implicit object parameter.
struct A
{
void foo ();
void bar () const;
};
is basically the same as:
struct A
{
};
void foo (A * this);
void bar (A const * this);
The vtable... |
101,604 | 101,640 | Converting C++ code to HTML safe | I decided to try http://www.screwturn.eu/ wiki as a code snippet storage utility. So far I am very impressed, but what irkes me is that when I copy paste my code that I want to save, '<'s and '[' (http://en.wikipedia.org/wiki/Character_encodings_in_HTML#Character_references) invariably screw up the output as the wiki i... | Surround your code in <nowiki> .. </nowiki> tags.
|
102,009 | 102,044 | When is it best to use the stack instead of the heap and vice versa? | In C++, when is it best to use the stack? When is it best to use the heap?
| Use the stack when your variable will not be used after the current function returns. Use the heap when the data in the variable is needed beyond the lifetime of the current function.
|
102,283 | 102,341 | What WPF C# Control is similar to a CWnd in C++? | What would be the best WPF control in C# (VS 2008) that you can place on a form that would allow you to do drawing similar to the "Paint" function for the CWnd class in C++? Also, that could display bitmaps, have a scroll bar, and the ability to accept user inputs (ie. MouseMove, Button Clicks, etc...). Basically all... | The UIElement is the lowest level element that supports input and drawing. Although, using WPF, you really have to do a lot less manual drawing. Are you sure that you need to do this? Also, the scroll bar will never be inherit in your element. If you need scrolling behavior, just wrap your element in a ScrollViewer... |
102,459 | 102,529 | Why does std::stack use std::deque by default? | Since the only operations required for a container to be used in a stack are:
back()
push_back()
pop_back()
Why is the default container for it a deque instead of a vector?
Don't deque reallocations give a buffer of elements before front() so that push_front() is an efficient operation? Aren't these elements wasted s... | As the container grows, a reallocation for a vector requires copying all the elements into the new block of memory. Growing a deque allocates a new block and links it to the list of blocks - no copies are required.
Of course you can specify that a different backing container be used if you like. So if you have a stac... |
103,280 | 103,926 | Portable way to catch signals and report problem to the user | If by some miracle a segfault occurs in our program, I want to catch the SIGSEGV and let the user (possibly a GUI client) know with a single return code that a serious problem has occurred. At the same time I would like to display information on the command line to show which signal was caught.
Today our signal handle... | This table lists all of the functions that POSIX guarantees to be async-signal-safe and so can be called from a signal handler.
By using the 'write' command from this table, the following relatively "ugly" solution hopefully will do the trick:
#include <csignal>
#ifdef _WINDOWS_
#define _exit _Exit
#else
#include <uni... |
103,298 | 103,381 | How to convert a unmanaged double to a managed string? | From managed C++, I am calling an unmanaged C++ method which returns a double. How can I convert this double into a managed string?
| I assume something like
(gcnew System::Double(d))->ToString()
|
103,358 | 103,511 | C++ strings: UTF-8 or 16-bit encoding? | I'm still trying to decide whether my (home) project should use UTF-8 strings (implemented in terms of std::string with additional UTF-8-specific functions when necessary) or some 16-bit string (implemented as std::wstring). The project is a programming language and environment (like VB, it's a combination of both).
Th... | I would recommend UTF-16 for any kind of data manipulation and UI.
The Mac OS X and Win32 API uses UTF-16, same for wxWidgets, Qt, ICU, Xerces, and others.
UTF-8 might be better for data interchange and storage.
See http://unicode.org/notes/tn12/.
But whatever you choose, I would definitely recommend against std::strin... |
103,480 | 103,594 | iPhone programming - impressions, opinions? | I've been programming in C,C++,C# and a few other languages for many years, mainly for Windows and Linux but also embedded platforms. Recently started to do some iPhone programming as a side project so I'm using Apple platforms for the first time since my Apple II days. I'm wondering what other developers that are comi... | I'm in the same boat as you (somewhat). I've been developing in C# for 7 years, ever since .NET 1.0. Over the past couple weeks I've been teaching myself Cocoa and Objective-C. Here are my impressions (note for note with yours)
Agreed in that clutter can be a problem. I tend to use Spaces heavily when developing i... |
103,512 | 103,868 | Why use static_cast<int>(x) instead of (int)x? | I've heard that the static_cast function should be preferred to C-style or simple function-style casting. Is this true? Why?
| The main reason is that classic C casts make no distinction between what we call static_cast<>(), reinterpret_cast<>(), const_cast<>(), and dynamic_cast<>(). These four things are completely different.
A static_cast<>() is usually safe. There is a valid conversion in the language, or an appropriate constructor that mak... |
104,009 | 104,449 | How can I get full string value of variable in VC6 watch window? | I'm wanting to get the full value of a char[] variable in the VC6 watch window, but it only shows a truncated version. I can copy the value from a debug memory window, but that contains mixed lines of hex and string values. Surely there is a better way??
| For large strings, you're pretty much stuck with the memory window - the tooltip would truncate eventually.
Fortunately, the memory window is easy to get data from - I tend to show it in 8-byte chunks so its easy to manage, find your string data and cut&paste the lot into a blank window, then use alt+drag to select co... |
104,322 | 104,389 | How do you install Boost on MacOS? | How do you install Boost on MacOS?
Right now I can't find bjam for the Mac.
| Download MacPorts, and run the following command:
sudo port install boost
|
104,844 | 104,882 | Default Printer in Unmanaged C++ | I'm looking for a way to find the name of the Windows default printer using unmanaged C++ (found plenty of .NET examples, but no success unmanaged). Thanks.
| The following works great for printing with the win32api from C++
char szPrinterName[255];
unsigned long lPrinterNameLength;
GetDefaultPrinter( szPrinterName, &lPrinterNameLength );
HDC hPrinterDC;
hPrinterDC = CreateDC("WINSPOOL\0", szPrinterName, NULL, NULL);
In the future instead of googling "unmanaged" try googlin... |
104,959 | 105,032 | Inspecting STL containers in Visual Studio debugging | If I have a std::vector or std::map variable, and I want to see the contents, it's a big pain to see the nth element while debugging. Is there a plugin, or some trick to making it easier to watch STL container variables while debugging (VS2003/2005/2008)?
| For vectors, this thread on the msdn forums has a code snippet for setting a watch on a vector index that might help.
|
105,014 | 105,061 | Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function? | A while ago I came across some code that marked a member variable of a class with the mutable keyword. As far as I can see it simply allows you to modify a variable in a const method:
class Foo
{
private:
mutable bool done_;
public:
void doSomething() const { ...; done_ = true; }
};
Is this the on... | It allows the differentiation of bitwise const and logical const. Logical const is when an object doesn't change in a way that is visible through the public interface, like your locking example. Another example would be a class that computes a value the first time it is requested, and caches the result.
Since c++11 ... |
105,252 | 105,339 | How do I convert between big-endian and little-endian values in C++? | How do I convert between big-endian and little-endian values in C++?
For clarity, I have to translate binary data (double-precision floating point values and 32-bit and 64-bit integers) from one CPU architecture to another. This doesn't involve networking, so ntoh() and similar functions won't work here.
Note: The an... | If you're using Visual C++ do the following: You include intrin.h and call the following functions:
For 16 bit numbers:
unsigned short _byteswap_ushort(unsigned short value);
For 32 bit numbers:
unsigned long _byteswap_ulong(unsigned long value);
For 64 bit numbers:
unsigned __int64 _byteswap_uint64(unsigned __int64 ... |
106,033 | 106,101 | How do I call a .NET assembly from C/C++? | Suppose I am writing an application in C++ and C#. I want to write the low level parts in C++ and write the high level logic in C#. How can I load a .NET assembly from my C++ program and start calling methods and accessing the properties of my C# classes?
| [Guid("123565C4-C5FA-4512-A560-1D47F9FDFA20")]
public interface IConfig
{
[DispId(1)]
string Destination{ get; }
[DispId(2)]
void Unserialize();
[DispId(3)]
void Serialize();
}
[ComVisible(true)]
[Guid("12AC8095-BD27-4de8-A30B-991940666927")]
[ClassInterface(ClassInterfaceType.None)]
public s... |
106,117 | 106,170 | GCC - "expected unqualified-id before ')' token" | Please bear with me, I'm just learning C++.
I'm trying to write my header file (for class) and I'm running into an odd error.
cards.h:21: error: expected unqualified-id before ')' token
cards.h:22: error: expected `)' before "str"
cards.h:23: error: expected `)' before "r"
What does "expected unqualified-id before ')... | Your issue is your #define. You did #define Card, so now everywhere Card is seen as a token, it will be replaced.
Usually a #define Token with no additional token, as in #define Token Replace will use the value 1.
Remove the #define Card, it's making line 22 read: 1(); or ();, which is causing the complaint.
|
106,347 | 107,503 | Secure a DLL file with a license file | What is the best way to secure the use/loading of a DLL with a license file?
| A couple of things you might want to consider:
Check sum the DLL. Using a cryptographic hash function, you can store this inside the license file or inside the DLL. This provides a verification method to determined if my original DLL file is unhacked, or if it is the license file for this DLL. A few simple byte swappin... |
106,412 | 106,423 | Is there a good general method for debugging C++ macros? | In general, I occasionally have a chain of nested macros with a few preprocessor conditional elements in their definitions. These can be painful to debug since it's hard to directly see the actual code being executed.
A while ago I vaguely remember finding a compiler (gcc) flag to expand them, but I had trouble gettin... | gcc -E will output the preprocessed source to stdout.
|
106,470 | 106,796 | Changing the default settings for a console application | I would prefer that a console app would default to
multithreaded debug.
warning level 4.
build browse information.
no resource folder.
Does anyone know of any technique that would allow me to create a console app, with my desired options, without manually setting it.
| Yes, you can do that. What you want is to create your own project template. You can then select that template from the New Project wizard. I wasn't able to location documentation on how to create a project template in Visual Studio 6, but this MSDN article explains the procedure for Visual Studio 2005. Hopefully you wi... |
106,862 | 108,160 | Any experiences with Intel's Threading Building Blocks? | Intel's Threading Building Blocks (TBB) open source library looks really interesting. Even though there's even an O'Reilly Book about the subject I don't hear about a lot of people using it. I'm interested in using it for some multi-level parallel applications (MPI + threads) in Unix (Mac, Linux, etc.) environments. ... | I've introduced it into our code base because we needed a bettor malloc to use when we moved to a 16 core machine. With 8 and under it wasn't a significant issue. It has worked well for us. We plan on using the fine grained concurrent containers next. Ideally we can make use of the real meat of the product, but that re... |
107,294 | 107,301 | Change pointer to an array to get a specific array element | I understand the overall meaning of pointers and references(or at least I think i do), I also understand that when I use new I am dynamically allocating memory.
My question is the following:
If i were to use cout << &p, it would display the "virtual memory location" of p.
Is there a way in which I could manipulate this... | Sure, you can manipulate the pointer to access the different elements in the array, but you will need to manipulate the content of the pointer (i.e. the address of what p is pointing to), rather than the address of the pointer itself.
int *p = new int[3];
p[0] = 13;
p[1] = 54;
p[2] = 42;
cout << *p << ' ' << *(p+1) <<... |
107,549 | 107,564 | GCC compiling a dll with __stdcall | When we compile a dll using __stdcall inside visual studio 2008 the compiled function names inside the dll are.
FunctionName
Though when we compile the same dll using GCC using wx-dev-cpp GCC appends the number of paramers the function has, so the name of the function using Dependency walker looks like.
FunctionName@nu... | __stdcall decorates the function name by adding an underscore to the start, and the number of bytes of parameters to the end (separated by @).
So, a function:
void __stdcall Foo(int a, int b);
...would become _Foo@8.
If you list the function name (undecorated) in the EXPORTS section of your .DEF file, it is exported u... |
107,591 | 107,859 | Unit testing MFC UI applications? | How do you unit test a large MFC UI application?
We have a few large MFC applications that have been in development for many years, we use some standard automated QA tools to run basic scripts to check fundamentals, file open etc. These are run by the QA group post the daily build.
But we would like to introduce proced... | It depends on how the App is structured. If logic and GUI code is separated (MVC) then testing the logic is easy. Take a look at Michael Feathers "Humble Dialog Box" (PDF).
EDIT: If you think about it: You should very carefully refactor if the App is not structured that way. There is no other technique for testing the ... |
107,616 | 108,032 | XML-RPC: best way to handle 64-bit values? | So the official XML-RPC standard doesn't support 64-bit values. But in these modern times, 64-bit values are increasingly common.
How do you handle these? What XML-RPC extensions are the most common? What language bindings are there? I'm especially interested in Python and C++, but all information is appreciated.
| Some libraries support 64 bits extensions, indeed, but there doesn't seem to be a standard. xmlrpc-c, for example, has a so called i8 but it doesn't work with python (at least not by default).
I would recommend to either:
Convert the integer to string by hand and send it as such. XMLRPC will convert it to string anywa... |
108,047 | 108,060 | Whats the best Ribbon UI control to retro fit to a legacy MFC application build with VC2005? | What experience have you had with introducing a Ribbon style control to legacy MFC applications?
I know it exists in the new VC2008 Feature Pack, but changing compilers from VC2005 is a big deal for our source base and integration to our environment, Intel FORTRAN, ClearCase, many 3rd libraries.
There are quiet a few ... | In my projects I'm using the MFC Feature Pack in Visual Studio 2008, which is based on code from BCGSoft. Their BCGControlBar Library Professional Edition includes a ribbon control and is compatible with Visual Studio 2005.
I'm not aware of any open source ribbon control libraries for C++, though.
|
108,518 | 108,575 | RSA encryption library for C++ | I am developing a Win32 application and I would like to use an RSA encryption library. Which library would you recommend?
| I use the following library:
http://www.efgh.com/software/rsa.htm
It's public domain, compact, self contained, and does the work well.
|
108,768 | 108,781 | Needless pointer-casts in C | I got a comment to my answer on this thread:
Malloc inside a function call appears to be getting freed on return?
In short I had code like this:
int * somefunc (void)
{
int * temp = (int*) malloc (sizeof (int));
temp[0] = 0;
return temp;
}
I got this comment:
Can I just say, please don't cast the
return value... | It seems fitting I post an answer, since I left the comment :P
Basically, if you forget to include stdlib.h the compiler will assume malloc returns an int. Without casting, you will get a warning. With casting you won't.
So by casting you get nothing, and run the risk of suppressing legitimate warnings.
Much is written... |
109,129 | 109,161 | Dynamically created operators | I created a program using dev-cpp and wxwidgets which solves a puzzle.
The user must fill the operations blocks and the results blocks, and the program will solve it. I'm solving it using brute force, I generate all non-repeated 9 length number combinations using a recursive algorithm. It does it pretty fast.
Up to her... | Not sure that this is really what you're looking for but..
Any Object Oriented language such as C++ or C# will allow you to create an "Operator" base class and then to derive from this base class a "PlusOperator" or "MinusOperator" etc'. this is the standard way to avoid such case statements.
However I am not sure th... |
109,317 | 109,341 | Why use c strings in c++? | Is there any good reason to use C-strings in C++ nowadays? My textbook uses them in examples at some points, and I really feel like it would be easier just to use a std::string.
| The only reasons I've had to use them is when interfacing with 3rd party libraries that use C style strings. There might also be esoteric situations where you would use C style strings for performance reasons, but more often than not, using methods on C++ strings is probably faster due to inlining and specialization, ... |
109,449 | 109,522 | Getting a FILE* from a std::fstream | Is there a (cross-platform) way to get a C FILE* handle from a C++ std::fstream ?
The reason I ask is because my C++ library accepts fstreams and in one particular function I'd like to use a C library that accepts a FILE*.
| The short answer is no.
The reason, is because the std::fstream is not required to use a FILE* as part of its implementation. So even if you manage to extract file descriptor from the std::fstream object and manually build a FILE object, then you will have other problems because you will now have two buffered objects w... |
110,015 | 110,364 | Not getting event arguments in IHTMLElement event handler | I've added a callback to an IHTMLElement instance but when the IDispatch::Invoke is called for the event, there are never any arguments (i.e. the pDispParams->cArgs and pDispParams->cNamedArgs are always 0). For example, I add a callback for an onmouseup event. From what I can tell, a callback for this event is suppose... | Events arguments for all DOM events including onmouseup are stored in the parent window's event property (IHTMLWindow2::event)
If you don't already have the parent window cached, IHTMLElement has a document property which returns an IHTMLDocument interface. From that you can query for IHTMLDocument2 which has a parent... |
110,157 | 110,255 | How to retrieve all keys (or values) from a std::map and put them into a vector? | This is one of the possible ways I come out:
struct RetrieveKey
{
template <typename T>
typename T::first_type operator()(T keyValuePair) const
{
return keyValuePair.first;
}
};
map<int, int> m;
vector<int> keys;
// Retrieve all keys
transform(m.begin(), m.end(), back_inserter(keys), RetrieveK... | While your solution should work, it can be difficult to read depending on the skill level of your fellow programmers. Additionally, it moves functionality away from the call site. Which can make maintenance a little more difficult.
I'm not sure if your goal is to get the keys into a vector or print them to cout so I'... |
110,393 | 110,425 | TinyXML: Save document to char * or string | I'm attempting to use TinyXML to read and save from memory, instead of only reading and saving files to disk.
It seems that the documnent's parse function can load a char *. But then I need to save the document to a char * when I'm done with it. Does anyone know about this?
Edit: The printing & streaming functions aren... | I'm not familiar with TinyXML, but from the documentation it seems that by using operator << to a C++ stream (so you can use C++ string streams) or a TiXMLPrinter class you can get an STL string without using a file. See TinyXML documentation (look for the "Printing" section)
|
110,436 | 110,608 | Cleaning up Legacy Code "header spaghetti" | Any recommended practices for cleaning up "header spaghetti" which is causing extremely
slow compilation times (Linux/Unix)?
Is there any equvalent to "#pragma once" with GCC?
(found conflicting messages regarding this)
Thanks.
| Assuming you're familiar with "include guards" (#ifdef at the begining of the header..), an additional way of speeding up build time is by using external include guards.
It was discussed in "Large Scale C++ Software Design". The idea is that classic include guards, unlike #pragma once, do not spare you the preprocessor... |
110,833 | 110,856 | Dynamically importing a C++ class from a DLL | What is the correct way to import a C++ class from a DLL? We're using Visual C++.
There's the dllexport/exports.def+LoadLibrary+GetProcAddress trifecta, but it doesn't work on C++ classes, only C functions. Is this due to C++ name-mangling? How do I make this work?
| Found the solution at http://www.codeproject.com/KB/DLL/XDllPt4.aspx
Thanks for your efforts guys & girls
|
111,023 | 111,078 | How to get a full call stack in Visual Studio 2005? | How can I get a full call stack for a c++ application developed with Visual Studio 2005? I would like to have a full call stack including the code in the system libraries.
Do I have to change some settings in Visual Studio, or do I have to install additional software?
|
Get debug information for all project dependencies. This is specified under the "Configuration Properties -> C/C++ -> General" section of the project properties.
On the menu, go to "Tools -> Options" then select "Debugging -> Symbols".
Add a new symbol location (the folder icon) that points to Microsoft's free symbol... |
111,391 | 111,399 | Is it a problem if multiple different accepting sockets use the same OpenSSL context? | Is it OK if the same OpenSSL context is used by several different accepting sockets?
In particular I'm using the same boost::asio::ssl::context with 2 different listening sockets.
| Yep, SSL_CTX--which I believe is the underlying data structure--is just a global data structure used by your program. From ssl(3):
SSL_CTX (SSL Context)
That's the global context structure which is created by a server or client once per program life-time and which holds mainly default values for the SSL structures whi... |
111,415 | 111,479 | Strange call stack, could it be problem in asio's usage of openssl? | I have this strange call stack and I am stumped to understand why.
It seems to me that asio calls open ssl's read and then gets a negative return value (-37) .
Asio seems to then try to use it inside the memcpy function.
The function that causes this call stack is used hunderds of thousands of times without this error... | A quick look at evp_lib.c shows that it tries to pull a length from the cipher context, and in your case gets a Very Bad Value(tm). It then uses this value to copy a string (which does the memcpy). My guess is something is trashing your cipher, be it a thread safety problem, or a reading more bytes into a buffer than a... |
111,478 | 111,531 | Why is it wrong to use std::auto_ptr<> with standard containers? | Why is it wrong to use std::auto_ptr<> with standard containers?
| The C++ Standard says that an STL element must be "copy-constructible" and "assignable." In other words, an element must be able to be assigned or copied and the two elements are logically independent. std::auto_ptr does not fulfill this requirement.
Take for example this code:
class X
{
};
std::vector<std::auto_ptr<... |
111,630 | 111,661 | Using the Window API, how do I ensure controls retain a native appearance? | Some of the controls I've created seem to default to the old Windows 95 theme, how do I prevent this? Here's an example of a button that does not retain the Operating System's native appearance (I'm using Vista as my development environment):
HWND button = CreateWindowEx(NULL, L"BUTTON", L"OK", WS_VISIBLE | WS_CHILD | ... | I believe it has got nothing to do with your code, but you need to set up a proper manifest file to get the themed controls.
Some info here: @msdn.com and here: @blogs.msdn.com
You can see a difference between application with and without manifest here: heaventools.com
|
112,085 | 112,100 | Is this C++ structure initialization trick safe? | Instead of having to remember to initialize a simple 'C' structure, I might derive from it and zero it in the constructor like this:
struct MY_STRUCT
{
int n1;
int n2;
};
class CMyStruct : public MY_STRUCT
{
public:
CMyStruct()
{
memset(this, 0, sizeof(MY_STRUCT));
}
};
This trick is often... | PREAMBLE:
While my answer is still Ok, I find litb's answer quite superior to mine because:
It teaches me a trick that I did not know (litb's answers usually have this effect, but this is the first time I write it down)
It answers exactly the question (that is, initializing the original struct's part to zero)
So plea... |
112,277 | 112,302 | Best introduction to C++ template metaprogramming? | Static metaprogramming (aka "template metaprogramming") is a great C++ technique that allows the execution of programs at compile-time. A light bulb went off in my head as soon as I read this canonical metaprogramming example:
#include <iostream>
using namespace std;
template< int n >
struct factorial { enum { ret = ... | [Answering my own question]
The best introductions I've found so far are chapter 10, "Static Metaprogramming in C++" from Generative Programming, Methods, Tools, and Applications by Krzysztof Czarnecki and Ulrich W. Eisenecker, ISBN-13: 9780201309775; and chapter 17, "Metaprograms" of C++ Templates: The Complete Guide ... |
112,433 | 113,560 | Should I use #define, enum or const? | In a C++ project I'm working on, I have a flag kind of value which can have four values. Those four flags can be combined. Flags describe the records in database and can be:
new record
deleted record
modified record
existing record
Now, for each record I wish to keep this attribute, so I could use an enum:
enum { xNe... | Combine the strategies to reduce the disadvantages of a single approach. I work in embedded systems so the following solution is based on the fact that integer and bitwise operators are fast, low memory & low in flash usage.
Place the enum in a namespace to prevent the constants from polluting the global namespace.
nam... |
112,612 | 112,737 | Are C++ non-type parameters to (function) templates ordered? | I am hosting SpiderMonkey in a current project and would like to have template functions generate some of the simple property get/set methods, eg:
template <typename TClassImpl, int32 TClassImpl::*mem>
JSBool JS_DLL_CALLBACK WriteProp(JSContext* cx, JSObject* obj, jsval id, jsval* vp)
{
if (TClassImpl* pImpl = (TCl... | Pretty sure VC++ has "issues" here. Comeau and g++ 4.2 are both happy with the following program:
struct X
{
int i;
void* p;
};
template<int X::*P>
void foo(X* t)
{
t->*P = 0;
}
template<void* X::*P>
void foo(X* t)
{
t->*P = 0;
}
int main()
{
X x;
foo<&X::i>(&x);
foo<&X::p>(&x);
}
VC++ ... |
112,738 | 113,134 | How does boost bind work behind the scenes in general? | Without spending a long time reviewing the boost source code, could someone give me a quick rundown of how boost bind is implemented?
| I like this piece of the bind source:
template<class R, class F, class L> class bind_t
{
public:
typedef bind_t this_type;
bind_t(F f, L const & l): f_(f), l_(l) {}
#define BOOST_BIND_RETURN return
#include <boost/bind/bind_template.hpp>
#undef BOOST_BIND_RETURN
};
Tells you almost all you need to know, re... |
112,831 | 112,834 | How to get a stack trace when C++ program crashes? (using msvc8/2005) | Sometimes my c++ program crashes in debug mode, and what I got is a message box saying that an assertion failed in some of the internal memory management routines (accessing unallocated memory etc.). But I don't know where that was called from, because I didn't get any stack trace. How do I get a stack trace or at leas... | If you have a crash, you can get information about where the crash happened whether you have a debug or a release build. And you can see the call stack even if you are on a computer that does not have the source code.
To do this you need to use the PDB file that was built with your EXE. Put the PDB file inside the s... |
112,897 | 113,073 | Determining the size of a file larger than 4GB | The code currently does this and the fgetpos does handle files larger than 4GB but the seek returns an error, so any idea how to seek to the end of a file > 4GB?
fpos_t currentpos;
sok=fseek(fp,0,SEEK_END);
assert(sok==0,"Seek error!");
fgetpos(fp,¤tpos);
m_filesize=currentpos;
| If you're in Windows, you want GetFileSizeEx (MSDN). The return value is a 64bit int.
On linux stat64 (manpage) is correct. fstat if you're working with a FILE*.
|
112,946 | 112,961 | Accessing files across the windows network with near MAX_PATH length | I'm using C++ and accessing a UNC path across the network. This path is slightly greater than MAX_PATH. So I cannot obtain a file handle.
But if I run the program on the computer in question, the path is not greater than MAX_PATH. So I can get a file handle. If I rename the file to have less characters (minus length... | I recall that there is some feature like using \\?\ at the start of the path to get around the MAX_PATH limit. Here is a reference on MSDN:
http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx
For remote machines, you would use a path name such as: \\?\unc\server\share\path\file. The \\?\unc\ is the special pre... |
113,033 | 113,039 | How to use one object's method to update another object's attribute? | I have three (C++) classes: Player, Hand, and Card.
Player has a member, hand, that holds a Hand. It also has a method, getHand(), that returns the contents of hand.
Hand Player::getHand() {
return hand;
}
Hand has a method, addCard(Card c), that adds a card to the hand.
I want to do this:
player1.getHand().addCar... | If getHand() is not returning a reference you will be in trouble.
|
113,150 | 113,155 | What is the cost of using a pointer to member function vs. a switch? | I have the following situation:
class A
{
public:
A(int whichFoo);
int foo1();
int foo2();
int foo3();
int callFoo(); // cals one of the foo's depending on the value of whichFoo
};
In my current implementation I save the value of whichFoo in a data member in the constructor and use a switch in cal... | How sure are you that calling a member function via a pointer is slower than just calling it directly? Can you measure the difference?
In general, you should not rely on your intuition when making performance evaluations. Sit down with your compiler and a timing function, and actually measure the different choices. You... |
113,288 | 113,294 | Multiple services from the same executable | I've written a small service (plain Win32) and I'd like to know if it's possible to run multiple instances of it when multiple users are logged on.
Basically, let's say we've got UserA and UserB for UserA the service would log on as "domain\UserA" and for UserB the service would log on as "domain\UserB" - this is from ... | Win32 services are designed to be system-wide, and start running before any user is logged in. If you want something to run on a per-user basis, it's probably better to design it as a regular application and run it from the user's Startup group.
|
113,385 | 113,399 | Declare an object even before that class is created | Is there anyway to declare an object of a class before the class is created in C++? I ask because I am trying to use two classes, the first needs to have an instance of the second class within it, but the second class also contains an instance of the first class. I realize that you may think I might get into an infin... | You can't do something like this:
class A {
B b;
};
class B {
A a;
};
The most obvious problem is the compiler doesn't know how to large it needs to make class A, because the size of B depends on the size of A!
You can, however, do this:
class B; // this is a "forward declaration"
class A {
B *b;
};
class ... |
113,424 | 113,442 | Converting Reverse Polish Notation | Is there any way to interpret Reverse Polish Notation into "normal" mathematical notation when using either C++ or C#? I work for an engineering firm, so they use RPN occasionally and we need a way to convert it. Any suggestions?
| Yes. Think of how a RPN calculator works. Now, instead of calculating the value, instead you add the operation to the tree. So, for example, 2 3 4 + *, when you get to the +, then rather than putting 7 on the stack, you put (+ 3 4) on the stack. And similarly when you get to the * (your stack will look like 2 (+ 3 4) *... |
113,818 | 113,879 | Class library with support for several persistence strategies | I am developing a C++ class library containing domain model classes, and I would like to add support for instantiating these classes from various persistence mechanisms, i.e. databases and file. The user of the class library should be given an interface(?) against which to program a class that can transfer the data fro... | C++ supports multiple inheritance so you can have a generic persistence API and inherit a persistence mechanism. This would still have to use introspection to get out the class metadata, but you would still have this issue with any persistence layer.
Alternatively you could do something similar but use the metadata to... |
113,830 | 113,843 | Performance penalty for working with interfaces in C++? | Is there a runtime performance penalty when using interfaces (abstract base classes) in C++?
| Short Answer: No.
Long Answer:
It is not the base class or the number of ancestors a class has in its hierarchy that affects it speed. The only thing is the cost of a method call.
A non virtual method call has a cost (but can be inlined)
A virtual method call has a slightly higher cost as you need to look up the method... |
113,992 | 113,995 | C++ Binary operators order of precedence | In what order are the following parameters tested (in C++)?
if (a || b && c)
{
}
I've just seen this code in our application and I hate it, I want to add some brackets to just clarify the ordering. But I don't want to add the brackets until I know I'm adding them in the right place.
Edit: Accepted Answer & Follow Up
T... | From here:
a || (b && c)
This is the default precedence.
|
114,085 | 114,102 | Fast String Hashing Algorithm with low collision rates with 32 bit integer | I have lots of unrelated named things that I'd like to do quick searches against. An "aardvark" is always an "aardvark" everywhere, so hashing the string and reusing the integer would work well to speed up comparisons. The entire set of names is unknown (and changes over time). What is a fast string hashing algorithm t... | One of the FNV variants should meet your requirements. They're fast, and produce fairly evenly distributed outputs.
|
114,180 | 114,189 | Pointer vs. Reference | What would be better practice when giving a function the original variable to work with:
unsigned long x = 4;
void func1(unsigned long& val) {
val = 5;
}
func1(x);
or:
void func2(unsigned long* val) {
*val = 5;
}
func2(&x);
IOW: Is there any reason to pick one over another?
| My rule of thumb is:
Use pointers if you want to do pointer arithmetic with them (e.g. incrementing the pointer address to step through an array) or if you ever have to pass a NULL-pointer.
Use references otherwise.
|
114,211 | 114,221 | Boost shared_ptr container question | Let's say I have a container (std::vector) of pointers used by a multi-threaded application. When adding new pointers to the container, the code is protected using a critical section (boost::mutex). All well and good. The code should be able to return one of these pointers to a thread for processing, but another sep... | For the threading safety of boost::shared_ptr you should check this link. It's not guarantied to be safe, but on many platforms it works. Modifying the std::vector is not safe AFAIK.
|
114,238 | 114,264 | Difference between managed C++ and C++ | The second question is: When do I use what of these two?
| When not specified, C++ is unmanaged C++, compiled to machine code. In unmanaged C++ you must manage memory allocation manually.
Managed C++ is a language invented by Microsoft, that compiles to bytecode run by the .NET Framework. It uses mostly the same syntax as C++ (hence the name) but is compiled in the same way as... |
114,819 | 114,883 | Getting a vector<Derived*> into a function that expects a vector<Base*> | Consider these classes.
class Base
{
...
};
class Derived : public Base
{
...
};
this function
void BaseFoo( std::vector<Base*>vec )
{
...
}
And finally my vector
std::vector<Derived*>derived;
I want to pass derived to function BaseFoo, but the compiler doesn't let me. How do I solve this, without copying... | vector<Base*> and vector<Derived*> are unrelated types, so you can't do this. This is explained in the C++ FAQ here.
You need to change your variable from a vector<Derived*> to a vector<Base*> and insert Derived objects into it.
Also, to avoid copying the vector unnecessarily, you should pass it by const-reference, not... |
114,874 | 114,903 | How to determine the value of socket listen() backlog parameter? | How should I determine what to use for a listening socket's backlog parameter? Is it a problem to simply specify a very large number?
| From the docs:
A value for the backlog of SOMAXCONN is a special constant that instructs the underlying service provider responsible for socket s to set the length of the queue of pending connections to a maximum reasonable value.
|
115,115 | 115,157 | Test Automation with Embedded Hardware | Has anyone had success automating testing directly on embedded hardware?
Specifically, I am thinking of automating a battery of unit tests for hardware layer modules. We need to have greater confidence in our hardware layer code. A lot of our projects use interrupt driven timers, ADCs, serial io, serial SPI devices (fl... | Sure. In the automotive industry we use $100,000 custom built testers for each new product to verify the hardware and software are operating correctly.
The developers, however, also build a cheaper (sub $1,000) tester that includes a bunch of USB I/O, A/D, PWM in/out, etc and either use scripting on the workstation, o... |
115,703 | 115,735 | Storing C++ template function definitions in a .CPP file | I have some template code that I would prefer to have stored in a CPP file instead of inline in the header. I know this can be done as long as you know which template types will be used. For example:
.h file
class foo
{
public:
template <typename T>
void do(const T& t);
};
.cpp file
template <typename T>
voi... | The problem you describe can be solved by defining the template in the header, or via the approach you describe above.
I recommend reading the following points from the C++ FAQ Lite:
Why can’t I separate the definition of my templates class from its declaration and put it inside a .cpp file?
How can I avoid linker er... |
116,002 | 116,049 | Pointers and containers | We all know that RAW pointers need to be wrapped in some form of smart pointer to get Exception safe memory management. But when it comes to containers of pointers the issue becomes more thorny.
The std containers insist on the contained object being copyable so this rules out the use of std::auto_ptr, though you can s... | Boost pointer containers have strict ownership over the resources they hold. A std::vector<boost::shared_ptr<X>> has shared ownership. There are reasons why that may be necessary, but in case it isn't, I would default to boost::ptr_vector<X>. YMMV.
|
116,469 | 116,510 | Cleaning a string of punctuation in C++ | Ok so before I even ask my question I want to make one thing clear. I am currently a student at NIU for Computer Science and this does relate to one of my assignments for a class there. So if anyone has a problem read no further and just go on about your business.
Now for anyone who is willing to help heres the situat... | The problem with empty entries is in your while loop. If you get an empty string, you clean the next one, and add it without checking. Try changing:
not_s = "";
clean_entry(s, not_s);
if((int)not_s.length() == 0)
{
input >> s;
clean_entry(s, not_s);
}
mapz[not_s]++; //increment occurence
inp... |
116,485 | 116,636 | Fastest way to see how many bytes are equal between fixed length arrays | I have 2 arrays of 16 elements (chars) that I need to "compare" and see how many elements are equal between the two.
This routine is going to be used millions of times (a usual run is about 60 or 70 million times), so I need it to be as fast as possible. I'm working on C++ (C++Builder 2007, for the record)
Right now, I... | UPDATE: This answer has been modified to make my comments match the source code provided below.
There is an optimization available if you have the capability to use SSE2 and popcnt instructions.
16 bytes happens to fit nicely in an SSE register. Using c++ and assembly/intrinsics, load the two 16 byte arrays into xmm ... |
116,646 | 116,714 | data access object pattern implementation | I would like to implement a data access object pattern in C++, but preferably without using multiple inheritance and/or boost (which my client does not like).
Do you have any suggestions?
| OTL (otl.sourceforge.net) is an excellent C++ database library. It's a single include file so doesn't have all the complexity associated (rightly or wrongly!) with Boost.
In terms of the DAO itself, you have many options. The simplest that hides the database implementation is just to use C++ style interfaces and impl... |
116,687 | 116,741 | Problem Linking "static" Methods in C++ | I want to call a few "static" methods of a CPP class defined in a different file but I'm having linking problems. I created a test-case that recreates my problem and the code for it is below.
(I'm completely new to C++, I come from a Java background and I'm a little familiar with C.)
// CppClass.cpp
#include <iostream>... | It's obvious you come from a Java background because you haven't yet grasped the concept of header files. In Java the process of defining something is usually in one piece. You declare and define at the same time. In C/C++ it's a two-step process. Declaring something tells the compiler "something exists with this type,... |
117,110 | 117,145 | When have we any practical use for hierarchical namespaces in c++? | I can understand the use for one level of namespaces. But 3 levels of namespaces. Looks insane. Is there any practical use for that? Or is it just a misconception?
| Hierarchical namespaces do have a use in that they allow progressively more refined definitions. Certainly a single provider may produce two classes with the same name. Often the first level is occupied by the company name, the second specifies the product, the third (and possibly more) my provide the domain.
There are... |
117,293 | 117,308 | Use of 'const' for function parameters | How far do you go with const? Do you just make functions const when necessary or do you go the whole hog and use it everywhere? For example, imagine a simple mutator that takes a single boolean parameter:
void SetValue(const bool b) { my_val_ = b; }
Is that const actually useful? Personally I opt to use it extensiv... | The reason is that const for the parameter only applies locally within the function, since it is working on a copy of the data. This means the function signature is really the same anyways. It's probably bad style to do this a lot though.
I personally tend to not use const except for reference and pointer parameters. F... |
117,693 | 118,095 | How to initialize Pango under Win32? | Having downloaded Pango and GLib from the GTK+ Project's Win32 downloads page and having created and configured a Win32 project under Visual Studio 2005 so it points to the proper lib and include directories, how do you initialize Pango for rendering to a Win32 window?
Should the first call be to pango_win32_get_contex... | Pango is a GObject based library. As such, you need to make sure that the glib dynamic type system is initialized before using any of its functionality. This can be done by calling g_type_init() (either directly or indirectly via something like gtk_init()). Could this be your problem?
|
117,708 | 117,760 | nonvirtual interface idiom for more than two levels of inheritance? | The non-virtual interface idiom describes how the virtual methods are nonpublic customisation points, and public methods are nonvirtual to allow the base class to control at all times how the customisation points are called.
This is an elegant idiom and I like to use it, but how does it work if the derived class is a ... | It works, because the derived class can override a private virtual function of a base class, even if the base class function overrides its base class function.
This is perfectly legal:
class Parent
{
public:
int foo() {return bar();} // the non-virtual public interface
private
virtual int bar();
};
class Child : ... |
117,755 | 118,442 | Getting a char* from a _variant_t in optimal time | Here's the code I want to speed up. It's getting a value from an ADO recordset and converting it to a char*. But this is slow. Can I skip the creation of the _bstr_t?
_variant_t var = pRs->Fields->GetItem(i)->GetValue();
if (V_VT(&var) == VT_BSTR)
{
... | The first 4 bytes of the BSTR contain the length. You can loop through and get every other character if unicode or every character if multibyte. Some sort of memcpy or other method would work too. IIRC, this can be faster than W2A or casting (LPCSTR)(_bstr_t)
|
117,844 | 117,870 | Converting string of 1s and 0s into binary value | I'm trying to convert an incoming sting of 1s and 0s from stdin into their respective binary values (where a string such as "11110111" would be converted to 0xF7). This seems pretty trivial but I don't want to reinvent the wheel so I'm wondering if there's anything in the C/C++ standard libs that can already perform su... | #include <stdio.h>
#include <stdlib.h>
int main(void) {
char * ptr;
long parsed = strtol("11110111", & ptr, 2);
printf("%lX\n", parsed);
return EXIT_SUCCESS;
}
For larger numbers, there as a long long version, strtoll.
|
118,199 | 118,311 | C++ Thread, shared data | I have an application where 2 threads are running... Is there any certanty that when I change a global variable from one thread, the other will notice this change?
I don't have any syncronization or Mutual exclusion system in place... but should this code work all the time (imagine a global bool named dataUpdated):
Th... | Yes. No. Maybe.
First, as others have mentioned you need to make dataUpdated volatile; otherwise the compiler may be free to lift reading it out of the loop (depending on whether or not it can see that doSomethingElse doesn't touch it).
Secondly, depending on your processor and ordering needs, you may need memory barri... |
118,547 | 118,606 | Creating a ZIP file on Windows (XP/2003) in C/C++ | I am looking for a way to create a ZIP file from a folder in Windows C/C++ APIs. I can find the way to do this in VBScript using the Shell32.Application CopyHere method, and I found a tutorial explaining how to do it in C# also, but nothing for the C API (C++ is fine too, project already uses MFC).
I'd be really gratef... | EDIT: This answer is old, but I cannot delete it because it was accepted. See the next one
https://stackoverflow.com/a/121720/3937
----- ORIGINAL ANSWER -----
There is sample code to do that here
[EDIT: Link is now broken]
http://www.eggheadcafe.com/software/aspnet/31056644/using-shfileoperation-to.aspx
Make sure you ... |
118,630 | 118,664 | What is the best signature for overloaded arithmetic operators in C++? | I had assumed that the canonical form for operator+, assuming the existence of an overloaded operator+= member function, was like this:
const T operator+(const T& lhs, const T& rhs)
{
return T(lhs) +=rhs;
}
But it was pointed out to me that this would also work:
const T operator+ (T lhs, const T& rhs)
{
return... | With the edited question, the first form would be preferred. The compiler will more likely optimize the return value (you could verify this by placing a breakpoint in the constructor for T). The first form also takes both parameters as const, which would be more desirable.
Research on the topic of return value optimi... |
118,659 | 175,086 | How do I use Qt and SDL together? | I am building a physics simulation engine and editor in Windows. I want to build the editor part using Qt and I want to run the engine using SDL with OpenGL.
My first idea was to build the editor using only Qt and share as much code with the engine (the resource manager, the renderer, the maths). But, I would also like... | While you might get it to work like first answer suggest you will likely run into problems due to threading. There is no simple solutions when it comes to threading, and here you would have SDL Qt and OpenGL mainloop interacting. Not fun.
The easiest and sanest solution would be to decouple both parts. So that SDL and ... |
118,727 | 118,734 | Compile errors in mshtml.h compiling with VS2008 | I'm in the process of moving one of our projects from VS6 to VS2008 and I've hit the following compile error with mshtml.h:
1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(5272) : error C2143: syntax error : missing '}' before 'constant'
1>c:\program files\microsoft sdks\windows\v6.0a\include\mshtml.h(... | There is probably a #define changing something. Try running just the preprocessor on your .cpp and generating a .i file. The setting is in the project property pages.
EDIT: Also, you can get the answer from that other expert site by scrolling to the bottom of the page. They have to do that or Google will take them o... |
118,774 | 119,553 | Is there a clean way to prevent windows.h from creating a near & far macro? | Deep down in WinDef.h there's this relic from the segmented memory era:
#define far
#define near
This obviously causes problems if you attempt to use near or far as variable names. Any clean workarounds? Other then renaming my variables?
| You can safely undefine them, contrary to claims from others. The reason is that they're just macros's. They only affect the preprocessor between their definition and their undefinition. In your case, that will be from early in windows.h to the last line of windows.h. If you need extra windows headers, you'd include th... |
118,945 | 118,968 | Best C/C++ Network Library | I haven't done work in C/C++ for a little bit and was just wondering what people's favorite cross platform libraries are to use.
I'm looking for something that is a good quick and dirty library as well as a library that is a little more robust. Often those are two different libraries and that's okay.
| Aggregated List of Libraries
Boost.Asio is really good.
Asio is also available as a stand-alone library.
ACE is also good, a bit more mature and has a couple of books to support it.
C++ Network Library
POCO
Qt
Raknet
ZeroMQ (C++)
nanomsg (C Library)
nng (C Library)
Berkeley Sockets
libevent
Apache APR
yield
Winsock2(W... |
119,098 | 119,194 | Which C I/O library should be used in C++ code? | In new C++ code, I tend to use the C++ iostream library instead of the C stdio library.
I've noticed some programmers seem to stick to stdio, insisting that it's more portable.
Is this really the case? What is better to use?
| To answer the original question:
Anything that can be done using stdio can be done using the iostream library.
Disadvantages of iostreams: verbose
Advantages of iostreams: easy to extend for new non POD types.
The step forward the C++ made over C was type safety.
iostreams was designed to be explicitly type safe. ... |
119,114 | 119,148 | Conditional compilation for working at home | I code C++ using MS Dev Studio and I work from home two days per week. I use CVS to keep my sources synchronized between the two computers but there are difference between the environments the machines are in.
Can anyone suggest a way I can conditionally modify constants in my code depending on whether I am compiling o... | On your home and work machines, set an environment variable LOCATION that is either "1" for home or "2" for work.
Then in the preprocessor options, add a preprocessor define /DLOCATION=$(LOCATION). This will evaluate to either the "home" or "work" string that you set in the environment variable.
Then in your code:
#if ... |
119,123 | 119,128 | Why isn't sizeof for a struct equal to the sum of sizeof of each member? | Why does the sizeof operator return a size larger for a structure than the total sizes of the structure's members?
| This is because of padding added to satisfy alignment constraints. Data structure alignment impacts both performance and correctness of programs:
Mis-aligned access might be a hard error (often SIGBUS).
Mis-aligned access might be a soft error.
Either corrected in hardware, for a modest performance-degradation.
Or c... |
119,414 | 119,522 | How would you unittest a memory allocator? | There's a lot of people today who sell unittesting as bread-and-butter of development. That might even work for strongly algorithmically-oriented routines. However, how would you unit-test, for example, a memory allocator (think malloc()/realloc()/free()). It's not hard to produce a working (but absolutely useless) m... | Highly testable code tends to be structured differently than other code.
You describe several tasks that you want an allocator to do:
coalescing free blocks
reusing free blocks on next
allocations
returning excess free memory to the
system
asserting that the allocation policy
(e.g. first-fit) really is respected
Whil... |
119,492 | 119,498 | Difference between Visual C++ 2008 and 2005 | I couldn't find any useful information on Microsoft's site, so here is the question: has the compiler in Visual C++ 2008 been improved significantly since the 2005 version? I'm especially looking for better optimization.
| Straight from the horses mouth....
http://msdn.microsoft.com/en-us/library/bb384632.aspx
|
119,578 | 119,752 | Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE | What is the best way to disable the warnings generated via _CRT_SECURE_NO_DEPRECATE that allows them to be reinstated with ease and will work across Visual Studio versions?
| If you don't want to pollute your source code (after all this warning presents only with Microsoft compiler), add _CRT_SECURE_NO_WARNINGS symbol to your project settings via "Project"->"Properties"->"Configuration properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions".
Also you can define it just before you i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.