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 |
|---|---|---|---|---|
207,881 | 208,425 | Hide a tab previously added to Qt TabWidget | I've a dialog which contains a Qt TabWidget with a number of tabs added.
I'd like to hide one of the tabs.
_mytab->hide()
doesn't work. I don't want to just delete the tab and all its widgets from the .ui file because other code relies on the widgets within the tab. However, it would be fine to generate the tab ... | I would use QTabDialog::removePage(QWidget* pTabPage) which does not delete pTabPage, which is what you want.
_myTabDlg->removePage(_mytab);
I'm using it and it works fine !
|
207,965 | 255,524 | General way to reset a member variable to its original value using the stack? | I came across a class instance function that needed to temporarily change a class instance variable, and then restore it when the function completed. The function had return statements all over the place, and before each return there was a restoring statement. That seemed messy to me, not to mention scary when a except... | I revised the sample a bit more based on the comments, and placed as an Community Wiki answer instead of editing the question.
/// c++ code sample
#ifndef UTIL_RESTORER_HPP
#define UTIL_RESTORER_HPP
namespace Utility {
/// A Restorer instance ("inst") uses the stack to restore a saved
/// value to the named variable... |
207,994 | 209,101 | How do i specify a bold version of the theme's default font? | I'm having problems with cross theme compatibility in windows forms. If you don't set the font for a control on a windows form, it will use the system font with correct typeface and size. If you want to make the font bold, it hard codes in the rest of the system font values for the current theme you're programming wi... | You can put the modified font initialization directly after the InitializeComponent call in your constructor.
Also, you can you one of the many, many constructors to change the size.
InitializeComponent();
label1->Font = gcnew System::Drawing::Font(
label1->Font->FontFamily,
label1->Font->SizeInPoints + 4,
... |
208,268 | 208,286 | Enumerating network shared directories in C++ / MFC | I need to get a list of directories shared by the current computer, and their shared names. How do I do this in C++ / MFC?
| You can use NetShareEnum, supplying NULL as the server name.
You need to include Lm.h and add Netapi32.lib to the list of libraries linked,
|
208,373 | 212,953 | wxWidgets: How to initialize wxApp without using macros and without entering the main application loop? | We need to write unit tests for a wxWidgets application using Google Test Framework.
The problem is that wxWidgets uses the macro IMPLEMENT_APP(MyApp) to initialize and enter the application main loop. This macro creates several functions including int main(). The google test framework also uses macro definitions for e... | You want to use the function:
bool wxEntryStart(int& argc, wxChar **argv)
instead of wxEntry. It doesn't call your app's OnInit() or run the main loop.
You can call wxTheApp->CallOnInit() to invoke OnInit() when needed in your tests.
You'll need to use
void wxEntryCleanup()
when you're done.
|
208,433 | 208,446 | How do I write a short literal in C++? | Very basic question: how do I write a short literal in C++?
I know the following:
2 is an int
2U is an unsigned int
2L is a long
2LL is a long long
2.0f is a float
2.0 is a double
'\2' is a char.
But how would I write a short literal? I tried 2S but that gives a compiler warning.
| ((short)2)
Yeah, it's not strictly a short literal, more of a casted-int, but the behaviour is the same and I think there isn't a direct way of doing it.
That's what I've been doing because I couldn't find anything about it. I would guess that the compiler would be smart enough to compile this as if it's a short lite... |
208,855 | 208,888 | How to get pointer from another thread? | Let's have the following class definition:
CThread::CThread ()
{
this->hThread = NULL;
this->hThreadId = 0;
this->hMainThread = ::GetCurrentThread ();
this->hMainThreadId = ::GetCurrentThreadId ();
this->Timeout = 2000; //milliseconds
}
CThread::~CThread ()
{
//waiting for... | The memory space for your application is accessible to all threads. By default any variable is visible to any thread regardless of context (the only exception would be variables declared __delcspec(thread) )
You are getting a crash due to a race condition. The thread you just created hasn't started running yet at the... |
208,959 | 208,968 | How to store variant data in C++ | I'm in the process of creating a class that stores metadata about a particular data source. The metadata is structured in a tree, very similar to how XML is structured. The metadata values can be integer, decimal, or string values.
I'm curious if there is a good way in C++ to store variant data for a situation like t... | As of C++17, there’s std::variant.
If you can’t use that yet, you might want Boost.Variant. A similar, but distinct, type for modelling polymorphism is provided by std::any (and, pre-C++17, Boost.Any).
Just as an additional pointer, you can look for “type erasure”.
|
209,110 | 209,552 | MFC: Showing / Hiding Splitter Panes | In my application I have a number of panes from m_wndspliter classes. What I want to do is at run time show and hide one of these panes. Whilst with the following code I can show and hide the view associated with the pane, I can't temporarily remove the pane itself.
CWnd * pCurView = m_wndSplitter2.GetPane(2, 0);
if( ... | Does this help?
http://www.codeguru.com/cpp/w-d/splitter/article.php/c1543
I have used something very similar myself,
|
209,148 | 209,624 | MFC: What on earth is a CSplitterWnd Caret? | What on earth is a caret in the context of a CSplitterWnd class? I can't find any documentation relating explicitly to CSplitterWnds...
EDIT: Specifically, what do these functions actually do:
CWnd * pCurView = m_wndSplitter2.GetPane(2, 0);
pCurView->ShowCaret()
pCurView->HideCaret()
EDIT2: Please note, I know what a ... | Any CWnd can have a caret, but only CWnd inheritors that CreateCaret first actually display one. @DannySmurf gives you one example - CEditView - of a CView that creates a caret that you can show and hide.
Depending on the specific kind of CView you've got on your pane, ShowCaret is probably irrelevant. It has nothing t... |
209,198 | 210,694 | Borland x86 inlined assembler; get a label's address? | I am using Borland Turbo C++ with some inlined assembler code, so presumably Turbo Assembler (TASM) style assembly code. I wish to do the following:
void foo::bar( void )
{
__asm
{
mov eax, SomeLabel
// ...
}
// ...
SomeLabel:
// ...
}
So the address of SomeLabel is placed into EAX. Thi... | Last time I tried to make some assembly code Borland-compatible I came across the limitation that you can't forward-reference labels. Not sure if that's what you're running into here.
|
209,334 | 499,549 | How to start Linux Programming | I am working on C++ and COM/ATL in Windows from last few years. Now I want to shift to Linux Programming. I know basic architecture of Linux. I did some of the projects which are using ncurses, sockets and audio libraries(Terminal Applications). On which tool I should be familiar to start with projects. In windows I ha... | Start reading the book Advanced Linux Programming which is also available as a free PDF.
Do not fear the advanced keyword. From the details of your post (ncurses, sockets) you are already "advanced".
You can also look later at the glib library (Standard component of GTK+/GNOME but
also used in command line applications... |
209,603 | 209,658 | Steps to make a LED blink from a C/C++ program? | What are the easiest steps to make a small circuit with an LED flash from a C/C++ program?
I would prefer the least number of dependencies and packages needed.
What port would I connect something into?
Which compiler would I use?
How do I send data to that port?
Do I need to have a micro-processor? If not I don't wan... | Here's a tutorial on doing it with a parallel port.
Though I would recommend an Arduino which can be purchased very cheaply and would only involve the following code:
/* Blinking LED
* ------------
*
* turns on and off a light emitting diode(LED) connected to a digital
* pin, in intervals of 2 seconds. Ideally ... |
209,793 | 223,541 | Any way to cast with class operator only? | Kind of a random question...
What I'm looking for is a way to express a cast operation which uses a defined operator of the class instance I'm casting from, and generates a compile-time error if there is not a defined cast operator for the type. So, for example, what I'm looking for is something like:
template< typenam... | The code you posted works with the Cameau compiler (which is usually a good indication that it's valid C++).
As you know a valid cast consists of no more than one user defined cast, so a possible solution I was thinking of was adding another user defined cast by defining a new type in the cast template and having a st... |
210,026 | 210,043 | Doxygen won't index my C++ source - why not? | I have some C++ source code with templates maybe like this - doxygen runs without errors but none of the documentation is added to the output, what is going on?
///
/// A class
///
class A
{
///
/// A typedef
///
typedef B<C<D>> SomeTypedefOfTemplates;
};
| Yeah, so what is going on is the template instantiation is bogus. The ">>" like that is ambiguous and is meant to be a compile time error. You couldn't see it because maybe your compiler (VC++) let it slip by but I guess doxygen was stricter on that. Add a space like shown.
///
/// A class
///
class A
{
///
/// A t... |
210,247 | 210,316 | Visual studio intellisense for headers without .h | I am using a library that has headers without the .h
This defeats visual studio's intellisense (declaration/definition lookup)
Anyone know how to tell VS2008 that a file is a header?
| Go to Tools::Options::Text Editor::File Extension tab in Visual Studio. Check the "Map extensionless headers" checkbox, and select the language you want from the combobox.
|
210,616 | 210,638 | What is the member variables list after the colon in a constructor good for? | I'm reading this C++ open source code and I came to a constructor but I don't get it ( basically because I don't know C++ :P )
I understand C and Java very well.
TransparentObject::TransparentObject( int w, int x, int y, int z ) :
_someMethod( 0 ),
_someOtherMethod( 0 ),
_someOtherOtherMethod( 0 ),
... | The most common case is this:
class foo{
private:
int x;
int y;
public:
foo(int _x, int _y) : x(_x), y(_y) {}
}
This will set x and y to the values that are given in _x and _y in the constructor parameters. This is often the best way to construct any objects that are declared as data members.
It is also p... |
210,639 | 210,706 | How can I limit CreateWindowEx to alphanumeric input only? | I know that ES_NUMBER exists to limit CreateWindowEx to numeric input only, is there a similar mechanism for limiting it to only alphanumeric (a-z,0-9) input? Or another way to do something similar. I know I can check after the fact, but I would like to limit it as the user types.
| Check the EN_UPDATE message (via WM_COMMAND). It is sent just before the screen is updated; you can check the contents of the control and modify them if they contain any characters you don't want.
|
210,646 | 211,980 | Can't detect when Windows Font Size has changed C++ MFC | I'm trying to determine how I can detect when the user changes the Windows Font Size from Normal to Extra Large Fonts, the font size is selected by executing the following steps on a Windows XP machine:
Right-click on the desktop and select Properties.
Click on the Appearance Tab.
Select the Font Size: Normal/Large Fo... | [EDIT after re-read] I'm almost positive that changing to "Large fonts" does not cause a DPI change, rather it's a theme setting. You should be able to verify by applying the "Large fonts" change and then opening the advanced display properties where the DPI setting lives, it should have remained at 96dpi.
DPI change ... |
210,836 | 210,864 | stdcall over-ride by visual studio? | In xp 32bit this line compiles with not problem however in vista 64bit this line:
m_FuncAddr = ::GetProcAddress (somthing);
gives the following error
error C2440: '=' : cannot convert from
'FARPROC' to 'int (__cdecl *)(void)'
GetProcAddress is defined as
WINBASEAPI FARPROC WINAPI GetProcAddress (somthing)
And m_F... | The return type should be INT_PTR (a 64-bit value in 64-bit builds). You shouldn't cast around this error -- the compiler is trying to tell you that something is wrong.
From WinDef.h:
#ifdef _WIN64
typedef INT_PTR (FAR WINAPI *FARPROC)();
So the declaration of m_FuncAddr should be:
INT_PTR (WINAPI *m_FuncAddr)();
|
210,939 | 211,309 | Better Way To Use C++ Named Parameter Idiom? | I've been developing a GUI library for Windows (as a personal side project, no aspirations of usefulness). For my main window class, I've set up a hierarchy of option classes (using the Named Parameter Idiom), because some options are shared and others are specific to particular types of windows (like dialogs).
The way... | Maybe not what you want to hear, but I for one think it's ok to have lots of ugly type-casts and template parameters in library-code that's (more or less) hidden from the client as long as it is safe and makes the life of the client a lot easier. The beauty in library code is not in the code itself, but in the code it ... |
211,237 | 211,307 | Static variables initialisation order | C++ guarantees that variables in a compilation unit (.cpp file) are initialised in order of declaration. For number of compilation units this rule works for each one separately (I mean static variables outside of classes).
But, the order of initialization of variables, is undefined across different compilation units.
W... | As you say the order is undefined across different compilation units.
Within the same compilation unit the order is well defined: The same order as definition.
This is because this is not resolved at the language level but at the linker level. So you really need to check out the linker documentation. Though I really do... |
211,376 | 211,419 | function overloading fail: why did these operators clash? | I've got a big big code base that includes two main namespaces: the engine and the application.
The engine defines a vector3 class as a typedef of another vector3 class, with equality operators that sit in the engine namespace, not in the vector3 class. I added a class to the application that also had equality opera... | C++ Standard, 3.4.4.2 declares:
For each argument type T in the function call, there is a set of zero or more associated namespaces and a set of zero
or more associated classes to be considered. The sets of namespaces and classes is determined entirely by the types of
the function arguments (and the namespace of a... |
211,384 | 211,449 | Open Source C++ Data Visualization Library | We want to include data visualization in our desktop GUI (mostly timelines and graphs; clickable, draggable). We want to restrict to open-source, non-copyleft C++ libraries that allow commercial use and are portable across many platforms. Which library can I use? Our GUI is based on WxWidgets.
| there is VTK.
And if data visualization is your thing, have a look at opendx too.
|
211,934 | 211,949 | Dynamically Loading External Modules in a C Program? | I'm sure this problem has been solved before and I'm curious how its done. I have code in which, when run, I want to scan the contents of a directory and load in functionality.
Specifically, I am working with a scripting engine that I want to be able to add function calls to. I want the core engine to provide very limi... | It depends on the platform. On win32, you call LoadLibrary to load a DLL, then get functions from it with GetProcAddress. On Unixy platforms, the equivalents are dlopen and dlsym.
|
212,006 | 212,022 | multiple definition error including c++ header file with inline code from multiple sources | I have a c++ header file containing a class.
I want to use this class in several projects, bu I don't want to create a separate library for it, so I'm putting both methods declarations and definitions in the header file:
// example.h
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
namespace test_ns{
class TestClass{
public:
... | These are not equivalent. The second example given has an implicit 'inline' modifier on the method and so the compiler will reconcile multiple definitions itself (most likely with internal linkage of the method if it isn't inlineable).
The first example isn't inline and so if this header is included in multiple transla... |
212,237 | 212,693 | Constants and compiler optimization in C++ | I've read all the advice on const-correctness in C++ and that it is important (in part) because it helps the compiler to optimize your code. What I've never seen is a good explanation on how the compiler uses this information to optimize the code, not even the good books go on explaining what happens behind the curtain... | Let's disregard methods and look only at const objects; the compiler has much more opportunity for optimization here. If an object is declared const, then (ISO/IEC 14882:2003 7.1.5.1(4)):
Except that any class member declared
mutable (7.1.1) can be modified, any
attempt to modify a const object
during its lifet... |
212,442 | 212,462 | How to create a for loop like command in C++? | I want to do something very simple in C++ but i can't find how.
I want to create a function like a for loop where i will ideally enter a variable for the times the iteration should happen and some functions inside brackets my function will execute. I hope i was clear enough. Thanks...
Example
superFor (1)
{
//command... | What you want isn't possible in C++ because the (current version of the) language lacks some features that are required here: namely, creating function blocks “on the fly”.
The best you can do is pass a function pointer or function object to your function. The STL offers many examples of this. Consider:
void out(int x)... |
212,492 | 254,915 | How do you add external libraries for compilation in VC++? | I've worked with a couple of Visual C++ compilers (VC97, VC2005, VC2008) and I haven't really found a clearcut way of adding external libraries to my builds. I come from a Java background, and in Java libraries are everything!
I understand from compiling open-source projects on my Linux box that all the source code ... | In I think you might be asking the mechanics of how to add a lib to a project/solution in the IDEs...
In 2003, 2005 and 2008 it is something similar to:
from the solution explorer - right click on the project
select properties (typically last one)
I usually select all configurations at the top...
Linker
Input
Additiona... |
212,645 | 214,078 | How does _ftime / Windows internal time work? | I have found an interesting issue in windows which allows me to cause the Windows clock (but not the hardware clocks) to run fast - as much as 8 seconds every minute. I am doing some background research to work out how Windows calculates and updates it's internal time (not how it syncs with an NTP servers). Any informa... | This MSDN article gives a very brief description of how the system time is handled: "When the system first starts, it sets the system time to a value based on the real-time clock of the computer and then regularly updates the time." Another interesting function is GetSystemTimeAdjustment, which has this to say:
A valu... |
212,669 | 212,747 | Do the concepts in Accelerated C++ Practical Programming by Example still hold up today? | I was recommeded a book called:
Accelerated C++ Practical Programming by Example
by Andrew Koenig and Barbara E. Moo
Addison-Wesley, 2000
ISBN 0-201-70353-X
The basis of this book is that Object Oriented Programming is highly wasteful memory-wise, and that most source-code should not be written this way, rather tha... | I haven't read the book, but I have trouble believe that they wrote a book whose "basis ...is that Object Oriented Programming is highly wasteful memory-wise" (Full disclosure: Andy & Barbara are friends of mine).
Andy would never say the OOP is wasteful of memory. He WOULD say that a particular algorithm or techniq... |
212,900 | 212,930 | Advantages of Antlr (versus say, lex/yacc/bison) | I've used lex and yacc (more usually bison) in the past for various projects, usually translators (such as a subset of EDIF streamed into an EDA app). Additionally, I've had to support code based on lex/yacc grammars dating back decades. So I know my way around the tools, though I'm no expert.
I've seen positive commen... | Update/warning: This answer may be out of date!
One major difference is that ANTLR generates an LL(*) parser, whereas YACC and Bison both generate parsers that are LALR. This is an important distinction for a number of applications, the most obvious being operators:
expr ::= expr '+' expr
| expr '-' expr
... |
212,990 | 212,997 | Simple C++ UML w/ reverse engineering | I need a way to build C++ code from UML diagrams and vice versa.
Should be simple too hopefully. I don't mind paying too much.
| You could try Sparx Enterprise Architect but the code quality would be average, not excellent.
I am not aware of any great automatic code generators for C++
Prices start from $135
|
213,121 | 213,135 | Use 'class' or 'typename' for template parameters? |
Possible Duplicate:
C++ difference of keywords ‘typename’ and ‘class’ in templates
When defining a function template or class template in C++, one can write this:
template <class T> ...
or one can write this:
template <typename T> ...
Is there a good reason to prefer one over the other?
I accepted the most popula... | Stan Lippman talked about this here. I thought it was interesting.
Summary: Stroustrup originally used class to specify types in templates to avoid introducing a new keyword. Some in the committee worried that this overloading of the keyword led to confusion. Later, the committee introduced a new keyword typename to r... |
213,256 | 213,507 | How to determine whether a Windows application is offscreen? | I am trying to debug a strange issue with users that have LogMeIn installed. After a few days, some of my dialogs that my app opens can end up offscreen. If I could reliable detect that, I could programmatically move the dialogs back where they are visible again.
Note: this has to work for multiple monitors and use the... | Simply use MonitorFromWindow with the MONITOR_DEFAULTTONULL flag. If the return value is null, your window is not visible. You can subsequently pass MONITOR_DEFAULTTONEAREST to be able to reposition your window on the nearest monitor.
|
213,761 | 213,811 | What are some uses of template template parameters? | I've seen some examples of C++ using template template parameters (that is templates which take templates as parameters) to do policy-based class design. What other uses does this technique have?
| I think you need to use template template syntax to pass a parameter whose type is a template dependent on another template like this:
template <template<class> class H, class S>
void f(const H<S> &value) {
}
Here, H is a template, but I wanted this function to deal with all specializations of H.
NOTE: I've been progr... |
213,952 | 214,093 | Do c++ static libraries without mfc that are linked to an MFC project throw bad_alloc or CMemoryException*? | I'm working on a large, aging code base for an MFC app. The code has been worked on by many developers over time, and as a result, we have three different ways throughout the code of dealing with the possibility of an allocation failure with new.
The first way is to test for NULL on the result of new. We don't use no... | It will depend on the compile options for the static libraries to be linked to the application.
If the libraries are compiled with a configuration to use the static Standard C++ run-time then I would expect the operator new from the Standard C++ run-time to be called.
If libraries are compiled with a configuration to u... |
213,953 | 214,222 | Boost phoenix or lambda library problem: removing elements from a std::vector | I recently ran into a problem that I thought boost::lambda or boost::phoenix could help be solve, but I was not able to get the syntax right and so I did it another way. What I wanted to do was remove all the elements in "strings" that were less than a certain length and not in another container.
This is my first try:
... | You need boost::labmda::bind to lambda-ify function calls, for example the length < 24 part becomes:
bind(&string::length, _1) < 24
EDIT
See "Head Geek"'s post for why set::find is tricky. He got it to resolve the correct set::find overload (so I copied that part), but he missed an essential boost::ref() -- which is ... |
213,957 | 213,971 | ClickOnce: getting MSVCRT C++ DLLs on user's machine | I've been trying desperately to get my application (15 C# dlls and 1 C++/CLI dll with C++ Runtime DLL dependencies) to deploy with ClickOnce. I got it to work by just copying the Release folder, but ClickOnce refuses to copy the files (msvcm80.dll, msvcp80.dll and msvcr80.dll) and deploy them in this folder.
I did this... | I'm stupid: I just found this:
On Publish tab of Properties page of my startup project: click Prerequisites... button > check Visual C++ Runtime Libraries, radio button setting: Download prerequisites from the component vendor's web site.
It seems to work the way one might expect!
|
214,230 | 214,242 | <iostream> vs. <iostream.h> vs. "iostream.h" | When including a header file in C++, what's the difference between...
including the .h part versus not including .h part when wrapping it in <> signs?
#include <iostream> vs. #include <iostream.h>
wrapping the header name in double quotes versus wrapping it in < > signs?
#include <iostream.h> vs. #include "iostream.h... | In short:
iostream.h is deprecated—it is the original Stroustrup version. iostream is the version from the standards committee. Generally, compilers point them both to the same thing, but some older compilers won't have the older one. In some odd cases, they will both exist and be different (to support legacy code) a... |
214,411 | 214,422 | Embedding Flash Player in a C++ or Java application? | I would like to embed Flash Player directly inside a C++ or Java application.
I found an article that describes how to do this for C#:
http://www.adobe.com/devnet/flash/articles/stock_history03.html
Unfortunately, I have no experience with C#, COM or ActiveX. I need someone to translate this code to C++, allowing me to... | I don't know how to embed flash in C++, but Christopher Deckers (of SWTSwing fame) has developed an interesting hack which allows it to be embedded in Java. You can find more information in the Javalobby announcement thread.
Here is an updated link: https://github.com/Chrriis/DJ-Native-Swing
|
214,687 | 214,860 | Saving an array of colour data as a PNG file on DS | I'm looking for a library to save an array of colour data to a PNG file. (That's all there is to it, right? I know very little about the internals of a PNG.)
This is for use in Nintendo DS development, so something lightweight is preferable. I don't need any other fancy features like rotation, etc.
| To encode any kind of PNG file, libpng is the way of the walk.
However, on small devices like the DS you really want to store your image data in the format which the display hardware expects. It is technically possible to get libpng working on the platform, but it will add significant overhead, both in terms of loadtim... |
214,706 | 214,707 | C or C++ BigInt library on Microsoft Windows | What arbitrary-precision integers (and or rationals) library are there for compilers running on Microsoft Windows, and which would you recommend?
Please state license type / cost, supported compilers (i.e. GCC and or VC++) for the library.
| GMP.
LGPL. Standard download from official website is designed for GCC. VC++ port is available from here.
|
214,891 | 214,966 | Checklist for writing copy constructor and assignment operator in C++ | Please write a list of tasks that a copy constructor and assignment operator need to do in C++ to keep exception safety, avoid memory leaks etc.
| First be sure you really need to support copy. Most of the time it is not the case, and thus disabling both is the way to go.
Sometimes, you'll still need to provide duplication on a class from a polymorphic hierarchy, in that case: disable the assignment operator, write a (protected?) copy constructor, and provide a v... |
214,927 | 214,933 | Do you prefer explicit namespaces or 'using' in C++? | When using C++ namespaces, do you prefer to explicitly name them, like this:
std::cout << "Hello, world!\n";
Or do you prefer using namespace:
using namespace std;
cout << "Hello, world!\n";
And if if you prefer the latter, do you declare your usings at file or function scope?
Personally I prefer to explicitly name t... | I always use using namespace for std & boost. Everything else I tend to use an explicit namespace unless it is used so much that it would clutter up the code.
In headers, I never use using namespace to avoid polluting the global namespace of the #including source.
|
215,110 | 215,117 | Scatter Plots in C++ | What is the best way to graph scatter plots in C++?
Do you write data to a file and use another tool? Is there a library like matplotlib in Python?
| I always write out data and then using gnuplot to create my graphs. It is by far the best way I have found of producing graphs in a variety of formats: eps, png, jpeg, xpm, you name it.
gnuplot will do scatter plot very easily. Provided the x and y values are in 2 space-separated columnss, then
plot "data.txt" using 1:... |
215,430 | 215,432 | What type for an integer of more than 4 bytes? | I have to use unsigned integers that could span to more than 4 bytes, what type should I use?
PS Sorry for the "noobism" but that's it :D
NB: I need integers because i have to do divisions and care only for the integer parts and this way int are useful
| long long, 64 bit integer... here you can find some reference about the data types and ranges...
|
215,684 | 215,692 | Requirement for key in std::multimap | I have a std::multimap where key is a custom class. Something like this:
Class X {
public:
std::string s;
int x;
operator <(const X& other) const { return s < other.s; }
};
std::multimap<X, int> mymap;
Now, I'd like to use upper_bound and lower_bound to iterate over all elements with the same value of "s".... | Since class X is the key for the multimap, the parameter to upper_bound()/lower_bound() needs to be of that type. If class X has an implicit conversion from std::string (which is the type of X::s) then you can use that as the parameter to upper_bound()/lower_bound().
The default comparison for multimap is less<> which... |
215,752 | 215,874 | Python embedded in CPP: how to get data back to CPP | While working on a C++ project, I was looking for a third party library for something that is not my core business. I found a really good library, doing exactly what's needed, but it is written in Python. I decided to experiment with embedding Python code in C++, using the Boost.Python library.
The C++ code looks somet... | First of all, change your function to return the value. printing it will complicate things since you want to get the value back. Suppose your MyModule.py looks like this:
import thirdparty
def MyFunc(some_arg):
result = thirdparty.go()
return result
Now, to do what you want, you have to go beyond basic embedd... |
215,961 | 216,813 | Variable naming schemes for objects in C++? | I am implementing a BFS, and what it is going to do is go through an ordered tree to find the shortest solution to a puzzle.
What i will be doing is creating a Snapshot object that holds the current position of each piece in a puzzle. I will add this Snapshot object into the queue and check if it is the solution. Howev... | There is a way - you use the Preprocessor's Token-Pasting Operator. This allows you to create a name based on a variable, so you'd specify:
#define S(variable) snapshot#variable
and you'd be able to create variables named snapshot1, snapshot2 etc:
Snapshot S(1)
Snapshot S(2)
However, I'm not sure this is what you rea... |
216,068 | 216,072 | Parsing integers from a line | I am parsing an input text file. If I grab the input one line at a time using getline(), is there a way that I can search through the string to get an integer? I was thinking something similar to getNextInt() in Java.
I know there has to be 2 numbers in that input line; however, these values will be separated by one... | If the only thing in there is whitespace and integers, just try something like this:
int i1, i2;
stringstream ss(lineFromGetLine);
ss >> i1 >> i2;
or easier:
int i1, i2;
theFileStream >> i1 >> i2;
|
216,124 | 216,154 | Question about shallow copy in C++ | Say I have a struct "s" with an int pointer member variable "i". I allocate memory on the heap for i in the default constructor of s. Later in some other part of the code I pass an instance of s by value to some function. Am I doing a shallow copy here? Assume I didn't implement any copy constructors or assignment ... | To follow up on what @[don.neufeld.myopenid.com] said, it is not only a shallow copy, but it is either (take your pick) a memory leak or a dangling pointer.
// memory leak (note that the pointer is never deleted)
class A
{
B *_b;
public:
A()
: _b(new B)
{
}
};
// dangling ptr (who deletes the instance?)
cl... |
216,259 | 216,266 | Is there a max array length limit in C++? | Is there a max length for an array in C++?
Is it a C++ limit or does it depend on my machine? Is it tweakable? Does it depend on the type the array is made of?
Can I break that limit somehow or do I have to search for a better way of storing information? And what should be the simplest way?
What I have to do is storing... | There are two limits, both not enforced by C++ but rather by the hardware.
The first limit (should never be reached) is set by the restrictions of the size type used to describe an index in the array (and the size thereof). It is given by the maximum value the system's std::size_t can take. This data type is large enou... |
216,450 | 216,464 | GCC and ld can't find exported symbols...but they're there | I have a C++ library and a C++ application trying to use functions and classes exported from the library. The library builds fine and the application compiles but fails to link. The errors I get follow this form:
app-source-file.cpp:(.text+0x2fdb): undefined reference to `lib-namespace::GetStatusStr(int)'
Classes in ... | the U before _ZN3lib-namespace12GetStatusStrEi in the nm output shows that the symbol is undefined in the library.
Maybe it's defined in the wrong namespace: it looks like you're calling it in lib-namepace but you might be defining it in another.
|
216,748 | 216,760 | Pros and cons of using nested C++ classes and enumerations? | What are the pros and cons of using nested public C++ classes and enumerations? For example, suppose you have a class called printer, and this class also stores information on output trays, you could have:
class printer
{
public:
std::string name_;
enum TYPE
{
TYPE_LOCAL,
TYPE_NETWORK,
... | Nested classes
There are several side effects to classes nested inside classes that I usually consider flaws (if not pure antipatterns).
Let's imagine the following code :
class A
{
public :
class B { /* etc. */ } ;
// etc.
} ;
Or even:
class A
{
public :
class B ;
// etc.
} ;
class A::B
{
... |
217,073 | 217,171 | Partial sort of std::list | I have a linked list that I want to sort part of, eg:
std::sort(someIterator, otherIterator, predicate);
std::sort requires random-access iterators so this approach doesn't work. There is a specialisation std::list::sort, but that can only sort the entire list. I don't think I have enough access to the list members to... | How about unhooking the part of the list that you want sorted, into a standalone list,
then use the specialized list sort, then hook it back into the original list?
|
217,463 | 217,474 | How do you configure the email settings in CrashRpt to send the crash dump? | After reading this discussion and this discussion about using CrashRpt to generate a crash dump and email it to the developers, I've been having a difficult time finding any instructions/tutorials for configuring the email settings used by the library to send the email.
When you call the install() function to initializ... | What CrashRpt does for emailing:
The email system simply uses MAPI to send your email. Which would try to use your default mail client if you have one, and if it supports MAPI. Take a look at MailMsg.cpp for details.
Personal experience:
In my company's usage of CrashRpt, we modified it a bit though to call a web ... |
217,532 | 217,649 | What are the possible classes for the OpenThemeData function? | I'm trying to call the OpenThemeData (see msdn OpenThemeData) function but I couldn't determine what are the acceptable Class names to be passed in by the pszClassList parameter.
HTHEME OpenThemeData(
HWND hwnd,
LPCWSTR pszClassList
);
Could anybody tell me what are the acceptable class names that I can ... | You can look in "AeroStyle.xml" as a previous poster noted, which gives an exact list for Vista/Aero. However, if you want to play safe (and you probably do) the class names should, in general, be Windows class names of Windows common controls. For example, push buttons and check boxes use the class name "Button", the ... |
217,892 | 217,904 | What is a safe equivalent of non-void STL erase? | Suppose I have a hash_map and a code like
// i is an iterator
i = hash_map.erase(i)
But GCC's STL doesn't return iterator in erase, but a void. Now is a code like
hash_map.erase(i++)
safe (i.e. does not invalidate the iterator or does any other unexpected or unpleasant things)? Please note this is a hash_map.
| Yes, this is safe, because the value of i will have been set to the next value, before the current value is erased.
According to the SGI documentation about hashed containers invalidation does not occur for non-erased elements, nor even for resizing (there is no word on whether insertions cause resizing, so to be caref... |
217,901 | 217,922 | c++ template function overloading | Below are lines from "the c++ programming language"
template<class T > T sqrt(T );
template<class T > complex<T> sqrt(complex<T>);
double sqrt(double);
void f(complex<double> z )
{
s q r t (2 ); // sqrt<int>(int)
sqrt(2.0) ; // sqrt(double)
sqrt(z) ; // sqrt<double>(complex<double>)
}
I dont understand why sqrt(z) ; c... | Well, the function used is the one you are talking about sqrt<double>(complex<double>) is an instance of the template template <class T> complex<T> sqrt(complex<T>).
Your misunderstanding was in the signification of the template instance and not in the overloading process.
|
217,911 | 217,934 | Why don't C++ compilers define operator== and operator!=? | I am a big fan of letting the compiler do as much work for you as possible. When writing a simple class the compiler can give you the following for 'free':
A default (empty) constructor
A copy constructor
A destructor
An assignment operator (operator=)
But it cannot seem to give you any comparison operators - such a... | The compiler wouldn't know whether you wanted a pointer comparison or a deep (internal) comparison.
It's safer to just not implement it and let the programmer do that themselves. Then they can make all the assumptions they like.
|
218,003 | 218,014 | Searching CStrings in C++ | I was wondering if there is a native C++ (or STL/Boost) function which will search a CString for a specified string?
e.g.
CString strIn = "Test number 1";
CString strQuery = "num";
bool fRet = SomeFn(strIn, StrQuery);
if( fRet == true )
{
// Ok strQuery was found in strIn
...
I have found a small number of functi... | CString::Find() is what you want, one of the overloads does sub-string searching.
CString strIn = "test number 1";
int index = strIn.Find("num");
if (index != -1)
// ok, found
|
218,226 | 218,250 | Visual C++ 2008 'Release' build contains debug information | I've noticed that when generating a new C++ project using MS Visual Studio 2008, the Release build contains debugging symbols - specifically the following settings are enabled:
The C++/General/Debug Information Format is set to Program Database.
The Linker/Debugging/Generate Debug Info setting is set to Yes.
I have n... | We have turned on those settings in our commercial releases for years now with no apparent downside. The upsides are enormous,though.
We have integrated a crash dump packager that packages the dump along with some other information and emails it (with the user's consent) to a company inbox. This has helped us find... |
218,488 | 218,720 | Finding "best matching key" for a given key in a sorted STL container | Problem
I have timestamped data, which I need to search based on the timestamp in order to get the one existing timestamp which matches my input timestamp the closest.
Preferably this should be solved with the STL. boost::* or stl::tr1::* (from VS9 with Featurepack) are also possible.
Example of timestamped data:
struc... | I would use set::lower_bound to find the matching or greater value, then decrement the iterator to check the next lower value. You should use std::set rather than std::map since your key is embedded in the object - you'll need to provide a functor that compares the timestamp members.
struct TimestampCompare
{
bool... |
218,786 | 218,817 | Concurrent programming c++? | I keep on hearing about concurrent programing every where.
Can you guys throw some light on what it's and how c++ new standards facilitate doing the same?
| Concurrency is about your code doing multiple things at the same time. This is typically done with explicit "threads", but there are other possibilities. For example, if you use OpenMP directives in your code then a compiler that supports OpenMP will automatically generate threads for you.
Thread is short for "thread o... |
218,951 | 221,409 | Simple Model Checker Tool | Is there a simple Model Checker tool. I am planning to implement a model checker tool which will analyze the code for some of the predefined properties.
| One important tool is SPIN, with the Promela language. If you use LaTeX, there is also TLA+.
These will not analyse your code, but will let you express a model for your assumtions and state transitons, and will then analyse for invalid states. In other words, they will detect problems in your model, not the implement... |
219,139 | 220,220 | Polymorphic functors in std::for_each | I'm trying to use stl algorithm for_each without proliferating templates throughout my code. std::for_each wants to instantiate MyFunctor class by value, but it can't since its abstract. I've created a functor adapter class which passes a pointer around and then derefernces it when appropriate.
My Question:
Does the S... | tr1::ref may help you here --- it's meant to be a reference wrapper so that you can pass normal objects by reference to bind or function objects (even abstract ones) by reference to standard algorithms.
// requires TR1 support from your compiler / standard library implementation
#include <functional>
void applyToAll(M... |
219,726 | 221,208 | VCL alternative to IStorage | To preface I am using Borland C++ and the VCL.
I need some sort of structured storage object which can be saved to disk as a single file and can contain multiple named blobs of binary data which I can programatically enumerate, access and manipulate.
The IStorage interface seems to be close what I want but I would pref... | A zip file is de facto a standard container, and it seems you can get a TStream interface to them: http://www.tek-tips.com/faqs.cfm?fid=6734
|
219,770 | 219,791 | Dealing with C++ "initialized but not referenced" warning for destruction of scope helpers? | In Visual Studio, I often use objects only for RAII purposes. For example:
ScopeGuard close_guard = MakeGuard( &close_file, file );
The whole purpose of close_guard is to make sure that the file will be close on function exit, it is not used anywhere else. However, Visual Studio gives me a warning that a "local vari... | Method 1: Use the #pragma warning directive.
#pragma warning allows selective modification of the behavior of compiler warning messages.
#pragma warning( push )
#pragma warning( disable : 4705 ) // replace 4705 with warning number
ScopeGuard close_guard = MakeGuard( &close_file, file );
#pragma warning( pop )
This c... |
219,914 | 219,956 | What use are const pointers (as opposed to pointers to const objects)? | I've often used pointers to const objects, like so...
const int *p;
That simply means that you can't change the integer that p is pointing at through p. But I've also seen reference to const pointers, declared like this...
int* const p;
As I understand it, that means that the pointer variable itself is constant -- yo... | When you're designing C programs for embedded systems, or special purpose programs that need to refer to the same memory (multi-processor applications sharing memory) then you need constant pointers.
For instance, I have a 32 bit MIPs processor that has a little LCD attached to it. I have to write my LCD data to a spe... |
220,040 | 221,061 | how to get as much as possible from dbx | I do TDD on a daily basis for my C++ development on Solaris10. It has greatly reduced the time I have to spend using my debugger but sometime this is the only option.
DBX is pretty powerful but not that user friendly. Note that I'm talking about console DBX not the SunStudio GUI for DBX).
What are the best productivity... | I have bookmarked a few sites related to dbx. Here they are, in no particular order in case they might be useful to you:
Why Can't dbx Find My Function?
Online Help for the Dbx Debugger
Sun Studio: debugging a multi-threaded application w/ dbx
gdb vs. dbx: commands mapping and feature comparison
Importing debug inform... |
220,323 | 220,908 | Determine Process Info Programmatically in Darwin/OSX | I have a class with the following member functions:
/// caller pid
virtual pid_t Pid() const = 0;
/// physical memory size in KB
virtual uint64_t Size() const = 0;
/// resident memory for this process
virtual uint64_t Rss() const = 0;
/// cpu used by this process
virtual double PercentCpu() const = 0;
/// mem... | Process info comes from pidinfo:
cristi:~ diciu$ grep proc_pidinfo /usr/include/libproc.h
int proc_pidinfo(int pid, int flavor, uint64_t arg, void *buffer, int buffersize);
cpu load comes from host_statistics:
cristi:~ diciu$ grep -r host_statistics /usr/include/
/usr/include/mach/host_info.h:/* host_statistics() *... |
220,423 | 220,434 | How do you deal with NUL? | From time to time, I run into communications issue with other programmers, when we talk about NULL. Now NULL could be
a NULL pointer
the NUL character
an empty data element in some sort of database.
NUL seems to be the most confusing. It is the ASCII character 0x00.
I tend to use '\0' in my code to represent... | I use '\0' for the nul-character and NULL for pointers because it is clearest in both cases.
BTW, both 0 and '\0' are ints in C and either one will be converted to char when stored in a char variable.
|
220,718 | 220,722 | Using set.insert( key ) as a conditional? | I am trying to use set.insert (key) as a conditional, where if the key is inserted correctly (meaning that the key does NOT already exist in the set ) then it should go on and perform some kind of code. For example, something like:
if (set.insert( key )) {
// some kind of code
}
Is this allowed? Because the compil... | The version of insert that takes a single key value should return a std::pair<iterator,bool>, where the bool indicates whether an insertion was made. A value of true indicates that the value was inserted, and false indicates that the value was already present. So your conditional would look like this:
if( set.insert( k... |
220,752 | 221,038 | What is the C++03 memory model for concurrency? | What is the memory model for concurrency in C++03?
(And, does C++11 change the memory model to support concurrency better?)
| The C++ memory model is the specification of when and why physical memory is read/written with respect to C++ code.
Until the next C++ standard, the C++ memory model is the same as C. In the C++0x standard, a proper memory model for multithreading is expected to be included (see here), and it will be part possibly of t... |
220,832 | 220,837 | Easy way to shift specific characters in a string in C++? | If I have the string .....ZZ..ZZ..... or .Z.1.Z.23Z.4.Z55,
Is there an easy way of shifting all Zcharacters in the string one space right of the current position?
Some additional test strings are:
.Z
Z.
ZZ.
.ZZ
Z
ZZ
ZZZ
I think a few of the higher voted answers to this question (including the currently accepted one) ... | Just iterate through the text and swap characters:
int main ()
{
char text[] = "...Z.Z.Z...", temp;
int text_len = strlen (text), i;
for (i = text_len - 1; i >= 0; i--)
{
if (text[i] == 'Z')
{
temp = text[i+1];
text[i+1] = text[i];
text[i] ... |
220,884 | 221,026 | Should my C++ program support IA64 or only x64? | Should my program support IA64, or should it only support x64?
I haven't been able to easily find IA64 computers myself. Is IA64 dead?
MS seems to have a wide support for IA64, but it took me a long time to be able to find an IA64, and I had to end up getting it on eBay.
| What kind of software do you develop? If it's not a data center type of application or a high-end number crunching app, I'd be surprised if there were any demand for an ia64 version. And even then, I'd think it would be a situation where if you have to ask if you should support it, you probably don't need to.
A couple... |
220,891 | 220,962 | In what syntax should a COM SDK reference document be written? | I have a COM SDK written in C++ and I'd like to create documentation for my product. I understand that most people will probably not use C++ for integration with this COM component, but many will.
Which method is best to describe the API, without losing details that a C++ developer would need to know.
| You can write the documentation directly in the IDL using the helpstring attributes - most consumers of your code will be able to read this directly using e.g., OLE View or in their object browser. Our company wrote an internal tool to extract the helpstring documentation and turn it into internal reference documentat... |
221,185 | 221,257 | How can I compile and run C/C++ code in a Unix console or Mac terminal? | How can I compile/run C or C++ code in a Unix console or a Mac terminal?
| If it is a simple single-source program,
make foo
where the source file is foo.c, foo.cpp, etc., you don’t even need a makefile. Make has enough built-in rules to build your source file into an executable of the same name, minus the extension.
Running the executable just built is the same as running any program - but ... |
221,281 | 221,325 | Converting Simplifed Chinese GB 2312 text characters into UTF8 | How do I convert text between multi-byte text strings, for example Simplified Chinese GB 2312, into UTF8 using c++ ?
| On unix systems you'd best use the iconv library.
See iconv_open, iconv, iconv_close
You'd have to know the character encoding of course (EUC-CN, HZ).
If not on a unix system, search for some support in the OS, doing character conversions by hand is very hard to get right.
|
221,346 | 221,351 | What can I use instead of the arrow operator, `->`? | What is the arrow operator (->) a synonym for?
| The following two expressions are equivalent:
a->b
(*a).b
(subject to operator overloading, as Konrad mentions, but that's unusual).
|
221,482 | 221,548 | Unit testing with C/C++: Lessons, what to remember? | Unit testing with C/C++:
What do you teach people who either did not do unit testing before or come from Java/Junit?
What is the single most important lesson / thing to remember/ practice from your point of view that saves a lot of time or stress (especially regarding C/C++)?
|
Unit tests have to run automatically on every checkin (or, unit tests that are written then forgotten are not unit tests).
Before fixing a bug, write a unit test to expose it (it should fail). Then fix the bug and rejoice as the test turns green.
It's OK to sacrifice a bit of "beauty" of a class for easier testing (li... |
221,894 | 221,934 | C++: Get MAC address of network adapters on Vista? | We are currently using the NetBios method, and it works ok under XP. Preliminary tests under Vista show that it also works, but there are caveats - NetBIOS has to be present, for instance, and from what I've been reading, the order of the adapters is bound to change. Our alternative method - with SNMPExtensionQuery - s... | Could you use the WMIService? I used it to get the mac-address of a machine in pre-Vista days though.
|
221,950 | 221,961 | Operations on arbitrary value types | This article describes a way, in C#, to allow the addition of arbitrary value types which have a + operator defined for them. In essence it allows the following code:
public T Add(T val1, T val2)
{
return val1 + val2;
}
This code does not compile as there is no guarantee that the T type has a definition for the '+'... | Due to the way templates are compiled in C++, simply doing:
template < class T >
T add(T const & val1, T const & val2)
{
return val1 + val2;
}
will work, you'll get a compile error for every type where an operator+ is not defined.
C++ templates generate code for every type instantiation, so for every type T code w... |
222,175 | 222,213 | Why destructor is not called on exception? | I expected A::~A() to be called in this program, but it isn't:
#include <iostream>
struct A {
~A() { std::cout << "~A()" << std::endl; }
};
void f() {
A a;
throw "spam";
}
int main() { f(); }
However, if I change last line to
int main() try { f(); } catch (...) { throw; }
then A::~A() is called.
I am compil... | The destructor is not being called because terminate() for the unhandled exception is called before the stack gets unwound.
The specific details of what the C++ spec says is outside of my knowledge, but a debug trace with gdb and g++ seems to bear this out.
According to the draft standard section 15.3 bullet 9:
9 If n... |
222,189 | 222,234 | Is it correct to export data members? (C++) | As the title suggests, is it correct or valid to import/export static data from within a C++ class?
I found out my problem - the author of the class I was looking at was trying to export writable static data which isn't supported on this platform.
Many thanks for the responses however.
| Is it correct inasmuch as it'll work and do what you expect it to? Assuming that you are talking about using _declspec(dllexport/dllimport) on a class or class member, yes, you can do that and it should give you the expected result - the static data would be accessible outside your dll and other C++ code could access i... |
222,195 | 222,288 | Are there gotchas using varargs with reference parameters | I have this piece of code (summarized)...
AnsiString working(AnsiString format,...)
{
va_list argptr;
AnsiString buff;
va_start(argptr, format);
buff.vprintf(format.c_str(), argptr);
va_end(argptr);
return buff;
}
And, on the basis that pass by reference is preferred where possible, I changed... | If you look at what va_start expands out to, you'll see what's happening:
va_start(argptr, format);
becomes (roughly)
argptr = (va_list) (&format+1);
If format is a value-type, it gets placed on the stack right before all the variadic arguments. If format is a reference type, only the address gets placed on the sta... |
222,471 | 222,494 | Setting up a Programming Environment in Linux | I recently started using Linux as my primary OS. What are the tools that I will need to set up a complete programming environment in Linux for C and C++?
| Standard stuff:
The compiler tools, gcc, gdb, etc.
Some sort of editor/IDE (emacs, vim, eclipse)
Profiling tools
Source Control (SubVersion, git, etc)
Language specific tools, like easy_install for python (you said C/C++, but the same goes for everything)
A web server maybe? Apache, Lighttpd, nginx
Any libraries you'l... |
222,557 | 222,578 | What uses are there for "placement new"? | Has anyone here ever used C++'s "placement new"? If so, what for? It looks to me like it would only be useful on memory-mapped hardware.
| Placement new allows you to construct an object in memory that's already allocated.
You may want to do this for optimization when you need to construct multiple instances of an object, and it is faster not to re-allocate memory each time you need a new instance. Instead, it might be more efficient to perform a single ... |
222,667 | 222,687 | XML-RPC library for C++ | What libraries are available for writing xml-rpc clients in native C++ or C?
| You might want to check out either xmlrpc-c or xmlrpc++.
|
222,916 | 222,926 | In a multi-threaded C++ app, do I need a mutex to protect a simple boolean? | I have a multi-threaded C++ app which does 3D rendering with the OpenSceneGraph library. I'm planning to kick off OSG's render loop as a separate thread using boost::threads, passing a data structure containing shared state in to the thread. I'm trying to avoid anything too heavyweight (like mutexes) for synchronizatio... | In C++11 and later, which has standards-defined concurrency, use std::atomic<bool> for this purpose. From http://en.cppreference.com/w/cpp/atomic/atomic:
If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined (see memory model for details on data races).
The followi... |
223,021 | 223,047 | What's the scope of the "using" declaration in C++? | I'm using the 'using' declaration in C++ to add std::string and std::vector to the local namespace (to save typing unnecessary 'std::'s).
using std::string;
using std::vector;
class Foo { /*...*/ };
What is the scope on this declaration? If I do this in a header, will it inject these 'using' declarations into every ... | When you #include a header file in C++, it places the whole contents of the header file into the spot that you included it in the source file. So including a file that has a using declaration has the exact same effect of placing the using declaration at the top of each file that includes that header file.
|
223,215 | 223,230 | C++ example of Coding Horror or Brilliant Idea? | At a previous employer, we were writing binary messages that had to go "over the wire" to other computers. Each message had a standard header something like:
class Header
{
int type;
int payloadLength;
};
All of the data was contiguous (header, immediately followed by data). We wanted to get to the payload g... | I'd go for crime against coding.
Both methods will generate the exact same object code. The first makes it's intention clear. The second is very confusing, with the only advantage that it saves a couple keystrokes. (Just learn to freakin' type).
Also, note that NEITHER method is guaranteed to work. The sizeof() an o... |
223,314 | 224,393 | How to create an empty DOMElement | I am using Xerces-c in my project, and would like to create a single DOMElement without having to create a whole new DOMDocument. Is such a thing possible?
| I haven't seen a way. AFAIK the DOMDocument acts as the "memory pool" and all elements are created in this pool. In the Xerces docs we see:
Objects created by DOMDocument::createXXXX
Users can call the release() function to indicate the release of any orphaned nodes. When an orphaned Node is released, its associate... |
223,421 | 224,705 | Adding unit tests to an existing project | My question is quite relevant to something asked before but I need some practical advice.
I have "Working effectively with legacy code" in my hands and I 'm using advice from the book as I read it in the project I 'm working on. The project is a C++ application that consists of a few libraries but the major portion of ... | If your test app is only linking the object files it needs to test then you are effectively already treating them as a library, it should be possible to group those object files into a separate library for the main and the test app. If you can't then I don't see that what you are doing is too bad an alternative.
If you... |
223,634 | 223,665 | Linux programming environment configuration | The other day I set up an Ubuntu installation in a VM and went to gather the tools and libraries I figured I would need for programming mostly in C++.
I had a problem though, where to put things such as 3rd party source libraries, etc. From what I can gather, a lot of source distributions assume that a lot of their dep... | Short answer: don't do a "heaps of code in local dir" thing.
Long answer: don't do a "heaps of code in local dir" thing, because it will be nightmare to keep up-to-date, and if you decide to distribute your code, it will be nightmare to package it for any decent distribution.
Whenever possible, stick to the libraries s... |
223,919 | 223,943 | Having trouble linking a static library C++ | I've figured out how to set VC++ to compile code into a .lib file instead of a .exe, but I'm having trouble getting a lib to link together with my other .obj files.
Here is how I have the library and application folders set up. (I'm not sure if this is right)
AppFolder
App.sln
App.ncb
*.h
*.cpp
Debug
*.o... | On the project properties:
Configuration Properties -> Linker -> Input -> Additional Dependancies
Add it in there.
Or, in your .h file for the library, add:
#pragma comment(lib, "Library")
This will do it automatically for you.
|
224,043 | 224,063 | Timer in a win32 service | Can someone please point me to the easiest way to have a timer in a Win32 service?
I suppose I could create a dummy window for this purpose or have a second thread do tick counts, but what's best? Is there a more elegant way?
Thanks in advance.
| You can use Timer Queues (http://msdn.microsoft.com/en-us/library/ms686796.aspx). They don't require an HWND.
|
224,090 | 343,141 | local variables in constructors are not followed. Is this a bug in gdb ? | I am currently running gdb version 6.7.1 on Ubuntu Linux, and working in a C++ project.
Surprisingly I was trying to debug a constructor and I have found that local variables declared within the scope of the constructor are not followed or noticed by gdb. Is this a bug ?
Thanks for any information ..
| It is a bug in GCC, not in GDB.
It was recently fixed.
|
224,163 | 224,177 | Capturing R6025 pure virtual call | I currently capture MiniDumps of unhandled exceptions using SetUnhandledExceptionFilter however at times I am getting "R6025: pure virtual function".
I understand how a pure virtual function call happens I am just wondering if it is possible to capture them so I can create a MiniDump at that point.
| If you want to catch all crashes you have to do more than just: SetUnhandledExceptionFilter
I would also set the abort handler, the purecall handler, unexpected, terminate, and invalid parameter handler.
#include <signal.h>
inline void signal_handler(int)
{
terminator();
}
inline void terminator()
{
int*z = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.