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 |
|---|---|---|---|---|
74,326 | 74,491 | How should I detect unnecessary #include files in a large C++ project? | I am working on a large C++ project in Visual Studio 2008, and there are a lot of files with unnecessary #include directives. Sometimes the #includes are just artifacts and everything will compile fine with them removed, and in other cases classes could be forward declared and the #include could be moved to the .cpp fi... | While it won't reveal unneeded include files, Visual studio has a setting /showIncludes (right click on a .cpp file, Properties->C/C++->Advanced) that will output a tree of all included files at compile time. This can help in identifying files that shouldn't need to be included.
You can also take a look at the pimpl i... |
74,350 | 81,662 | How to fix an MFC Painting Glitch? | I'm trying to implement some drag and drop functionality for a material system being developed at my work. Part of this system includes a 'Material Library' which acts as a repository, divided into groups, of saved materials on the user's hard drive.
As part of some UI polish, I was hoping to implement a 'highlight' ty... | Thanks for the answers guys, ajryan, you seem to always come up with help for my questions so extra thanks.
Thankfully this time the answer was fairly straightforward....
ImageList_DragShowNolock(FALSE);
m_pDragDropTargetWnd->SendMessage(WM_USER_DRAG_DROP_OBJECT_DRAG_ENTER, (WPARAM)pDragDropObject, (LPARAM)(&dragDropPo... |
74,451 | 81,493 | Getting actual file name (with proper casing) on Windows | Windows file system is case insensitive. How, given a file/folder name (e.g. "somefile"), I get the actual name of that file/folder (e.g. it should return "SomeFile" if Explorer displays it so)?
Some ways I know, all of which seem quite backwards:
Given the full path, search for each folder on the path (via FindFirstF... | And hereby I answer my own question, based on original answer from cspirz.
Here's a function that given absolute, relative or network path, will return the path with upper/lower case as it would be displayed on Windows. If some component of the path does not exist, it will return the passed in path from that point.
It ... |
74,696 | 75,346 | On Windows Mobile device, what is the best way to display an OK button instead of the X button? | I have a C++ program that when run, by default, displays the X in the upper right corner. Clicking X, minimizes the program. I've added code using the SHInitDialog function to change the X to OK, so that clicking OK exits the program.
My question: Is there a better method that applies to the window, since SHInitDialog ... | With Windows Mobile 5.0 and higher, using the CreateWindowEx function passing it WS_EX_CAPTIONOKBTN for the extended style works.
@ctacke SHDoneButton may have also worked but I wanted to change the main window without handling it like a dialogbox, which is basically what SHInitDialog is doing.
|
75,180 | 75,202 | How to display a dynamically allocated array in the Visual Studio debugger? | If you have a statically allocated array, the Visual Studio debugger can easily display all of the array elements. However, if you have an array allocated dynamically and pointed to by a pointer, it will only display the first element of the array when you click the + to expand it. Is there an easy way to tell the de... | Yes, simple.
say you have
char *a = new char[10];
writing in the debugger:
a,10
would show you the content as if it were an array.
|
75,191 | 87,648 | What is an unsigned char? | In C/C++, what an unsigned char is used for? How is it different from a regular char?
| In C++, there are three distinct character types:
char
signed char
unsigned char
If you are using character types for text, use the unqualified char:
it is the type of character literals like 'a' or '0' (in C++ only, in C their type is int)
it is the type that makes up C strings like "abcde"
It also works out as a ... |
75,213 | 75,262 | scope resolution operator without a scope | In C++, what is the purpose of the scope resolution operator when used without a scope? For instance:
::foo();
| It means global scope. You might need to use this operator when you have conflicting functions or variables in the same scope and you need to use a global one. You might have something like:
void bar(); // this is a global function
class foo {
void some_func() { ::bar(); } // this function is calling the g... |
75,385 | 75,596 | Make VS compiler catch signed/unsigned assignments? | The Visual Studio compiler does not seem to warn on signed/unsigned assignments, only on comparisons. For example the code below will generate a warning on the if statement but not the initial assignments.
Is there anyway to make it catch these? I'm already at W4 but thought (hoped) there may be another setting somewhe... | You need to enable warning 4365 to catch the assignment.
That might be tricky - you need to enable ALL warnings - use /Wall which enables lots of warnings, so you may have some trouble seeing the warning occur, but it does.
|
75,432 | 75,452 | How can I prevent URLDownloadToFile from retrieving from the cache? | I am using URLDownloadToFile to retrieve a file from a website. Subsequent calls return the original file rather than an updated version. I assume it is retrieving a cached version.
| Call DeleteUrlCacheEntry with the same URL just prior to calling URLDownloadToFile.
You will need to link against Wininet.lib
|
75,701 | 78,235 | What happens to global variables declared in a DLL? | Let's say I write a DLL in C++, and declare a global object of a class with a non-trivial destructor. Will the destructor be called when the DLL is unloaded?
| In a Windows C++ DLL, all global objects (including static members of classes) will be constructed just before the calling of the DllMain with DLL_PROCESS_ATTACH, and they will be destroyed just after the call of the DllMain with DLL_PROCESS_DETACH.
Now, you must consider three problems:
0 - Of course, global non-const... |
75,722 | 75,755 | Is there a better deterministic disposal pattern than nested "using"s? | In C#, if I want to deterministically clean up non-managed resources, I can use the "using" keyword. But for multiple dependent objects, this ends up nesting further and further:
using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
{
using (BufferedStream bs = new BufferedStream(fs))
{
... | You don't have to nest with multiple usings:
using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
// all three get disposed when you're done
}
|
76,796 | 76,844 | General guidelines to avoid memory leaks in C++ | What are some general tips to make sure I don't leak memory in C++ programs? How do I figure out who should free memory that has been dynamically allocated?
| Instead of managing memory manually, try to use smart pointers where applicable.
Take a look at the Boost lib, TR1, and smart pointers.
Also smart pointers are now a part of C++ standard called C++11.
|
77,005 | 77,336 | How to automatically generate a stacktrace when my program crashes | I am working on Linux with the GCC compiler. When my C++ program crashes I would like it to automatically generate a stacktrace.
My program is being run by many different users and it also runs on Linux, Windows and Macintosh (all versions are compiled using gcc).
I would like my program to be able to generate a stack ... | For Linux and I believe Mac OS X, if you're using gcc, or any compiler that uses glibc, you can use the backtrace() functions in execinfo.h to print a stacktrace and exit gracefully when you get a segmentation fault. Documentation can be found in the libc manual.
Here's an example program that installs a SIGSEGV handl... |
77,013 | 77,049 | Which open-source C++ database GUI project should I help with? | I am looking for an open-source project involving c++ GUI(s) working with a database. I have not done it before, and am looking for a way to get my feet wet. Which can I work on?
| How about this one http://sourceforge.net/projects/sqlitebrowser/:
SQLite Database browser is a light GUI editor for SQLite databases, built on top of QT. The main goal of the project is to allow non-technical users to create, modify and edit SQLite databases using a set of wizards and a spreadsheet-like interface.
|
77,126 | 77,147 | What are some good compilers to use when learning C++? | What are some suggestions for easy to use C++ compilers for a beginner? Free or open-source ones would be preferred.
| GCC is a good choice for simple things.
Visual Studio Express edition is the free version of the major windows C++ compiler.
If you are on Windows I would use VS. If you are on linux you should use GCC.
*I say GCC for simple things because for a more complicated project the build process isn't so easy
|
77,266 | 77,360 | Can operator>> read an int hex AND decimal? | Can I persuade operator>> in C++ to read both a hex value AND and a decimal value? The following program demonstrates how reading hex goes wrong. I'd like the same istringstream to be able to read both hex and decimal.
#include <iostream>
#include <sstream>
int main(int argc, char** argv)
{
int result = 0;
/... | Use std::setbase(0) which enables prefix dependent parsing. It will be able to parse 10 (dec) as 10 decimal, 0x10 (hex) as 16 decimal and 010 (octal) as 8 decimal.
#include <iomanip>
is >> std::setbase(0) >> result;
|
77,293 | 77,457 | What is an easy way to create a MessageBox with custom button text in Managed C++? | I would like to keep the overhead at a minimum. Right now I have:
// Launch a Message Box with advice to the user
DialogResult result = MessageBox::Show("This may take awhile, do you wish to continue?", "Warning", MessageBoxButtons::YesNo, MessageBoxIcon::Exclamation);
// The test will only be launched if the user has... | You can use "OK" and "Cancel"
By substituting MessageBoxButtons::YesNo with MessageBoxButtons::OKCancel
MessageBoxButtons Enum
Short of that you would have to create a new form, as I don't believe the Enum can be extended.
|
77,817 | 77,911 | C++ runtime knowledge of classes | I have multiple classes that all derive from a base class, now some of the derived classes will not be compiled depending on the platform. I have a class that allows me to return an object of the base class, however now all the names of the derived classes have been hard coded.
Is there a way to determine what classes ... | Are you looking for C++ runtime class registration? I found this link (backup).
That would probably accomplish what you want, I am not sure about the dynamically loaded modules and whether or not you can register them using the same method.
|
78,053 | 78,866 | How to iterate over all the page breaks in an Excel 2003 worksheet via COM | I've been trying to retrieve the locations of all the page breaks on a given Excel 2003 worksheet over COM. Here's an example of the kind of thing I'm trying to do:
Excel::HPageBreaksPtr pHPageBreaks = pSheet->GetHPageBreaks();
long count = pHPageBreaks->Count;
for (long i=0; i < count; ++i)
{
Excel::HPageBreakPtr p... | Experimenting with Excel 2007 from Visual Basic, I discovered that the page break isn't known unless it has been displayed on the screen at least once.
The best workaround I could find was to page down, from the top of the sheet to the last row containing data. Then you can enumerate all the page breaks.
Here's the VBA... |
78,717 | 79,071 | "foreach values" macro in gcc & cpp | I have a 'foreach' macro I use frequently in C++ that works for most STL containers:
#define foreach(var, container) \
for(typeof((container).begin()) var = (container).begin(); \
var != (container).end(); \
++var)
(Note that 'typeof' is a gcc extension.) It is used like this:
std::vector< Blorgus > blor... | You can do this using two loops. The first declares the iterator, with a name which is a function of the container variable (and you can make this uglier if you're worried about conflicts with your own code). The second declares the value variable.
#define ci(container) container ## iter
#define foreach_value(var, co... |
78,723 | 79,169 | How to test function call order | Considering such code:
class ToBeTested {
public:
void doForEach() {
for (vector<Contained>::iterator it = m_contained.begin(); it != m_contained.end(); it++) {
doOnce(*it);
doTwice(*it);
doTwice(*it);
}
}
void doOnce(Contained & c) {
// do something
}
void doTwice(Contained &... | If you're interested in performance, I recommend that you write a test that measures performance.
Check the current time, run the method you're concerned about, then check the time again. Assert that the total time taken is less than some value.
The problem with check that methods are called in a certain order is that... |
79,023 | 79,050 | Is there a C++ gdb GUI for Linux? | Briefly: Does anyone know of a GUI for gdb that brings it on par or close to the feature set you get in the more recent version of Visual C++?
In detail: As someone who has spent a lot of time programming in Windows, one of the larger stumbling blocks I've found whenever I have to code C++ in Linux is that debugging a... | You won't find anything overlaying GDB which can compete with the raw power of the Visual Studio debugger. It's just too powerful, and it's just too well integrated inside the IDE.
For a Linux alternative, try DDD if free software is your thing.
|
79,210 | 79,358 | Best C++ IDE for *nix | What is the best C++ IDE for a *nix envirnoment? I have heard the C/C++ module of Eclipse is decent as well as Notepad++ but beyond these two I have no real idea. Any thoughts or comments?
| On Ubuntu, some the IDEs that are available in the repositories are:
Kdevelop
Geany
Anjuta
There is also:
Eclipse (Recommended you don't install from repositories, due to issues with file/folder permissions)
Code::blocks
And of course, everyone's favourite text-based editors:
vi/vim
emacs
Its true that vim an... |
79,356 | 79,859 | What is best for desktop widgets (small footprint and pretty graphics)? | If I were to want to create a nice looking widget to stay running in the background with a small memory footprint, where would I start building the windows application. It's goal is to keep an updated list of items off of a web service. Similar to an RSS reader.
note: The data layer will be connecting through REST, wh... | re:
Update: Clarification The above sizes,
are the memory being used as the
process is ran, not the executable.
Okay, when you run a tiny C# Win Forms app, the smallest amount of RAM that is reserved for it is around 2 meg, maybe 4 meg. This is just a working set that it creates. It's not actively using all of t... |
79,745 | 79,817 | How to determine which version of Direct3D is installed? | We have an application which needs to use Direct3D. Specifically, it needs at least DirectX 9.0c version 4.09.0000.0904. While this should be present on all newer XP machines it might not be installed on older XP machines. How can I programmatically (using C++) determine if it is installed? I want to be able to give an... | Call DirectXSetupGetVersion: http://msdn.microsoft.com/en-us/library/microsoft.directx_sdk.directsetup.directxsetupgetversion
You'll need to include dsetup.h
Here's the sample code from the site:
DWORD dwVersion;
DWORD dwRevision;
if (DirectXSetupGetVersion(&dwVersion, &dwRevision))
{
printf("DirectX version is %d.... |
80,341 | 80,402 | Best OS App for Outbound SMTP Packet Capture? | Okay, so this probably sounds terribly nefarious, but I need such capabilities for my senior project. Essentially I'm tasked with writing something that will cut down outbound spam on a zombified pc through a system of packet interception and evaluation. We have a number of algorithms we'll use on the captured messages... | Sounds like you need to write a Winsock LSP.
Once in the stack, a Layered Service Provider can intercept and modify inbound and outbound Internet traffic. It allows processing all the TCP/IP traffic taking place between the Internet and the applications that are accessing the Internet.
|
80,348 | 80,573 | In C++, can you have a function that modifies a tuple of variable length? | In C++0x I would like to write a function like this:
template <typename... Types>
void fun(typename std::tuple<Types...> my_tuple) {
//Put things into the tuple
}
I first tried to use a for loop on int i and then do:
get<i>(my_tuple);
And then store some value in the result. However, get only works on constexpr.
... | Since the "i" in
get<i>(tup)
needs to be a compile-time constant, template instantiation is used to "iterate" (actually recurse) through the values. Boost tuples have the "length" and "element" meta-functions that can be helpful here -- I assume C++0x has these too.
|
80,452 | 81,070 | Best technology for developing an app that runs on DESKTOP and in BROWSER? | Microsoft WPF? Adobe AIR/Flex? Adobe Flash? Curl programming language?
How does AJAX fit in?
Given a server written in C++ .NET.
| The answer does depend really on what your application actually does and your platform requirements.
If its a regular web application like gmail and you want it to work on lots of browsers and platforms; then I'd recommend a combination of HTML, CSS and GWT as this means your application code is all Java, its very eas... |
80,518 | 80,566 | What happens when the stylus "lifts" on a tablet PC? | I am working on a legacy project in VC++/Win32/MFC. Recently it became a requirement that the application work on a tablet pc, and this ushered in a host of new issues.
I have been able to work with, and around these issues, but am left with one wherein I could use some expert suggestions.
I have a particular bug that ... | As a tablet user I can answer a few of your questions.
First:
You cannot very easily keep a "keyboard focus" on a window when the stylus has to trail out of the focused window to push a key on the virtual keyboard.
Most of the virtual keyboards I've used (The windows tablet input panel and one under ubuntu) allow the... |
80,619 | 80,651 | 'Helper' functions in C++ | While refactoring some old code I have stripped out a number of public methods that should actually of been statics as they a) don't operate on any member data or call any other member functions and b) because they might prove useful elsewhere.
This led me to think about the best way to group 'helper' functions togethe... | Overhead is not an issue, namespaces have some advantages though
You can reopen a namespace in another header, grouping things more logically while
keeping compile dependencies low
You can use namespace aliasing to your advantage
(debug/release, platform specific helpers, ....)
e.g. I've done stuff like
namespace Lit... |
80,691 | 81,827 | Orthogonal variables code duplication problem | I've started refactoring some legacy code recently and came across two functions for drawing a coordinate grid, the problem is that these functions differ only in orthogonal variables they treat, something like that
void DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1)
{
for(int x = x0; x < x1; x += ste... | Drawing a line is simply joining two points, and drawing a scaling incrementing (x0,y0) and(x1,y1) in a particular direction, through X, and/or through Y.
This boils down to, in the scale case, which direction(s) stepping occurs (maybe both directions for fun).
template< int XIncrement, YIncrement >
struct DrawScale
{
... |
80,831 | 90,972 | How to find out the distinguished name of the information store to feed to IExchangeManageStore::GetMailboxTable? | There is a Microsoft knowledge base article with sample code to open all mailboxes in a given information store. It works so far (requires a bit of copy & pasting on compilers newer than VC++ 6.0).
At one point it calls IExchangeManageStore::GetMailboxTable with the distinguished name of the information store. For the ... | Thinking there must be a pure MAPI solution, I believe I've figured out how OutlookSpy does it.
The following code snippet, inserted after
printf("Created MAPI session\n");
in the example from KB194627, will show the Server DN.
LPPROFSECT lpProfSect;
hr = lpSess->OpenProfileSection((LPMAPIUID)pbGlobalProfileSectionG... |
82,415 | 82,526 | Prefetch instructions on ARM | Newer ARM processors include the PLD and PLI instructions.
I'm writing tight inner loops (in C++) which have a non-sequential memory access pattern, but a pattern that naturally my code fully understands. I would anticipate a substantial speedup if I could prefetch the next location whilst processing the current memor... | There should be some Compiler-specific Features. There is no standard way to do it for C/C++. Check out you compiler Compiler Reference Guide. For RealView Compiler see this or this.
|
82,495 | 84,292 | Has anyone tried transactional memory for C++? | I was checking out Intel's "whatif" site and their Transactional Memory compiler (each thread has to make atomic commits or rollback the system's memory, like a Database would).
It seems like a promising way to replace locks and mutexes but I can't find many testimonials. Does anyone here have any input?
| I have not used Intel's compiler, however, Herb Sutter had some interesting comments on it...
From Sutter Speaks: The Future of Concurrency
Do you see a lot of interest in and usage of transactional memory, or is the concept too difficult for most developers to grasp?
It's not yet possible to answer who's using it beca... |
82,550 | 83,616 | Boost serialization: specifying a template class version | I have a template class that I serialize (call it C), for which I want to specify a version for boost serialization. As BOOST_CLASS_VERSION does not work for template classes. I tried this:
namespace boost {
namespace serialization {
template< typename T, typename U >
struct version< C<T,U> >
{
type... | #include <boost/serialization/version.hpp>
:-)
|
83,439 | 83,538 | Remove spaces from std::string in C++ | What is the preferred way to remove spaces from a string in C++? I could loop through all the characters and build a new string, but is there a better way?
| The best thing to do is to use the algorithm remove_if and isspace:
remove_if(str.begin(), str.end(), isspace);
Now the algorithm itself can't change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase t... |
83,640 | 83,705 | C++ does begin/end/rbegin/rend execute in constant time for std::set, std::map, etc? | For data types such as std::set and std::map where lookup occurs in logarithmic time, is the implementation required to maintain the begin and end iterators? Does accessing begin and end imply a lookup that could occur in logarithmic time?
I have always assumed that begin and end always occur in constant time, however ... | They happen in constant time. I'm looking at page 466 of the ISO/IEC 14882:2003 standard:
Table 65 - Container Requiments
a.begin(); (constant complexity)
a.end(); (constant complexity)
Table 66 - Reversible Container Requirements
a.rbegin(); (constant complexity)
a.rend(); (constant complexity)
|
84,064 | 85,102 | SQLBindParameter to prepare for SQLPutData using C++ and SQL Native Client | I'm trying to use SQLBindParameter to prepare my driver for input via SQLPutData. The field in the database is a TEXT field. My function is crafted based on MS's example here:
http://msdn.microsoft.com/en-us/library/ms713824(VS.85).aspx.
I've setup the environment, made the connection, and prepared my statement succes... | you're passing NULL as the buffer length, this is an in/out param that shoudl be the size of the col_num parameter. Also, you should pass a value for the ColumnSize or DecimalDigits parameters.
http://msdn.microsoft.com/en-us/library/ms710963(VS.85).aspx
|
84,269 | 254,883 | Using Component Object Model (COM) on non-Microsoft platforms | I'm regularly running into similar situations :
I have a bunch of COM .DLLs (no IDL files) which I need to use and invoke to be able to access some foreign (non-open, non-documented) data format.
Microsoft's Visual Studio platform has very nice capabilities to import such COM DLLs and use them in my project (Visual C++... | Answering myself but I managed to find the perfect library for OLE/COM calling in non-Microsoft compilers : disphelper.
(it's available from sourceforge.net under a permissive BSD license).
It works both in C and C++ (and thus any other language with C bindings as well). It uses a printf/scanf-like format string syntax... |
84,427 | 84,562 | Is it legal to pass a newly constructed object by reference to a function? | Specifically, is the following legal C++?
class A{};
void foo(A*);
void bar(const A&);
int main(void)
{
foo(&A()); // 1
bar(A()); // 2
}
It appears to work correctly, but that doesn't mean it's necessarily legal. Is it?
Edit - changed A& to const A&
| 1: Taking the address of a temporary is not allowed. Visual C++ allows it as a language extension (language extensions are on by default).
2: This is perfectly legal.
|
84,817 | 85,452 | Super Robust as chrome c++ and portable - tips - help - comments | We are producing a portable code (win+macOs) and we are looking at how to make the code more rubust as it crashes every so often... (overflows or bad initializations usually) :-(
I was reading that Google Chrome uses a process for every tab so if something goes wrong then the program does not crash compleatelly, only t... | I've developed on numerous multi-platform C++ apps (the largest being 1.5M lines of code and running on 7 platforms -- AIX, HP-UX PA-RISC, HP-UX Itanium, Solaris, Linux, Windows, OS X). You actually have two entirely different issues in your post.
Instability. Your code is not stable. Fix it.
Use unit tests to find ... |
85,122 | 85,143 | How to make thread sleep less than a millisecond on Windows | On Windows I have a problem I never encountered on Unix. That is how to get a thread to sleep for less than one millisecond. On Unix you typically have a number of choices (sleep, usleep and nanosleep) to fit your needs. On Windows, however, there is only Sleep with millisecond granularity.
On Unix, I can use the use ... | On Windows the use of select forces you to include the Winsock library which has to be initialized like this in your application:
WORD wVersionRequested = MAKEWORD(1,0);
WSADATA wsaData;
WSAStartup(wVersionRequested, &wsaData);
And then the select won't allow you to be called without any socket so you have to do a lit... |
86,046 | 86,146 | Best way to start a thread as a member of a C++ class? | I'm wondering the best way to start a pthread that is a member of a C++ class? My own approach follows as an answer...
| I usually use a static member function of the class, and use a pointer to the class as the void * parameter. That function can then either perform thread processing, or call another non-static member function with the class reference. That function can then reference all class members without awkward syntax.
|
86,219 | 87,159 | Interfacing with telephony systems from *nix | Does anyone know of any 'standard' way to interface with a telephony system (think Cisco CCM) from a C/C++ app in *nix? I have used MS TAPI in the past but this is Windows only and don't want to go the jTAPI (Java) route, which seems to be the only option on the face of it.
I want to monitor the phone system for loggi... | I have experience with two telephony standards TAPI, and CSTA, as far as I know there is no such agreement between vendors (e.g. Cisco, Nortel, NEC) regarding THE standard API.
I would recommend looking at the availability of SMDR (Station Messaging Detail Recording) on the PBX platforms you are targeting, assuming tha... |
86,474 | 86,522 | Firing COM events in C++ - Synchronous or asynchronous? | I have an ActiveX control written using the MS ATL library and I am firing events via pDispatch->Invoke(..., DISPATCH_METHOD). The control will be used by a .NET client and my question is this - is the firing of the event a synchronous or asynchronous call? My concern is that, if synchronous, the application that han... | It is synchronous from the point of view of the component generating the event. The control's thread of execution will call out into the receivers code and things are out of its control at that point.
Clients receiving the events must make sure they return quickly. If they need to do some significant amount of work t... |
86,582 | 92,193 | Singleton: How should it be used | Edit:
From another question I provided an answer that has links to a lot of questions/answers about singletons: More info about singletons here:
So I have read the thread Singletons: good design or a crutch?
And the argument still rages.
I see Singletons as a Design Pattern (good and bad).
The problem with Singleton... | Answer:
Use a Singleton if:
You need to have one and only one object of a type in system
Do not use a Singleton if:
You want to save memory
You want to try something new
You want to show off how much you know
Because everyone else is doing it (See cargo cult programmer in wikipedia)
In user interface widgets
It is s... |
87,220 | 4,506,050 | How does gcc implement stack unrolling for C++ exceptions on linux? | How does gcc implement stack unrolling for C++ exceptions on linux? In particular, how does it know which destructors to call when unrolling a frame (i.e., what kind of information is stored and where is it stored)?
| See section 6.2 of the x86_64 ABI. This details the interface but not a lot of the underlying data. This is also independent of C++ and could conceivably be used for other purposes as well.
There are primarily two sections of the ELF binary as emitted by gcc which are of interest for exception handling. They are .eh_fr... |
87,372 | 87,846 | Check if a class has a member function of a given signature | I'm asking for a template trick to detect if a class has a specific member function of a given signature.
The problem is similar to the one cited here
http://www.gotw.ca/gotw/071.htm
but not the same: in the item of Sutter's book he answered to the question that a class C MUST PROVIDE a member function with a particul... | I'm not sure if I understand you correctly, but you may exploit SFINAE to detect function presence at compile-time. Example from my code (tests if class has member function size_t used_memory() const).
template<typename T>
struct HasUsedMemoryMethod
{
template<typename U, size_t (U::*)() const> struct SFINAE {};
... |
87,405 | 87,460 | Different versions of C++ libraries | After compiling a simple C++ project using Visual Studio 2008 on vista, everything runs fine on the original vista machine and other vista computers. However, moving it over to an XP box results in an error message: "The application failed to start because the application configuration is incorrect".
What do I have to ... | You need to install the Visual Studios 2008 runtime on the target computer:
http://www.microsoft.com/downloads/details.aspx?FamilyID=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&displaylang=en
Alternatively, you could also link the run time statically, in the project properties window go to:
c++ -> Code Generation -> Runtim... |
87,610 | 87,882 | Automated integration testing a C++ app with a database | I am introducing automated integration testing to a mature application that until now has only been manually tested.
The app is Windows based and talks to a MySQL database.
What is the best way (including details of any tools recommended) to keep tests independent of each other in terms of the database transactions tha... | How are you verifying the results?
If you need to query the DB (and it sounds like you probably do) for results then I agree with Kris K, except I would endeavor to rebuild the DB after every test case, not just every suite.
This helps avoid dangerous interacting tests
As for tools, I would recommend CppUnit. You aren... |
87,689 | 92,462 | Testing running condition of a Windows app | I have several applications that are part of a suite of tools that various developers at our studio use. these applications are mainly command line apps that open a DOS cmd shell. These apps in turn start up a GUI application that tracks output and status (via sockets) of these command line apps.
The command line app... | I found the programmatic answer that I was looking for. It has to do with stations. Apparently anything running on the desktop will run on a station with a particular name. Anything that isn't on the desktop (i.e. a process started by the task manager when logged off or on a locked workstation) will get started with... |
87,794 | 92,750 | C++ unit testing framework | I use the Boost Test framework for my C++ code but there are two problems with it that are probably common to all C++ test frameworks:
There is no way to create automatic test stubs (by extracting public functions from selected classes for example).
You cannot run a single test - you have to run the entire 'suite' of ... | I just responded to a very similar question. I ended up using Noel Llopis' UnitTest++. I liked it more than boost::test because it didn't insist on implementing the main program of the test harness with a macro - it can plug into whatever executable you create. It does suffer from the same encumbrance of boost::test in... |
87,831 | 87,948 | How do I use my own compiler with Nant? | Nant seems very compiler-centric - which is guess is because it's considered a .NET development system. But I know it can be done! I've seen it. The platform we're building on has its own compiler and doesn't use 'cl.exe' for c++. We're building a C++ app on a different platform and would like to override with our own... | Here is one I did for Delphi. Each 'arg' is a separate param with a value defined elsewhere. The target is called with the params set up before calling it.
<target name="build.application">
<exec program="dcc32" basedir="${Delphi.Bin}" workingdir="${Application.Folder}" verbose="true">
<arg value="${Applica... |
87,932 | 88,215 | Attribute & Reflection libraries for C++? | Most mature C++ projects seem to have an own reflection and attribute system, i.e for defining attributes which can be accessed by string and are automatically serializable. At least many C++ projects I participated in seemed to reinvent the wheel.
Do you know any good open source libraries for C++ which support reflec... | You could have a look at the two tools below. I've never used either of them, so I can't tell you how (im)practical they are.
XRTTI:
Xrtti is a tool and accompanying C++ library which extends the standard runtime type system of C++ to provide a much richer set of reflection information about classes and methods to man... |
88,573 | 88,905 | Should I use an exception specifier in C++? | In C++, you can specify that a function may or may not throw an exception by using an exception specifier. For example:
void foo() throw(); // guaranteed not to throw an exception
void bar() throw(int); // may throw an exception of type int
void baz() throw(...); // may throw an exception of some unspecified type
I'm ... | No.
Here are several examples why:
Template code is impossible to write with exception specifications,
template<class T>
void f( T k )
{
T x( k );
x.x();
}
The copies might throw, the parameter passing might throw, and x() might throw some unknown exception.
Exception-specifications tend to prohibit extensi... |
88,957 | 88,960 | What does {0} mean when initializing an object? | When {0} is used to initialize an object, what does it mean? I can't find any references to {0} anywhere, and because of the curly braces Google searches are not helpful.
Example code:
SHELLEXECUTEINFO sexi = {0}; // what does this do?
sexi.cbSize = sizeof(SHELLEXECUTEINFO);
sexi.hwnd = NULL;
sexi.fMask = SEE_MASK_NOCL... | What's happening here is called aggregate initialization. Here is the (abbreviated) definition of an aggregate from section 8.5.1 of the ISO spec:
An aggregate is an array or a class with no user-declared constructors, no private or protected non-static data members, no base classes, and no virtual functions.
Now, u... |
88,991 | 90,563 | Produce conditional compile time error in Java | I do not mean the compile errors because I made a syntax mistake or whatever. In C++ we can create compile time errors based on conditions as in the following example:
template<int> struct CompileTimeError;
template<> struct CompileTimeError<true> {};
#define STATIC_CHECK(expr, msg) { CompileTimeError<((expr) != 0)> E... | There is no way to do this in Java, not in the same way it works for you in C++.
You could perhaps use annotations, and run apt before or after compilation to check your annotations.
For example:
@MyStaticCheck(false, "Compile Time Error, kind-of")
public static void main(String[] args) {
return;
}
And then write ... |
89,275 | 89,284 | Best C++ IDE or Editor for Windows | What is the best C++ IDE or editor for using on Windows? I use Notepad++, but am missing IntelliSense from Visual Studio.
| I've found the latest release of NetBeans, which includes C/C++ support, to be excellent.
http://www.netbeans.org/features/cpp/index.html
|
89,588 | 89,589 | AssignProcessToJobObject fails with "Access Denied" error when running under the debugger | You do AssignProcessToJobObject and it fails with "access denied" but only when you are running in the debugger. Why is this?
| This one puzzled me for for about 30 minutes.
First off, you probably need a UAC manifest embedded in your app (as suggested here). Something like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<!-- Identify the application s... |
89,767 | 90,106 | Help on Porting a SIP library to PSP | I'm currently trying to port a SIP stack library (pjSIP) to the PSP Console (using the PSPSDK toolchain), but I'm having too much trouble with the makefiles (making the proper changes and solving linking issues).
Does anyone know a good text, book or something to get some insight on porting libraries?
The only documen... | Look at other libraries that were ported over to the PSP. Doing diffs between a linux version of a library, and a PSP version should show you.
Also, try to get to know how POSIX compatible the PSP is, that will tell you how big the job of porting the library over is.
|
90,164 | 90,994 | Is there a way to compile C++ code to Microsoft .Net CIL (bytecode)? | I.e., a web browser client would be written in C++ !!!
| There are a two choices. Managed C++ (/clr:oldSyntax, no longer maintained) or C++/CLI (definitely maintained). You'll want to use /clr:safe for in-browser software, because you wnat the browser to be able to verify it.
|
90,503 | 90,592 | Game Development Sound Frameworks | I'm working with a team that's building an engine for a variety of 2D and eventually 3D mini-games. The problem we're facing is a solid, cross-platform, sound API. Obviously, DirectX is out of the question due to our needs for cross-platform capabilities. SDL is nice, and works great, but let's face it SDL_Mixer is a b... | (note: I have experience with FMOD, BASS, OpenAL and DirectSound; and while I list other libraries below, I haven't used them).
BASS and FMOD are both good (and actually I liked FMOD's documentation a lot; why would you say it's "non existing"?). There are also Miles Sound System, Wwise, irrKlang and some more middlewa... |
90,798 | 90,931 | How do you place EXIF tags into a JPG, having the raw jpeg buffer in C++? | I am having a bit of a problem.
I get a RAW char* buffer from a camera and I need to add this tags before I can save it to disk. Writing the file to disk and reading it back again is not an option, as this will happen thousands of times.
The buffer data I receive from the camera does not contain any EXIF information, a... | Look at this PDF, on page 20 you have a diagram showing you were to place or modify your exif information. What is the difference with a file on disk ?
Does the JPEG buffer of your camera contain an EXIF section already ?
|
91,384 | 91,561 | Unit testing for C++ code - Tools and methodology | I'm working on a large c++ system that is has been in development for a few years now. As part of an effort to improve the quality of the existing code we engaged on a large long-term refactoring project.
Do you know a good tool that can help me write unit tests in C++? Maybe something similar to Junit or Nunit?
Can an... | Applying unit tests to legacy code was the very reason Working Effectively with Legacy Code was written. Michael Feathers is the author - as mentioned in other answers, he was involved in the creation of both CppUnit and CppUnitLite.
|
91,420 | 91,456 | Export variable from C++ static library | I have a static library written in C++ and I have a structure describing data format, i.e.
struct Format{
long fmtId;
long dataChunkSize;
long headerSize;
Format(long, long, long);
bool operator==(Format const & other) const;
};
Some of data formats are widely used, like {fmtId=0, dataChunkSize=1... | Don't use the static keyword on global declarations. Here is an article explain the visibility of variables with/without static. The static gives globals internal linkage, that is, only visible in the translation unit they are declared in.
|
91,511 | 91,575 | How to wrap an existing memory buffer as a DC for GDI | I have a memory buffer corresponding to my screen resolution (1280x800 at 24-bits-per-pixel) that contains my screen contents at 24bpp. I want to convert this to 8-bpp (ie. Halftone color palette in Windows).
I currently do this:
1. Use CreateDIBSection to allocate a new 1280x800 24-bpp buffer and access it as a DC, as... | OK, to address the two parts of the problem.
the following code shows how to get at the pixels inside of a bitmap, change them and put them back into the bitmap. You could always generate a dummy bitmap of the correct size and format, open it up, copy over your data and you then have a bitmap object with your data:
p... |
91,616 | 91,705 | Easiest cross platform widget toolkit? | What is the easiest cross platform widget toolkit? I'm looking for one that minimally covers Windows, OSX, and Linux with a C or C++ interface.
| I don't know of any I've personally used with a C API, but wxWidgets is C++. It runs on Windows, Linux, and Mac OS X. And if you're looking for easy, wxPython is a Python wrapper around wxWidgets and it is pretty easy to use.
|
91,683 | 91,872 | How do you implement unit-testing in large scale C++ projects? | I believe strongly in using unit-tests as part of building large multi-platform applications. We currently are planning on having our unit-tests within a separate project. This has the benefit of keeping our code base clean. I think, however, that this would separate the test code from the implementation of the unit. W... | There are many Test Unit frameforks for C++.
CppUnit is certainly not the one I would choose (at least in its stable version 1.x, as it lacks many tests, and requires a lot of redundant lines of codes).
So far, my preferred framework is CxxTest, and I plan on evaluating Fructose some day.
Any way, there are a few "pap... |
91,715 | 91,759 | C++ strings without <string> and STL | I've not used C++ very much in the past, and have recently been doing a lot of C#, and I'm really struggling to get back into the basics of C++ again. This is particularly tricky as work mandates that none of the most handy C++ constructs can be used, so all strings must be char *'s, and there is no provision for STL l... | You'll probably need to use strcmp to see if the string is already stored:
for (int index=0; index<=lastIndex; index++)
{
if (strcmp(registeredNames[index], name) == 0)
{
return; // Already registered
}
}
Then if you really need to store a copy of the string, then you'll need to allocate a buffer and copy th... |
92,039 | 92,071 | " Attach to Process " in Visual Studio 2005 | I installed Visual Studio 2005 ( with SP1 ) and made the default settings as what is required for C++ .
Now i open a solution and run the exe .
Under " Tools " menu item i go and Select " Attach the process " and i attach it to the exe i just ran . I put breakpoints several places in the code ( this breakpoints looks... | Perhaps it is attaching to "the wrong kind" of code.
In the "Attach to Process" dialog, there is a setting that allows you to select the kind of code you want to debug. Try clicking "Select" button next to "Attach to" text box and checking only "Managed code" the relevant code type.
http://img204.imageshack.us/img204/3... |
92,396 | 92,439 | Why can't variables be declared in a switch statement? | I've always wondered this - why can't you declare variables after a case label in a switch statement? In C++ you can declare variables pretty much anywhere (and declaring them close to first use is obviously a good thing) but the following still won't work:
switch (val)
{
case VAL:
// This won't work
int new... | Case statements are only labels. This means the compiler will interpret this as a jump directly to the label. In C++, the problem here is one of scope. Your curly brackets define the scope as everything inside the switch statement. This means that you are left with a scope where a jump will be performed further into th... |
92,546 | 92,641 | Variable declarations in header files - static or not? | When refactoring away some #defines I came across declarations similar to the following in a C++ header file:
static const unsigned int VAL = 42;
const unsigned int ANOTHER_VAL = 37;
The question is, what difference, if any, will the static make? Note that multiple inclusion of the headers isn't possible due to the c... | The static means that there will be one copy of VAL created for each source file it is included in. But it also means that multiple inclusions will not result in multiple definitions of VAL that will collide at link time. In C, without the static you would need to ensure that only one source file defined VAL while th... |
92,671 | 92,717 | How do I reserve caret position in CEdit control? | I'm programming an application in MFC (don't ask) and I have a CEdit box that holds a number. When that number is edited, I would like to act on the change, and then replace the caret where it was before I acted on the change - if the user was just before the "." in "35.40", I would like it to still be placed before t... | Use the GetSel() function before your change to store the location of the cursor, then use SelSel() to set it back. You can use these functions to get/set the location of the caret, not just to get/set the selection the user has made.
|
92,859 | 999,810 | What are the differences between struct and class in C++? | This question was already asked in the context of C#/.Net.
Now I'd like to learn the differences between a struct and a class in C++. Please discuss the technical differences as well as reasons for choosing one or the other in OO design.
I'll start with an obvious difference:
If you don't specify public: or private:, ... | You forget the tricky 2nd difference between classes and structs.
Quoth the standard (§11.2.2 in C++98 through C++11):
In absence of an access-specifier
for a base class, public is assumed
when the derived class is declared
struct and private is assumed when the class is declared class.
And just for completenes... |
93,039 | 93,411 | Where are static variables stored in C and C++? | In what segment (.BSS, .DATA, other) of an executable file are static variables stored so that they don't have name collision?
For example:
foo.c: bar.c:
static int foo = 1; static int foo = 10;
void fooTest() { void barTest() {
static int bar = 2; static i... | Where your statics go depends on whether they are zero-initialized. zero-initialized static data goes in .BSS (Block Started by Symbol), non-zero-initialized data goes in .DATA
|
93,073 | 93,115 | How to implement thread safe reference counting in C++ | How do you implement an efficient and thread safe reference counting system on X86 CPUs in the C++ programming language?
I always run into the problem that the critical operations not atomic, and the available X86 Interlock operations are not sufficient for implementing the ref counting system.
The following article c... | Nowadays, you can use the Boost/TR1 shared_ptr<> smart pointer to keep your reference counted references.
Works great; no fuss, no muss. The shared_ptr<> class takes care of all the locking needed on the refcount.
|
93,260 | 93,291 | A free tool to check C/C++ source code against a set of coding standards? | It looks quite easy to find such a tool for Java (Checkstyle, JCSC), but I can't seem to find one for C/C++. I am not looking for a lint-like static code analyzer, I only would like to check against coding standards like variable naming, capitalization, spacing, identation, bracket placement, and so on.
| The only tool I know is Vera. Haven't used it, though, so can't comment how viable it is. Demo looks promising.
|
93,545 | 2,089,097 | How do you detect dialup, broadband or wireless Internet connections in C++ for Windows? | I have an installation program (just a regular C++ MFC program, not Windows Installer based) that needs to set some registry values based on the type of Internet connection: broadband, dialup, and/or wireless. Right now this information is being determined by asking a series of yes or no questions. The problem is tha... | Use InternetGetConnectedState API to retrieve internet connection state.
I tested it and it works fine.
I found this document which can help:
http://www.pcausa.com/resources/InetActive.txt
|
93,569 | 93,797 | Are POD types always aligned? | For example, if I declare a long variable, can I assume it will always be aligned on a "sizeof(long)" boundary? Microsoft Visual C++ online help says so, but is it standard behavior?
some more info:
a. It is possible to explicitely create a misaligned integer (*bar):
char foo[5]
int * bar = (int *)(&foo[1]);
b. Appar... | As others have mentioned, this isn't part of the standard and is left up to the compiler to implement as it sees fit for the processor in question. For example, VC could easily implement different alignment requirements for an ARM processor than it does for x86 processors.
Microsoft VC implements what is basically cal... |
93,692 | 93,703 | Which Javascript engine would you embed in your application? | I want to embed Javascript in a hobby game engine of mine. Now that we have the 5th generation of Javascript engines out (all blazing fast) I'm curious what engine would you choose to embed in a C++ framework (that includes actual ease of embeding it)?
Note: Just to make it clear, I'm not interested in DOM scripting o... | Mozilla's SpiderMonkey is fairly easy and well-documented. It's a C API, but it's straightforward to wrap it in C++. It can be compiled to be thread-safe, which is useful for games since you'd likely want to have your main logic in one thread and user interface logic in a second thread.
Google's V8 might be a good ch... |
94,227 | 94,512 | Smart pointers: who owns the object? | C++ is all about memory ownership - aka ownership semantics.
It is the responsibility of the owner of a chunk of dynamically allocated memory to release that memory. So the question really becomes who owns the memory.
In C++ ownership is documented by the type a raw pointer is wrapped inside thus in a good (IMO) C++ pr... | For me, these 3 kinds cover most of my needs:
shared_ptr - reference-counted, deallocation when the counter reaches zero
weak_ptr - same as above, but it's a 'slave' for a shared_ptr, can't deallocate
auto_ptr - when the creation and deallocation happen inside the same function, or when the object has to be considered ... |
94,380 | 96,724 | Volume (Balance) Control for XP/Vista | Is there a method for controlling the Balance of the Wave output that will work on both XP and Vista?
| Vista has a new api for everything related to mixers and audio, per process legacy api's should still work, but to change global volume, you would have to look at the new COM interfaces added to Vista
This should get you started
|
94,755 | 94,979 | Best container for double-indexing | What is the best way (in C++) to set up a container allowing for double-indexing? Specifically, I have a list of objects, each indexed by a key (possibly multiple per key). This implies a multimap. The problem with this, however, is that it means a possibly worse-than-linear lookup to find the location of an object. I'... | I'm making several assumptions based on your writeup:
Keys are cheap to copy and compare
There should be only one copy of the object in the system
The same key may refer to many objects, but only one object corresponds to a given key (one-to-many)
You want to be able to efficiently look up which objects correspond to ... |
94,794 | 95,079 | What is the cost of a function call? | Compared to
Simple memory access
Disk access
Memory access on another computer(on the same network)
Disk access on another computer(on the same network)
in C++ on windows.
| relative timings (shouldn't be off by more than a factor of 100 ;-)
memory-access in cache = 1
function call/return in cache = 2
memory-access out of cache = 10 .. 300
disk access = 1000 .. 1e8 (amortized depends upon the number of bytes transferred)
depending mostly upon seek times
the transfer itself can be pretty... |
95,500 | 95,896 | Can this macro be converted to a function? | While refactoring code and ridding myself of all those #defines that we're now taught to hate, I came across this beauty used to calculate the number of elements in a structure:
#define STRUCTSIZE(s) (sizeof(s) / sizeof(*s))
Very useful as it is but can it be converted into an inline function or template?
OK, ARRAYSIZ... | As been stated, the code actually work out the number of elements in an array, not struct. I would just write out the sizeof() division explicitly when I want it. If I were to make it a function, I would want to make it clear in its definition that it's expecting an array.
template<typename T,int SIZE>
inline size_t ar... |
95,890 | 95,927 | What is a variable's linkage and storage specifier? | When someone talks about a variables storage class specifier, what are they talking about?
They also often talk about variable linkage in the same context, what is that?
| The storage class specifier controls the storage and the linkage of your variables. These are two concepts that are different.
C specifies the following specifiers for variables: auto, extern, register, static.
Storage
The storage duration determines how long your variable will live in ram.
There are three types of sto... |
95,956 | 96,034 | FindNextFile fails on 64-bit Windows? | using C++Builder 2007, the FindFirstFile and FindNextFile functions doesn't seem to be able to find some files on 64-bit versions of Vista and XP. My test application is 32-bit.
If I use them to iterate through the folder C:\Windows\System32\Drivers they only find a handful of files although there are 185 when I issue ... | Is there redirection going on? See the remarks on Wow64DisableWow64FsRedirection http://msdn.microsoft.com/en-gb/library/aa365743.aspx
|
96,196 | 96,268 | When are C++ macros beneficial? | The C preprocessor is justifiably feared and shunned by the C++ community. In-lined functions, consts and templates are usually a safer and superior alternative to a #define.
The following macro:
#define SUCCEEDED(hr) ((HRESULT)(hr) >= 0)
is in no way superior to the type safe:
inline bool succeeded(int hr) { retur... | As wrappers for debug functions, to automatically pass things like __FILE__, __LINE__, etc:
#ifdef ( DEBUG )
#define M_DebugLog( msg ) std::cout << __FILE__ << ":" << __LINE__ << ": " << msg
#else
#define M_DebugLog( msg )
#endif
Since C++20 the magic type std::source_location can however be used instead of __LINE__ ... |
96,233 | 96,263 | Why would I use 2's complement to compare two doubles instead of comparing their differences against an epsilon value? | Referenced here and here...Why would I use two's complement over an epsilon method? It seems like the epsilon method would be good enough for most cases.
Update: I'm purely looking for a theoretical reason why you'd use one over the other. I've always used the epsilon method.
Has anyone used the 2's complement comp... | the second link you reference mentions an article that has quite a long description of the issue:
http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
but unless you are tweaking performance I would stick with epsilon so people can debug your code
|
96,414 | 101,720 | C++: Step 1: ExtractIconEx. Step 2: ??? Step 3: SetMenuItemBitmaps | I'm experimenting with adding icons to a shell extension. I have this code (sanitized for easy reading), which works:
InsertMenu(hmenu, index, MF_POPUP|MF_BYPOSITION, (UINT)hParentMenu, namestring);
The next step is this code:
HICON hIconLarge, hIconSmall;
ICONINFO oIconInfo;
ExtractIconEx("c:\\progra~1\\winzip\\winzi... | This works, though the back color is black instead of transparent.
GetIconInfo(hIconSmall, &oIconInfo);
SetMenuItemBitmaps(hmenu, uMenuIndex+i+popUpMenuCount-1, MF_BITMAP | MF_BYPOSITION, oIconInfo.hbmColor, oIconInfo.hbmColor);
|
96,500 | 96,530 | Is there anything wrong with returning default constructed values? | Suppose I have the following code:
class some_class{};
some_class some_function()
{
return some_class();
}
This seems to work pretty well and saves me the trouble of having to declare a variable just to make a return value. But I don't think I've ever seen this in any kind of tutorial or reference. Is this a co... | No this is perfectly valid. This will also be more efficient as the compiler is actually able to optimise away the temporary.
|
96,579 | 97,536 | STL vectors with uninitialized storage? | I'm writing an inner loop that needs to place structs in contiguous storage. I don't know how many of these structs there will be ahead of time. My problem is that STL's vector initializes its values to 0, so no matter what I do, I incur the cost of the initialization plus the cost of setting the struct's members to ... | std::vector must initialize the values in the array somehow, which means some constructor (or copy-constructor) must be called. The behavior of vector (or any container class) is undefined if you were to access the uninitialized section of the array as if it were initialized.
The best way is to use reserve() and push_b... |
97,050 | 101,980 | std::map insert or std::map find? | Assuming a map where you want to preserve existing entries. 20% of the time, the entry you are inserting is new data. Is there an advantage to doing std::map::find then std::map::insert using that returned iterator? Or is it quicker to attempt the insert and then act based on whether or not the iterator indicates the... | The answer is you do neither. Instead you want to do something suggested by Item 24 of Effective STL by Scott Meyers:
typedef map<int, int> MapType; // Your map type may vary, just change the typedef
MapType mymap;
// Add elements to map here
int k = 4; // assume we're searching for keys equal to 4
int v = 0; ... |
97,081 | 97,229 | "get() const" vs. "getAsConst() const" | Someone told me about a C++ style difference in their team. I have my own viewpoint on the subject, but I would be interested by pros and cons coming from everyone.
So, in case you have a class property you want to expose via two getters, one read/write, and the other, readonly (i.e. there is no set method). There are ... | Well, for one thing, getAsConst must be called when the 'this' pointer is const -- not when you want to receive a const object. So, alongside any other issues, it's subtly misnamed. (You can still call it when 'this' is non-const, but that's neither here nor there.)
Ignoring that, getAsConst earns you nothing, and pu... |
97,338 | 99,282 | GCC dependency generation for a different output directory | I'm using GCC to generate a dependency file, but my build rules put the output into a subdirectory. Is there a way to tell GCC to put my subdirectory prefix in the dependency file it generates for me?
gcc $(INCLUDES) -E -MM $(CFLAGS) $(SRC) >>$(DEP)
| The answer is in the GCC manual: use the -MT flag.
-MT target
Change the target of the rule emitted by dependency generation. By default CPP takes the name of the main input file, deletes any directory components and any file suffix such as .c, and appends the platform's usual object suffix. The result is the target.
... |
97,987 | 98,024 | Advantage of switch over if-else statement | What's the best practice for using a switch statement vs using an if statement for 30 unsigned enumerations where about 10 have an expected action (that presently is the same action). Performance and space need to be considered but are not critical. I've abstracted the snippet so don't hate me for the naming conventio... | Use switch.
In the worst case the compiler will generate the same code as a if-else chain, so you don't lose anything. If in doubt put the most common cases first into the switch statement.
In the best case the optimizer may find a better way to generate the code. Common things a compiler does is to build a binary deci... |
98,242 | 98,256 | Post increment operator behavior |
Possible Duplicate:
Pre & post increment operator behavior in C, C++, Java, & C#
Here is a test case:
void foo(int i, int j)
{
printf("%d %d", i, j);
}
...
test = 0;
foo(test++, test);
I would expect to get a "0 1" output, but I get "0 0"
What gives??
| This is an example of unspecified behavior. The standard does not say what order arguments should be evaluated in. This is a compiler implementation decision. The compiler is free to evaluate the arguments to the function in any order.
In this case, it looks like actually processes the arguments right to left inste... |
98,586 | 98,977 | Where can I find the world's fastest atof implementation? | I'm looking for an extremely fast atof() implementation on IA32 optimized for US-en locale, ASCII, and non-scientific notation. The windows multithreaded CRT falls down miserably here as it checks for locale changes on every call to isdigit(). Our current best is derived from the best of perl + tcl's atof implementat... | What is your accuracy requirement? If you truly need it "correct" (always gets the nearest floating-point value to the decimal specified), it will probably be hard to beat the standard library versions (other than removing locale support, which you've already done), since this requires doing arbitrary precision arithm... |
98,705 | 100,593 | What are the semantics of a const member function? | I understand that the function is not allowed to change the state of the object, but I thought I read somewhere that the compiler was allowed to assume that if the function was called with the same arguments, it would return the same value and thus could reuse a cached value if it was available. e.g.
class object
{
... | const is about program semantics and not about implementation details. You should mark a member function const when it does not change the visible state of the object, and should be callable on an object that is itself const. Within a const member function on a class X, the type of this is X const *: pointer to constan... |
99,474 | 99,503 | how to handle code that is deemed dangerous to change, but stable? | What is the best way to handle a big team that has access to a stable but no so pretty code, that is easy to introduce bugs into?
I'm looking for something along the lines of SVN locking the file(s).
| Write unit tests if you don't have them already. Then start refactoring, and keep doing regression tests upon every commit.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.