question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,953,610 | 1,953,630 | C++: decoupling of interface / implementation w/o using virtual functions? | I've been spoiled using Java in the last few months! I have a C++ project where I would like to decouple a class interface (.h file) from its implementation details. But the class's member fields have to be in its declaration, and it seems like I have this unavoidable dependency linking if I want to tweak the class's m... | You want the PIMPL idiom.
|
1,953,621 | 1,953,708 | Reinterpret float vector as unsigned char array and back | I've searched and searched stackoverflow for the answer, but have not found what I needed.
I have a routine that takes an unsigned char array as a parameter in order to encode it as Base64. I would like to encode an STL float vector (vector) in Base64, and therefore would need to reinterpret the bytes in the float vect... | std::vector guarantees the data will be contiguous, and you can get a pointer to the first element in the vector by taking the address of the first element (assuming it's not empty).
typedef unsigned char byte;
std::vector<float> original_data;
...
if (!original_data.empty()) {
const float *p_floats = &(original_data... |
1,953,631 | 1,953,781 | QFileDialog: adding extension automatically when saving file? | When using a QFileDialog to save a file and to specify the extension (like *.pdf) and the user types in a name without this extension, also the saved file hasn't this extension.
Example-Code:
QFileDialog fileDialog(this, "Choose file to save");
fileDialog.setNameFilter("PDF-Files (*.pdf)");
fileDialog.exec();
QFile pdf... | You could use QFileDialog::setDefaultSuffix():
This property holds suffix added to the filename if no other suffix was specified.
This property specifies a string that will be added to the filename if it has no suffix already. The suffix is typically used to indicate the file type (e.g. "txt" indicates a text file).
|
1,953,639 | 1,953,738 | Is it safe to cast SOCKET to int under Win64? | I’m working on a Windows port of a POSIX C++ program.
The problem is that standard POSIX functions like accept() or bind() expect an ‘int’ as the first parameter while its WinSock counterparts use ‘SOCKET’.
When compiled for 32-bit everything is fine, because both are 32bit, but under Win64 SOCKET is 64 bit and int re... | This post seems by the to be repeating the information on kernel objects at msdn:
Kernel object handles are process specific. That is, a process must either create the object or open an existing object to obtain a kernel object handle. The per-process limit on kernel handles is 2^24.
The thread goes on to cite Windo... |
1,954,169 | 1,960,646 | Returning Garbage value c++ | I have a method that is suppose to return a garbage value if an item in a tree is not found. All I'm getting though is a runtime exception: "garbage is being used without being defined"
ItemType BstClass::rRetrieve(node* trav, KeyType key, bool& inTree)
{
if(trav == NULL)
{
inTree = false;
ItemT... | The answer depends on details of class ItemType which we don't have access to. Depending on what sort of operations you can do with ItemType and what sort of requirements you have about the 'garbage' value, you theoretically have a couple of choices.
Directly construct and return your 'garbage' value. Something like... |
1,954,249 | 1,954,281 | Iterator and constant interator in C++ | Whats the difference?
I want to be able to see if an element is in a HashMap and I just found out that if I do h[element], it will return the default element if it is not found, and not null. How would I use the iterator find method to see if the element is there?
Thanks
| Assuming you're talking about STL and not some 3rd party library... m[key] doesn't just return the default object if key isn't in the map. It will create a new element in the map with that key and a default-constructed object as value.
You could use this:
map<string, int> mymap;
//add items to it
map<string, int>::iter... |
1,954,404 | 1,954,479 | Program that modifes string inside its exe | I looking for example of program, that modifies a string inside its exe.
I work with C++, Visual Studio under Windows.
I searched working examples in Windows, but I can't find any working code.
I need simple code, that will ask user for string:
string strTest = "";
(if strTest != "")
{
cout << "Modified: " << strTes... | When an EXE is running on a Windows machine, the exe file is held open as a CreateFileMapping object with pages marked either as READONLY or COPY_ON_WRITE.
So when the exe writes to itself, the file is not modified. It just creates a new page backed by the swap file. But since the file is kept open, no-one else can o... |
1,954,699 | 1,954,880 | Audio track in video file - C++ | My application is transforming an AVI video file into another AVI file. I use
the OpenCV library. Unfortunately videos created with OpenCV have no sound as the library does not support audio.
Is there any easy way to copy the audio track from one video file to another? Maybe FFmpeg?
My application is written in Visual... | You can use FFmpeg. The easiest way would be to just use the command line tool to extract/reassemble. If you need your application to do it itself, looking into the sources for how they do it should help.
Alternatively, as you mention VC++, why not use DirectShow? It should not be too difficult to sink the audio into a... |
1,954,718 | 1,954,733 | How to get the elements in a set in C++? | I am confused as to how to get the elements in the set. I think I have to use the iterator but how do I step through it?
| Replace type with, for example, int.. And var with the name of the set
for (set<type>::iterator i = var.begin(); i != var.end(); i++) {
type element = *i;
}
The best way though is to use boost::foreach. The code above would simply become:
BOOST_FOREACH(type element, var) {
/* Here you can use var */
}
You can a... |
1,954,779 | 1,955,418 | Passing a pointer from C to assembly | I want to use "_test_and_set lock" assembly language implementation with atomic swap assembly instruction in my C/C++ program.
class LockImpl
{
public:
static void lockResource(DWORD resourceLock )
{
__asm
{
InUseLoop: mov eax, 0;0=In Use
xchg eax, resourceLock
... | The main problems with the original version in the question is that it needs to use register indirect addressing and take a reference (or pointer parameter) rather than a by-value parameter for the lock DWORD.
Here's a working solution for Visual C++. EDIT: I have worked offline with the author and we have verified the... |
1,954,853 | 1,955,253 | Does C++ programmer simulate features of Java? | As I read in Thinking in java,
Interface and inner class provide more
sophisiticated ways to organize and
control the objects in your
system. C++, for example, does not
contain such mechanisms, although the
clever programmer may simulate them.
Is it true that C++ programmer simluate features that java owns,... | I have to say "good" Java design is almost uniformly terrible. I've never seen so much code duplication, ridiculous layered levels of abstraction (but almost never the abstractions that would have actually made sense in the situation) as when looking at Java code.
There are many good features of C++ that Java has no eq... |
1,954,858 | 1,955,470 | Sieve of Eratosthenes algorithm | I am currently reading "Programming: Principles and Practice Using C++", in Chapter 4 there is an exercise in which:
I need to make a program to calculate prime numbers between 1 and 100 using the Sieve of Eratosthenes algorithm.
This is the program I came up with:
#include <vector>
#include <iostream>
using namespa... | I have no idea why you're not getting all the output, as it looks like you should get everything. What output are you missing?
The sieve is implemented wrongly. Something like
vector<int> sieve;
vector<int> primes;
for (int i = 1; i < max + 1; ++i)
sieve.push_back(i); // you'll learn more efficient ways to hand... |
1,954,891 | 1,954,932 | How do i create a GNU Autotool Project in Eclipse CDT from existing C++ source code? | I have an existing C++ source code that is built using autotools and i wish to use in Eclipse CDT. I'm a beginner with Eclipse CDT. I've installed the Autotools plugin for eclipse but don't know how to create a project from existing code.
May you please guide me in the right direction so that i can create an eclipse pr... | Try to generate all makefiles and then try to import project to eclipse. I think when all Makefiles will exist, then would be no need to install any external plugin for autotools in eclipse IDE. It should work as it is.
|
1,955,037 | 1,955,075 | Why does C++ prohibit non-integral data member initialization at the point of definition? | class Interface {
public:
static const int i = 1;
static const double d = 1.0;
//! static const string *name = new string("Interface name");
virtual string getName() = 0;
}
Since C++ is a traditional truely compiled programming language,it could be easily convinced that it does allow object initialization... | Because otherwise there would be a question of which compilation unit (e.g. object file) the value lived in. Every file that included a header with a class definition would try to create an object that would be assigned to the static value on creation, potentially causing unpredictable behavior.
It's not just assignme... |
1,955,074 | 1,955,109 | Virtual Methods or Function Pointers | When implementing polymorphic behavior in C++ one can either use a pure virtual method or one can use function pointers (or functors). For example an asynchronous callback can be implemented by:
Approach 1
class Callback
{
public:
Callback();
~Callback();
void go();
protected:
virtual void doGo() = 0; ... | Approach 1 (Virtual Function)
"+" The "correct way to do it in C++
"-" A new class must be created per callback
"-" Performance-wise an additional dereference through VF-Table compared to Function Pointer. Two indirect references compared to Functor solution.
Approach 2 (Class with Function Pointer)
"+" Can wrap a ... |
1,955,091 | 1,955,650 | Cross-platform C++ command line utility | I need to develop a Windows/Linux command line utility. The utility will talk to middleware that has a standard API on both platforms. I have done some cross-platform development before, on FreeBSD/Linux, which was considerably easier - and I had people in the group with experience that I could talk to.
At this poi... | Use standard C or C++ for most of the project. Only use platform specific functions when necessary. If possible, put those in a wrapper in isolated files so that the build (makefile) can substitute in the correct version for the appropriate platform.
Refrain from using #ifdef LINUX or #ifdef WINDOWS or similar condit... |
1,955,420 | 1,955,501 | Best & Fast way to find out if an ip address is reachable | I need the fastest way to see if an ip address is reachable. On each ip address theres a server listening on a specific port so let me know if your method is about to find if a server is listening on a port.
The reason for this is that suppose I have 10 ip addresses with 10 server listening on port 101 on each ip addre... | While you can quickly determine that an IP is reachable, your problem is determining that an IP is not reachable. The reason why is that you can't always definitively determine that an IP is not reachable. While there are some conditions where you will be given an affirmative notice that the IP is not reachable, usua... |
1,955,486 | 1,956,936 | Using Custom Events in QT4 | I have an app that has a progress bar & spawns a worker thread to do some work & report back progress. The dialog class overrides the customEvent method so that I can process events that are being passed to the gui thread via the worker thread. Before I was using a QThread derived class as the worker thread and I cha... | Try calling QApplication::postEvent(...) instead of QApplication::sendEvent(). The docs say that sendEvent sends the event directly, meaning that it calls the customEvent() function directly from the other thread. postEvent() adds the event to the event queue where it can later be dispatched to customEvent() by the m... |
1,955,661 | 1,955,670 | How can I call a method given only its name? | I'm trying to have method void run( string method ) which would run method in that class. For example:
class Foo {
public:
void run( string method ) {
// this method calls method *method* from this class
}
void bar() {
printf( "Function bar\n" );
}
void foo2() {
printf( "... | You can create an std::map which maps strings to member function pointers, as long as all the functions you want to call have the same signature.
The map would be declared like:
std::map<std::string, void(Foo::*)()> function_map;
|
1,955,806 | 1,956,630 | How do I dynamically create controls with the same visual style as their parent? | I'm using Visual Studio 2005 (and win32 API in C++), and I have a window which was designed using the built-in dialog box editor.
At runtime, I want to be able to use CreateWindow() to add new controls to it. This works, however the controls I create all look really ugly. For the purpose of concreteness, the control I'... | You really need to show us what you are currently doing (the code) if you want people to be able to help. This answer is going to be as much guesswork as a proper answer. so.
You probably don't need to muck around with the theme handle, Just having themes enabled for your app should be sufficient so long as you set t... |
1,955,885 | 1,955,902 | Is there an STL algorithm to find the last instance of a value in a sequence? | Using STL, I want to find the last instance of a certain value in a sequence.
This example will find the first instance of 0 in a vector of ints.
#include <algorithm>
#include <iterator>
#include <vector>
typedef std::vector<int> intvec;
intvec values;
// ... ints are added to values
intvec::const_iterator split = std... |
But the problem now is that I can't
make "head" and "tail" ranges using
begin() and end() because those aren't
reverse iterators.
reverse_iterator::base() is what you are looking for - section new members on SGIs reverse_iterator description or here on cppreference.com
|
1,955,899 | 1,955,944 | Is ASSERT redundant? | ASSERT(pointer);
pointer->x;
In this code, the ASSERT seems to be redundant. If the pointer is NULL, pointer->x will fail anyway. Is my argument correct?
| The important (if not main) purpose of assertions is to document the invariants that are supposed to hold at certain point in the code. The fact that assert can also abort the program if the invariant is broken is just icing on the cake, albeit a very useful one. I'd say that in a typical program 90% of assertions are ... |
1,956,472 | 1,956,490 | Does Visual Studio support data cache operations? | Reading through some great presentations on low latency computing. They had a reference to IBM's XL C/C++ compiler data cache operation __dcbt (Data Cache Block Touch) for their cell compiler. The operation loads a block of memory into L1 cache.
Does Visual Studio (or G++ or Intel) have similar functionality for Intel... | Yes, Visual Studio supports all the SSE and MMX intrinsic operations. The cache control operations are briefly described here: http://www.tommesani.com/SSECacheabilityControl.html
and explained at length in Intel's instruction set reference.
Microsoft documents their intrinsics for cache control at MSDN. Although they ... |
1,956,733 | 1,956,775 | How does std::string overload the assignment operator? | class mystring {
private:
string s;
public:
mystring(string ss) {
cout << "mystring : mystring() : " + s <<endl;
s = ss;
}
/*! mystring& operator=(const string ss) {
cout << "mystring : mystring& operator=(string) : " + s <<endl;
s = ss;
//! return this;
return (mystring&)this; // why COMPILE ERRO... | What you need is a 'conversion' constructor that takes a const char*:
mystring( char const* ss) {
cout << "mystring : mystring(char*) ctor : " << ss <<endl;
s = ss;
}
The line you're having a problem with:
mystring str1 = "abc"; // why COMPILE ERROR
isn't really an assignment - it's an initializer.
|
1,956,747 | 1,956,765 | Memory leak in trivial stack implementation | I'm decently experienced with Python and Java, but I recently decided to learn C++. I decided to make a quick integer stack implementation, but it has a massive memory leak that I can't understand. When I pop the node, it doesn't seem to be releasing the memory even though I explicitly delete the old node upon poping i... | How do you KNOW the memory isn't being released? The runtime library will manage allocations and may not release the memory back to the OS until the program terminates. If that's the case, the memory will be available for other allocations within your program during its execution.
However.... you seem to have other pr... |
1,956,764 | 1,956,801 | QMenu* << QAction* -- Help Me Write A Global QMenu Insertion Operator | If for no other reason than for my own amusement, I wish to write a global insertion operator so I can use the fancy code:
aQMenu << aQAction1 << aQAction2 << aQAction2 << seperator << aQAction3;
Perhaps you hate the syntax, but I would at least like to try my hand at using it. The problem is, that this is the first ... | The compiler complains because all the parameters are pointers. Using a reference for the menu parameter of the operator it would look like this:
QMenu& operator<< (QMenu &menu, QAction *action) {
menu.addAction(action);
return menu;
}
Now this operator should work on menu objects. If you want to use it with a... |
1,956,851 | 1,956,866 | How to convert double* to a double? | Any ideas for this typecasting problem?
Here's what I am trying to do. This is not the actual code:
LinkedList* angles;
double dblangle;
dblangle = (some function for angle calculation returning double value);
(double*)LinkedListCurrent(angles) = &double;
I hope you get the idea. The last line is causing the proble... | You use the unary * operator to dereference a pointer. Dereferencing a pointer means extracting the value pointed to, to get a value of the original type.
// Create a double value
double foo = 1.0;
// Create a pointer to that value
double *bar = &foo;
// Extract the value from that pointer
double baz = *bar;
edit 2: (... |
1,956,876 | 1,956,891 | STL with a custom data type | What am I doing wrong?
#include <iostream>
#include <deque>
using namespace std;
struct mystruct {
int number1;
int number2;
};
int main() {
std::deque<mystruct> mydeque;
mydeque.number1.push_front(77);
return 0;
}
| push_front is a method of deque not the number1 of structure mystruct..
The right way is :
struct mystruct {
int number1;
int number2;
mystruct(int n1, int n2) : number1(n1), number2(n2){}
};
int main() {
std::deque<mystruct> mydeque;
mydeque.push_front(mystruct(77,88));
return 0;
}
|
1,957,076 | 1,957,149 | What is the best way to store double dimension vector in c++? | What is the best way to store double dimension vector in c++?
std::vector <std::vector <int> > m_vector(N, std::vector<int>(M));
...
int k = m_vector[i][j];
How else?
| The most efficient and most convenient at the same time is to use boost::multi_array.
|
1,957,141 | 1,960,320 | How to get the fractional part of the seconds in UTCTime using time.h | I want to get the system time including fractional part of the seconds. Is it possible in standard c (ANSI C)?
If not then tell me some libraries for window OS so that I make it possible. In Linux I have the following code with work fine for me.
#include <sys/time.h> ... | Standard C does not provide sub-second resolution timing.
POSIX does provide sub-second resolution timing - in fact, a number of different ways of doing it, including gettimeofday() which you show.
|
1,957,227 | 1,957,506 | Build automation by using platform specific project files or by using project generators? | There are some build systems that are able to generate platform specific project files like Visual Studio sln,vcproj,vcxproj files or XCode xcodeproj projects under OS X.
One of them is CMake but I found out that the support for this is quite limited, buggy and that is very hard to keep it updated with newer versions ... | Here's what we do, it might not be the best way, but it works really good for us and we found that it's not too hard to maintain, maybe you find it interesting.
Our main platform is windows, nearly all development is done in the VS IDE. For the other platforms (only some linux flavors for now) we use CMake exclusively.... |
1,957,308 | 4,165,764 | GDI fails conversion to indexed color with exact palette? | Summary
Using Windows GDI to convert 24-bit color to indexed color, it seems GDI chooses colors which are "close enough" even though there are exact matches in the supplied palette.
Can anyone confirm this as a GDI issue or am I making a mistake somewhere?
Maybe there's a "please check the whole palette for color match... | I ran into this exact same problem, eventually contacted Microsoft and provided them with a test case. In the test case I provided a gradient image that had 128 colors in a 24bit DIB, I then converted that to an 8bit DIB that was created with a color table containing all 128 colors from the 24bit image. After convers... |
1,957,341 | 1,957,397 | newbie: Determinate CRT lib used by library | I'm developing application using VC++ 6.
I have a 3rd party DLL. This library compiled as Multithreaded DLL (/MD) and my application too.
But I fail to link:
LINK : warning LNK4075: ignoring /EDITANDCONTINUE due to /INCREMENTAL:NO specification
msvcprtd.lib(MSVCP60D.dll) : error LNK2005: "public: __thiscall std::basic... | There is dependency Walker, if you don't know this tool.
http://dependencywalker.com/
Drag and drop your DLL or exe on the main window. It will show all dependencies.
And if you want to link to a 3rd party DLL, all you need is a .lib made for that DLL.
If you don't have that .lib, you can always make one using lib.exe ... |
1,957,480 | 1,957,542 | How to configure Vim for C++ development? | I'm learning C++ using Vim as an editor on Windows XP, however I found a issue that I have listed below.
I have downloaded and installed c.vim and it is a essential file, however when I start vim it shows the message C/C++ template file 'C:\Program Files\Vim\vimfiles\c-support/templates/Templates' does not exist or is... | For your first problem: I suspect that you didn't extract all the files in the archive (that c.vim came in). The c.vim documentation (README.csupport) says:
The subdirectories in the zip archive
cvim.zip mirror the directory
structure which is needed below the
local installation directory
$HOME/.vim/ for LIN... |
1,957,495 | 1,957,525 | using C++ IO istream object to read is resulting in infinite loop | The below function results in infinite loop if a string is entered as input.
istream & inputFunc(istream &is)
{
int ival;
// read cin and test only for EOF; loop is executed even if there are other IO failures
while (cin >> ival, !cin.eof()) {
if (cin.bad()) // input stream is corrupted; bai... | You need to do two things:
1) clear state like here: cin.clear(istream::goodbit);
2) skip one char at a time after clearing the state, because you don't know where the next number starts:
char c;
cin >> c;
|
1,957,523 | 1,957,554 | interview questions - little help | i ran into thos quesiton in a google search.... they look pretty common, but i couldn't find a decent answer. any tips/links ?
1.Remove duplicates in array in O(n) without extra array
2.Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not all... | (1) isn't possible unless the array is presorted. The basic answer is to keep two pointers into the array, one walking forward searching for unequal elements, and one trailing pointer. When the forward pointer encounters an unequal element, it copies it into the trailing pointer and increments the trailing pointer.
(2)... |
1,957,532 | 1,958,151 | negative precision values in ostream | This is more of a question of curiosity but does anyone know how negative precision values are handled in C++? For example:
double pi = 3.14159265;
cout.precision(-10);
cout.setf(ios::fixed, ios::floatfield);
cout << pi << endl;
I've tried this out and using GCC and it seems that the precision value is ignored but ... | Strangely (and wrongly, IMHO) the C++ Standard specifies a signed type (streamsize) as the parameter for precision, so it won't be converted to a large number. However, the standard is silent on what a negative number might mean, if anything.
|
1,957,581 | 1,998,974 | AntiAlias failed when draw string with certain angle in GDI+ | I am using the following code to draw Strings. In GDI+
Graphics tempFontGr(XXX);
Matrix* myPathMatrix = NULL;
myPathMatrix->Rotate(GetDCAngle(), MatrixOrderPrepend);
cantempFontGr.SetTransform(myPathMatrix);
tempFontGr.SetInterpolationMode(InterpolationModeHighQuality);
tempFontGr.SetSmoothingMode(SmoothingModeAntiAli... | SetSmoothingMode applies to lines and curves. Try SetTextRenderingHint
|
1,957,593 | 1,957,606 | How to make an ambiguous call distinct in C++? | void outputString(const string &ss) {
cout << "outputString(const string& ) " + ss << endl;
}
void outputString(const string ss) {
cout << "outputString(const string ) " + ss << endl;
}
int main(void) {
//! outputString("ambigiousmethod");
const string constStr = "ambigiousmethod2";
//! outputStr... | C++ does not allow you to overload functions where the only difference in the function signature is that one takes an object and another takes reference to an object. So something like:
void foo(int);
and
void foo(int&);
is not allowed.
You need to change the number and/or the type of the parameter.
In your case th... |
1,957,605 | 1,957,658 | What is a good way of sending data as strings through sockets? | As there several ways to exchange data in the form of strings over sockets, such as:
using functions like:
sprintf() and sscanf()
snprintf() and sscanf()
printf() and strtof()
or converting to char and then passing it as an array
I would appreciate if you could suggest which way and why it is efficient and bette... | in C++ you can also use StringStream
stringstream ss;
int i = 1;
float f = "1.0";
char separtor = ';';
ss << i << separtor << f;
you can then extract the string with ss.str().c_str()
ss.str().c_str() will result in the case above with
"
1;1.0
"
|
1,957,644 | 1,957,791 | Which install system to pick when deploying to Windows and Linux? | My company is thinking of dumping InstallShield and move to something else, mainly because of the poor experience it had with it, mostly on Linux.
Our product is a C++ application (binaries, shared libraries) targeted at Windows and Linux (Red Hat).
The installer itself isn't required to do anything special, just dump ... | For Windows I would definitively use NSIS. It's very lightweight, easy to code and very simple to understand. Using msis would just be a killer - it generates guid for every file so you can get upgrades for free and stuff but truth being said, you never end up using any of these.
Regarding Linux I would go for RPM and ... |
1,957,665 | 1,959,879 | Magick++ animation generation via SDL pixel data | I'm trying to generate ImageMagick images from SDL pixel data. Here's what the GIF looks like so far. (This GIF is slower than the one below on purpose.)
http://www.starlon.net/images/combo.gif
Here's what it's supposed to look like. Notice in the above image that the pixels seem to be overlayed on top of other pixels.... | The top image is normally caused by a misaligned buffer. The SDL buffer is probably not DWORD aligned and the ImageMagick routines expect the buffer to be aligned on a DWORD. This is very common in bitmap processing. The popular image processing library - Leadtools, commonly, requires DWORD aligned data. This is mo... |
1,957,667 | 1,976,371 | Why do C++ allow constant to be transformed to reference argument in another method? | void outputString(const string &ss) {
cout << "outputString(const string& ) " + ss << endl;
}
int main(void) {
outputString("constant tranformed to reference argument");
//! outputString(new string("abc")); new only return pointer to object
return 0;
}
Since its prohibited to create temporary object r... | What are your alternatives?
void outputString(const string ss);
That will create a copy of any string passed, even if the type matches exactly: Overhead that's not really needed!
void outputString(string &ss);
That will allow changing the passed argument. We don't want to do that, and C++ does not allow us to pass a... |
1,957,671 | 1,957,703 | Are there any tools for compile time checking of asserts in c++? | I was writing a function in c++ the other day and it occured to me the compiler could do a lot more to help me guard against mistakes. The essentials of my code were like this -
void method(SomeType* p)
{
assert(p != 0);
p->something();
}
And it was called like this
SomeType p = NULL;
if (SomeCondition)
{
... | Static analysis tools such as PC-lint may be able to detect these issues.
http://www.gimpel.com/html/pcl.htm
With respect to your first example though: my style is to favour references over pointer arguments or return values unless NULL is an acceptable value. This eliminates the need to assert arguments are != NULL.
|
1,957,761 | 1,958,156 | istream from file_descriptor_source (boost::iostreams) or file | I need to do something like this for my program's input:
stream input;
if (decompressed)
input.open(filepath);
else {
file_descriptor=_popen("decompressor "+filepath,"r");
input.open(file_descriptor);
}
input.read(...)
...
I can see one solution - to use _popen in both cases and just copy the file to stdou... | Is this what you're after:
#include <cstdio>
#include <string>
#include <iostream>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
namespace io = boost::iostreams;
int main()
{
bool flag = false;
FILE* handle = 0;
if (flag)
{
handle = _popen("dir",... |
1,957,914 | 1,958,631 | Access violation when exporting a C++ class to Lua using LuaBind | I'm trying to export a simple class to Lua using LuaBind. I took the code from two sites which showed roughly the same way to do it, but it's still failing.
// Default headers
#include <iostream>
#include <string>
// Lua headers
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
#inc... | I would encourage you to get this started with the binaries and sample VS2008 solution available from this website. It has the exact same sample code you are trying to run (minus the typos) and it worked well on my machine. If it still doesn't work, you'll need help from the Lua community. A minidump is probably req... |
1,957,945 | 1,958,008 | What's a good project tailored to learning strengths of Unix / Linux | I've been developing Microsoft Windows based applications (both desktop and web) for several years using C#, .net, & Visual Studio with a dash of C/C++ & WIN32. I want to broaden my horizons and try out developing in a *NIX environment e.g. using Vim & C++. I have limited UNIX experience from a few school projects.
I... | In UNIX/Linux "everything" is files. What about writing a piece of software that reads the disk device, understands the partition tables and file system?
Another possibility is to write a linux kernel module that does "something". It will sure give you a better understanding on how the linux kernel works. As an added ... |
1,958,330 | 1,958,339 | Can Global Arrays in C++ Break Binary Compatibility? | Say a shared library contains the following lines:
const char* const arr[] =
{
"one",
"two",
"three"
};
1) Can an application link to this library and use the symbol "arr"?
2) Is binary compatibility broken if a new element is added to the definition?
3) How about if one of the string literals is changed?
4) Why... | 1) Yes
2) No
3) Not a problem
4) Why would you think otherwise?
|
1,958,369 | 1,958,455 | What is a good way to connect multiple clients to the server? | As there are several ways of connecting multiclients to the server such as: fork, select, threads, etc. I would be glad if you could describe which is better to connect multiple clients to the server?
| Take a look at the C10K page for a great overview and comparison of I/O frameworks and strategies.
|
1,958,453 | 1,958,649 | How to pass data from client to server when using gSOAP? | I am trying to exchange data between client and server using gSOAP. Actually, I succeeded to send data from client to server but not from server to client. So, could someone please explain what functions to use to pass data from server to client?
Thanks for your time and replies,
| The only way I know is by invoking with a function soap_call
See the example of calc in gsoap package
|
1,958,618 | 1,958,632 | What is the difference between soap_new() and soap_copy()? | What is the difference between:
thread_envs[i] = soap_copy(&env);
and
thread_envs[i] = soap_new();
Sould we use one of them or both?
| From the documentation:
struct soap *soap_new()
Allocates, initializes, and returns
a pointer to a runtime environment
struct soap *soap_copy(struct soap *soap)
Allocates a new runtime environment
and copies contents of the environment
such that the new environment does not
share any data with the original
... |
1,958,799 | 1,958,846 | Qt4 QNetworkManager Hangs | I'm trying to write an application using QNetworkManager. I have simplified the code down to the problem. The following code hangs, and I have no idea why:
main.cpp:
#include <QApplication>
#include "post.h"
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
post("http://google.com/search", "q=te... | I just tried it with the same results. The problem is that you are creating the post object by only calling the constructor. Since you are not specifying an object it is getting destroyed right away (to check this create a destructor and see when it gets called.)
try:
post p("http://google.com/search","q=test");
Then ... |
1,958,984 | 1,959,006 | C++ Templates and accessing namespaces | Let's say I'm using a templated class with something simple like:
template <class T>
class MyClass
I want to use elements from T's namespace, for example T could be string, and I wanted to use
T::const_iterator myIterator;
...or something like that. How do I achieve that?
Probably, it's either not possible or very... | By default if T is a template parameter like in your example, the T::some_member is assumed not to name a type. You have to explicitly specify that it is, by prefixing it with typename:
typename T::const_iterator myIterator;
This resolves some parsing problems like in the following example
// multiplication, or declar... |
1,959,102 | 1,959,107 | Tickcount and milliseconds in C++ | How do I convert from TickCounts to Milliseconds?
this is what I used:
long int before = GetTickCount();
long int after = GetTickCount();
I want the difference of it in seconds.
| int seconds = (after - before) /1000;
|
1,959,237 | 1,959,250 | What is a fast efficient way to find an item? | Hi so I need some FAST way to search for a word in a dictionary.
The dictionary has like 500k words in it.
I am thinking about a using a hashmap where each bin has at most 1 word.
Ideas on how to do this or is there something better?
| A Trie is an efficient way to store dictionaries and has very fast lookup characteristics, O(m) where m is the length of the word.
A hashmap will be less efficient memory-wise but lookup time is a constant quantity for a perfect hash, O(1) lookup but you still spend O(m) calculating the hash. An imperfect hash will hav... |
1,959,333 | 1,964,212 | In MFC how do I avoid dialog boxes from staying on top of my app window? | I have a dialog box based application (MFC - VS 2008). I have a list control on it. I pop up other dialog boxes, but I also want to be able to get back to the parent app dialog. I can get back to the parent app dilaog box, but the problem is that even if I click on it with the mouse it remains hidden behind the "chi... | A friend of mine suggested the following (and it work)
set the style of the 2nd dlg to WS_CHILD
histwind->SetParent( NULL );
histwind->ModifyStyle( WS_CHILD, 0 );
This works, however thereis a strange behavior when i move the parent window from behind a child. While moving the window is hidden until I release the mo... |
1,959,418 | 1,959,444 | how to cache a lambda in c++0x? | I'm trying to work with lambda's in C++ after having used them a great deal in C#. I currently have a boost tuple (this is the really simplified version).
typedef shared_ptr<Foo> (*StringFooCreator)(std::string, int, bool)
typedef tuple<StringFooCreator> FooTuple
I then load a function in the global namespace into my ... | The -> operator sets the return type of the lambda, in the case of no return type it can be omitted. Also, if it can be inferred by the compiler you can omit the return type. Like Terry said, you can't assign a lambda to a function pointer (GCC improperly allows this conversion) but you can use std::function.
This code... |
1,959,438 | 1,959,508 | Order preserving minimal perfect hash functions | I want to implement an OPMPH function for the words in a dictionary in C++. How do I do it?
Thanks!
| Have you looked at these papers?
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.84.4018&rep=rep1&type=pdf
http://dx.doi.org/10.1016/0020-0190(92)90220-P (the short form link that leads to a very long link at http://www.sciencedirect.com/)
http://eprints.cs.vt.edu/archive/00000248/01/TR-91-01.pdf
|
1,959,555 | 1,959,588 | rectangle disappearing with SDL | So I'm simply trying to make a red 10 x 10 box move vertically back and forth. I compile and run my program and the red box appears starts moving down, then just disappears after it hits the edge of the screen. I used some cout << statements that tell me when the functions are being called and they are all being called... | There isn't enough information to give conclusive answer, but here's a hint.
From my experience with SDL, SDL functions can modify your Rect structure when called, especially when rect is partly off-screen. Make sure you set all its properties (x,y,width,height) before each SDL function that uses the rectangle.
|
1,959,581 | 1,959,737 | client-server design | i want to develop a pretty basic client-server program.
one software reads xml (or any data) and send it to the server who in turn will manipulate it a little bit and eventually will write it to the disk.
the thing is that if i have many xml files on disk (on my client side), i want to open multiple connection to the s... | Take a look at boost::asio it uses a proactor pattern (see the docs) that basically uses the OS wait operations (waitforsingle/multiple,select,epoll, etc...) to make very efficient use of a single thread in a system like you're looking at implementing.
asio can read/write files as well as sockets. You could sumbit an a... |
1,959,682 | 1,959,696 | If the only thing that changes is the constructor should I still derive? | I have a class that has everything already implemented but its initialization process is different for every child class.
Is there a better idiom to replace the ctor? Is there something more generic/dynamic that I should use?
| Or use static factory methods. This allows you to have different names for the "constructor" that shows the intent.
|
1,959,927 | 1,960,051 | How to see hash items in C++? | Hi so I have the following code and I want to be able to insert words into it and be able to see the stuff I put into the hash by printing it out. Here's what I have:
#include <iostream>
#include <fstream>
#include <string>
#include <hash_map>
#include <set>
#include <windows.h>
using namespace std;
struct nlist{
... | The problem you are having here is that you are printing out the pointer to the nlist item that you have looked up, rather than the value of the defn string within that item.
In your main loop, you have the following code:
else if (inline1 == "lookup"){
getline(cin, inline1);
cout << lookup(inline1.c_st... |
1,960,075 | 1,960,117 | Boost Filesystem createdirectories on Linux replacing "/" with "\" | When using Boost Filesystem's createdirectory (and createdirectories) function in the following example, "/" is being replaced with "\".
boost::filesystem::path path ("/data/configSet");
boost::filesystem::create_directory(path);
This code snipped produces a directory called "data\configSet", instead of creating a sub... | It looks like for some reason boost::filesystem thinks that you are on Windows, not Linux, and thus is using Windows style pathnames (separated by \). Can you post a bit more information about how you are building Boost and how you're including the headers? Are you perhaps building a Windows version of Boost on Linux?
... |
1,960,243 | 1,960,367 | Threading on bootloader | Where can I find resources/tutorials on how to implement threads on a x86 architecture bootloader... lets say I want to load resources in the background while displaying a progress bar..
| That is a very unusual question...so allow me to provide my opinion on it...
Bootloaders, are really a limited bunch of assembly code, 464 bytes to be exact, 64 bytes for partition information and a final two bytes for the magic marker to indicate the end of the boot loader, that is 512bytes in total.
Bootloaders such... |
1,960,369 | 1,960,833 | Is shared ownership of objects a sign of bad design? | Background: When reading Dr. Stroustrup's papers and FAQs, I notice some strong "opinions" and great advices from legendary CS scientist and programmer. One of them is about shared_ptr in C++0x. He starts explaining about shared_ptr and how it represents shared ownership of the pointed object. At the last line, he says... |
To what extent does RAII substitute other design patterns like Garbage Collection? I am assuming that manual memory management is not used to represent shared ownership in the system
Hmm, with GC, you don't really have to think about ownership. The object stays around as long as anyone needs it. Shared ownership is t... |
1,960,543 | 1,960,573 | strange SDL memory usage depending on bits per pixel | I have a very simple SDL program that uses only 1MB of memory with 32 bits per pixel, 2.4MB with 24 bits per pixel, 1.9MB with 16 bits per pixel, and 1.4MB with 8 bits per pixel. what is with this strange memory usage? why does the most bits per pixel take up the least amount of memory?
C++
GCC
thanks
| Perhaps internal conversion buffers. If your surface bpp doesn't match your hardware surface you may need to store the full buffer in memory, whereas SDL may be able to use that surface directly otherwise. This is just a guess offhand.
But looking at a process in top or task manager may not be the best way to get a h... |
1,960,619 | 1,960,629 | Two calls to destructor | For the following code:
#include<iostream>
#include<vector>
#include<string>
using namespace std;
struct Test
{
string Str;
Test(const string s) :Str(s)
{
cout<<Str<<" Test() "<<this<<endl;
}
~Test()
{
cout<<Str<<" ~Test() "<<this<<endl;
}
};
struct TestWrapper
... | Your output doesn't account for the Test's copy constructor, which std::vector is apt to use.
The Test object you see get created is the temporary passed to push_back(), not the one actually in the vector.
|
1,960,740 | 1,960,751 | What is nothrow delete in C++? | This MSDN page mentions that there're nothrow versions of new and delete. nothrow new is quite a known thing - returns null instead of throwing an exception if memory allocation fails. But what is nothrow delete mentioned there?
| They are probably referring to the raw memory allocation functions operator new and operator delete.
When you invoke a specific version of placement new-expression (i.e. new-expression with extra parameters; they all are officially referred to as placement forms of new) and the memory allocation function operator new s... |
1,960,964 | 1,961,126 | Can anyone tell me about the Event Handler or Callback on switching of the front process on Mac? | I need to have the callback or some event handler which can help me, know front process is changed.
Mac: C++/Carbon.
Any help is highly appreciated.
| That would be the kEventAppFrontSwitched event in the kEventClassApplication class. See the Carbon Event Manager reference.
|
1,960,991 | 1,961,237 | Which one to use - memmove() or memcpy() - when buffers don't overlap? | Using memcpy() when source and destination overlap can lead to undefined behaviour - in those cases only memmove() can be used.
But what if I know for sure buffers don't overlap - is there a reason to use specifically memcpy() or specifically memmove()? Which should I use and why?
| Assuming a sane library implementor, memcpy will always be at least as fast as memmove. However, on most platforms the difference will be minimal, and on many platforms memcpy is just an alias for memmove to support legacy code that (incorrectly) calls memcpy on overlapping buffers.
Both memcpy and memmove should be w... |
1,961,028 | 1,961,143 | Any differences between f(const string &) and f(const string )? | class mystring {
friend ostream& operator<<(ostream &out, const mystring ss) {
out << ss.s;
return out;
}
private:
string s;
public:
mystring(const char ss[]) {
cout << "constructing mystring : " << ss << endl;
s = ss;
}
};
void outputStringByRef(const mystring &ss) {
... | There is a difference between the two. Consider the following:
#include <iostream>
#include <string>
using std::string;
string g_value;
void callback() {
g_value = "blue";
}
void ProcessStringByRef(const string &s) {
callback();
std::cout << s << "\n";
}
void ProcessStringByValue(const string s) {
c... |
1,961,086 | 1,961,101 | Multiple definitions of `GamepadControll::GamepadControll()' | I got this error message:
multiple definition of `GamepadControll::GamepadControll()'
After being frustrated for hours I reduced the code to:
GamepadControll.h:
#ifndef GAMEPADCONTROLL_H_
#define GAMEPADCONTROLL_H_
#include <iostream>
class GamepadControll {
public:
GamepadControll();
virtual ~GamepadContro... | Most mulitply-defined-symbol error situations tend to be caused by including code into two different compilation units.
Are you sure that you're not including GamepadControl.cpp into one of your other source files?
For example, with both your files and a main.cpp holding:
#include "GamepadControll.h"
int main (void) { ... |
1,961,158 | 1,961,180 | Where does execution resume following an exception? | In general, where does program execution resume after an exception has been thrown and caught? Does it resume following the line of code where the exception was thrown, or does it resume following where it's caught? Also, is this behavior consistent across most programming languages?
| the execution resumes where the exception is caught, that is at the beginning of the catch block which specifically address the current exception type. the catch block is executed, the other catch blocks are ignored (think of multiple catch block as a switch statement). in some languages, a finally block may also be ex... |
1,961,238 | 1,961,246 | Can anyone recommend a good C/C++ RESTful framework | Rather than possibly reinventing the wheel (by "rolling my own") - I thought I'd ask in here first.
Anyone knows where I can download a good C/C++ RESTful framework?. I have had a quick look on google, but there is nothing too impressive so far - maybe someone in here has written one already (that they dont mind sharin... | I've just seen this, it may be what I'm looking for. Could be useful for others too
|
1,961,240 | 1,961,269 | List of things to check to prevent VC++ applications from showing fatal error message boxes | Every now and then there's a strong need to write a program in such a way that it never (really never) shows an error message as a message box. For example it can be a program run inside a daily build - if it hangs with a message box the daily build hangs.
Unfortunately VC++ runtime has a lot of ways to trigger message... | I would recommend that you use a helper program to launch it and have this helper limit the time your program can run. This is by far the safest way if you can do it, as it handles every case. Some things you cannot handle in your program directly, such as "This program is not a valid Win32 application" which might hap... |
1,961,271 | 1,961,279 | Time spent on reading from file | I am doing this in C++:
if (myfile.is_open()){
while (! myfile.eof()){
getline (myfile,line);
DO STUFF
}
myfile.close();
}
else{
cout << "Unable to open file";
}
I am trying to read the lines from a text file and do stuff with it. I am trying to s... | Yes - if you want to accurately benchmark "DO STUFF" then you shouldn't take into account disk IO also. So one thing you could do is buffer the whole file into memory, and then process it and time that. But if the file is too large or it would make your line handler more difficult, another thing you could do is read ... |
1,961,370 | 1,961,381 | c++ node list - NULL test not working | I wanted to test the following code (which works fine for a non-null list) to see what would happen in the case of an empty list (in which case the head would be null).
hence the code which applies to filling the list is commented out..
But for some strange reason, the test for NULL in print_nodes() just doesnt seem to... | You have a problem: head was not allocated, but insert accesses its "next element":
before->nextPtr = tempPtr;
head is passed in as before, and you didn't allocate memory for head. Hence you dereference a NULL pointer here.
Could it be that your application crashes as a result, and the printout to cout isn't done beca... |
1,961,376 | 1,961,408 | length of array in c++ | I read to get the length of array in C++, you do this:
int arr[17];
int arrSize = sizeof(arr) / sizeof(int);
I tried to do the same for a string:
where I have
string * arr;
arr = new (nothrow) string [213561];
And then I do
arr[k] = "stuff";
where I loop through each index and put "stuff" in it.
Now I want the size ... | The correct way of doing this in C++ is to use a vector. That way you can either specify a size up-front, or resize it as you go.
Specifying size up-front:
using namespace std;
vector<string> arr(213561);
for (vector<string>::iterator p = arr.begin(); p != arr.end(); ++p)
{
*p = "abc";
}
Expanding the vector as yo... |
1,961,455 | 1,961,517 | How do i use C++ with Flex? | How can i outsource performance critical stuff to C++.
Is there any example ?
| If you're talking about Flex on AIR platform (basically out of browser application), there's a way to interact with native code on the same machine.
You may want to check this out (official doc from Adobe) : http://www.adobe.com/devnet/air/ajax/quickstart/interacting_with_native_process_print.html
If you're talking abo... |
1,961,561 | 1,961,576 | Standard convention for using "std" |
Exact Duplicate: Do you prefer explicit namespaces or ‘using’ in C++?
Which of these is a preferred convention for using any namespace?
using namespace std;
or
using std::cin;
using std::cout;
or
calling the function as and when required in the code?
std::cout<<"Hello World!"<<std::endl;
| A very good explanation is given here.
The first style i.e. using namespace whatever defeats the whole purpose of namespacing. You should never be using it except in small code snippets. (I don't use it there either! :D )
Second one is way too verbose. Not practical.
I personally like the third style i.e. typing out t... |
1,961,604 | 1,961,641 | How much time would it take to write a C++ compiler using flex/yacc? | How much time would it take to write a C++ compiler using lex/yacc?
Where can I get started with it?
| There are many parsing rules that cannot be parsed by a bison/yacc parser (for example, distinguishing between a declaration and a function call in some circumstances). Additionally sometimes the interpretation of tokens requires input from the parser, particularly in C++0x. The handling of the character sequence >> ... |
1,961,659 | 1,961,779 | Can I use partial template specialization for a (non-member) function? | I'm trying to use partial template specialization on a (non-member) function, and I'm tripping up on the syntax. I've searched StackOverflow for other partial template specialization questions, but those deal with partial specialization of a class or member function template.
For a starting point, I have:
struct RGBA ... | It is possible using class partitial specialization:
template<class A, class B>
struct Functor {
static A convert(B source);
};
template<class B>
struct Functor<GrayScale, B> {
static GrayScale convert(B source) {
return Grayscale(IntensityFromRGB(source.r, source.g, source.b));
}
};
// Common fu... |
1,961,812 | 1,961,896 | How to implement reference counting for library class whose implementation cant be changed? | I come to know that when many objects shares same data and creation and desturction of objects are expensive then one can go for reference counting .
Can anybody give input about how to achieve it for the library class which cant be changed ?.
| Use a referenced-counted pointer like boost::shared_ptr. No changes to the class pointed to are necessary, but you will be limited to creating class instances dynamically.
|
1,962,029 | 1,962,034 | Destructors called upon program termination | When an object is created in your main() function, is its destructor called upon program termination? I would assume so since main() still has a scope( the entire program ), but I just wanted to make sure.
| It depends on how your program terminates. If it terminates by having main return (either by an explicit return or falling off the end), then yes, any automatic objects in main will be destructed.
But if your program terminates by calling exit(), then main doesn't actually go out of scope and any automatic objects wil... |
1,962,103 | 1,962,139 | Can I use Qt as C++ Library without using its UI framework | Does it make sense to use Qt for increasing the productivity in an MFC app, without actually using the Qt user interface system?
I am currently looking or a good productivity library for my MFC based application, with useful container classes, string algorithmus, threading classes, I/O classes and so on. The Qt API is... | Qt is divided into several modules (QtGui being one of them). You can hand pick which modules are used by your application by linking only against the libraries you need.
I cannot answer whether Qt will be interopable with MFC. But at the very least, QString offers conversion to std::string and char*/wchar, which shoul... |
1,962,281 | 1,962,300 | Get ID from MIDI devices in C++ | I'm a musician and a programmer and would like to create my own program to make music.
I'll start with a console application in C++ before I make a GUI.
I'm quiet new to C/C++ and know how to make a basic console application and have read about the Win32 API.
I was looking into MSDN for multimedia in Win32 applications... | To get information, you loop calling midiInGetDevCaps, with a first parameter varying from 0 included to the result of midiInGetNumDevs excluded. Each call fills a MIDIINCAPS struct (you pass a pointer to the struct when you call the function) with information about the Nth device. To open a device, and fill the HMID... |
1,962,331 | 1,962,362 | C or C++ - dynamically growing/shrinking disk backed shared memory | I have several fastcgi processes that are supposed to share data.
The data is bound to a session (a unique session id string) and should be able to survive a server reboot. Depending on the number of sessions, the shared data might be too big to fit into main memory. Ideally, in the case when the shared data exceeds a... | After your comment to bmargulies I should caution you that I myself tried to do what you are describing, and I found that I was writing a ACID database. To recap, you have asked for :
Statistical Caching
data persistance
data sharing between processes
This is the role of a database system. It is far better to use one... |
1,962,482 | 1,962,644 | HZ variable not defined | I'm trying to compile someone's code right now and the person is using a variable HZ (which I think stands for Hertz for the hertz of the cpu) but the compiler is complaining that the variable is not defined. My guess is that the person didn't include the correct header file.
So does anyone know which header file, HZ i... | Paul's answer is correct, but I'll expand a little.
Linux has a compile-time option which determines the frequency of the kernel's timer. At approximately the frequency that HZ is defined to, the kernel scheduler will interrupt processes and begin its scheduling work. (A related feature is the DynTicks option, which el... |
1,962,624 | 1,962,637 | How can I write my own 'filesystem' within Windows? | I've recalled using little 'filesystems' before that basically provided an interface to something else. For example, I believe there was a GMail filesystem that created an entry in My Computer and could be used like any other drive on your local computer. How can I go about implementing something like this in C++?
Than... | Try Dokan. It's like FUSE, except for Windows. I think there are certain limitations to namespace extensions, like they cannot be accessed from the command line, but I'm really not sure as of now.
|
1,962,685 | 1,962,921 | Xcode STL C++ Debug compile error | I have some file writing code that works as expected, but prints an error on Debug mode, no output errors in Release.
Code:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main (int argc, char * const argv[]) {
string cppfilename;
std::cout << "Please ente... | This looks to be another case of _GLIBCXX_DEBUG being broken with gcc 4.2 on Mac OS X.
Your best options look to be to drop _GLIBCXX_DEBUG or to switch to gcc 4.0.
|
1,962,880 | 1,962,918 | Is C++ static member variable initialization thread-safe? | According to following resources, in C++(Specially Visual C++) scoped static variable initialization isn't thread safe. But, global static variables are safe.
Thread-safe static variables without mutexing?
http://blogs.msdn.com/oldnewthing/archive/2004/03/08/85901.aspx
So, is following code with static member variable ... | It's more a question of function-scoped static variables vs. every other kind of static variable, rather than scoped vs. globals.
All non-function-scope static variables are constructed before main(), while there is only one active thread. Function-scope static variables are constructed the first time their containing ... |
1,962,959 | 1,964,209 | std::vector reserve method fails to allocate enough memory | I have a buffer class in my C++ application as follows:
class Buffer
{
public:
Buffer(size_t res): _rpos(0), _wpos(0)
{
_storage.reserve(res);
}
protected:
size_t _rpos, _wpos;
std::vector<uint8> _storage;
}
Sometimes using the constructor fails because its unable to allocate the r... | If you can't use Valgrind to find out where your memory is corrupted because of the heavy load it implies, you can still test with lighter solutions.
For server application where Valgrind was not applicable (because the platform was on Solaris 8), I had pretty good result with mpatrol ( http://mpatrol.sf.net ) but espe... |
1,963,040 | 1,963,082 | std::map and 'fat' value objects | What's better from a performance point of view std::map<uint32_t, MyObject> or std::map<uint32_t. MyObject*> if MyObject is 'fat' (that is operator= rather expensive) and I have to insert/update/delete a lot ?
| If you'd prefer to store the objects "by value", but don't want to perform expensive copying, then just don't do the copying at all. For example, you can always insert "empty" objects (which can be copied quickly) and then fill them with actual content after they are already inserted into the map. The latter can be don... |
1,963,099 | 1,963,119 | How to inform the server when a client is interrupted? | How to inform the server if a client is interrupted, and then close the socket?
| If the other end of a socket is closed, your end will be marked as readable and return 0 from read - this is the "end of file" indication.
If you try to write to such a socket, you will recieve the SIGPIPE signal, and the write will return error with errno set to EPIPE ("Broken Pipe"). You must be prepared to handle t... |
1,963,106 | 1,963,134 | Find Even/Odd number without using mathematical/bitwise operator | I was recently asked to write a program, that determines whether a number is even or odd without using any mathematical/bitwise operator!
Any ideas?
Thanks!
| This can be done using a 1 bit field like in the code below:
#include<iostream>
struct OddEven{
unsigned a : 1;
};
int main(){
int num;
std::cout<<"Enter the number: ";
std::cin>>num;
OddEven obj;
obj.a = num;
if (obj.a==0)
cout<<"Even!";
else
cout<<"Odd!";
return 0;... |
1,963,157 | 1,963,166 | OpenGL Video Memory Usage | is there an API or profiler application that can track the video memory usage of my application?
I am using C++/OpenGL on Windows, but I am open to suggestions on other platforms as well.
| On Mac OS X you have OpenGL Profiler.app, which comes with the Developer Tools (on the OS DVD or from http://developer.apple.com)
On Windows you could try gDEBugger - a good commercial OpenGL Profiling tool.
|
1,963,241 | 1,963,680 | IGraphBuilder::RenderFile() failing with VFW_E_BAD_KEY - 0x800403f2 | Continuing investigation on a embedded WindowsMediaPlayer problem, i am trying to do simple file playback via a DirectShow in-process server:
::CoInitializeEx(0, COINIT_MULTITHREADED);
CComPtr<IGraphBuilder> spGraph;
spGraph.CoCreateInstance(CLSID_FilterGraph, 0, CLSCTX_INPROC_SERVER);
CComQIPtr<IMediaControl> spMedia... | It is reading the key from the wrong hive. It should use HKLM, not HKCU. The most likely reason for this is registry virtualization.
|
1,963,269 | 1,963,281 | C++ Force Template Parameter | I want this code to be possible.
template<typename K, typename T, typename Comparer>
class AVLTree
{
...
void foo() {
...
int res = Comparer::compare(key1, key2);
...
}
...
};
Specifically, I want to force Comparer class to have a static int compare(K key1, K key2) function. I was thin... | You can't. But if use the function and the Comparer doesn't have it, your compile will fail and this is more or less what you want to happen. And yes, like others pointed out you want to call static as static.
|
1,963,366 | 1,963,859 | Callbacks and Delays in a select/poll loop | One can use poll/select when writing a server that can service multiple clients all in the same thread. select and poll, however need a file descriptor to work. For this reason, I am uncertain how to perform simple asynchronous operations, like implementing a simple callback to break up a long running operation or a de... | For arbitrary callbacks, maintain a POSIX pipe (see pipe(2)). When you want to do a deferred call, write a struct consisting of a function pointer and optional context pointer to the write end. The read end is just another input for select. If it selects readable, read the same struct, and call the function with th... |
1,963,472 | 1,963,536 | how to create a gui to invoke a .exe or .cpp file? | i have a compiler project and i have used c++ , flex and bison in it
so bison and flex produce .cpp files to me and i can compile and run them
but i want to make a gui to my project
so i want to learn a technique to make a gui (in java or qt)
to write input to my project and get output
| There seems to be a bit of a language barrier, so let me attempt to state what I think I understand before providing my answer.
It appears that you're in a Compilers class, and your project is to write a C++ compiler. You've chosen to program this project using C++, with the help of bison and flex. Now that your proj... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.