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
3,886,826
3,886,936
How do I test for user input for equations?
I have an equation with 4 variables, I am prompting the user to enter each one of these variables, and then the program decides based on what variables are entered, which variables it needs to solve for. For instance, given variable a and b, I need to solve for b and c. I am trying to come up with a way for the program...
The pseudo-code that you've posted won't work, because >>x where xis an int will try to interpret the user's input as a specification of an integer. So, with the user typing ? what happens is that the operation fails, cin is put in a failure state, and further input operations are ignored until or if that failure state...
3,886,836
3,886,879
Optimizing 1D Convolution
Is there a way to speed up this 1D convolution ? I tried to make the dy cache efficient but compiling with g++ and -O3 gave worse performances. I am convolving with [-1. , 0., 1] in both directions. Is not homework. #include<iostream> #include<cstdlib> #include<sys/time.h> void print_matrix( int height, int width, flo...
First of all, I would rewrite the dy loop to get rid of "[ (j-1) * width + i]" and "in_matrix[ (j+1) * width + i]", and do something like: float* p, *q, *out; p = &in_matrix[(j-1)*width]; q = &in_matrix[(j+1)*width]; out = &out_matrix[j*width]; for (int i=0; i < width; i++){ float res = -1.F * p[i] + q[...
3,886,907
3,887,118
Transform a list of pointers to base class
I have a design where I have a std::list of base pointers that I'd like to transform into a parallel list that adds behavior. The problem I'm having is that the object that I'm trying to use to do the transform doesnt know what the actual types are when it is invoked. It's quite possible that I'm missing something subt...
In addition to JoshD's suggestion, you can keep the door open for other transformations by using the visitor pattern. Add a method dispatch_visit to the Sprite hierarchy, using covariant return types: class Sprite{ virtual HTMLSprite * dispatch_visit( HTMLConvert_ const &c ) const = 0; }; class Character : public S...
3,886,970
3,887,082
How do i change my merge algorithm to accept different arguments in c++?
The original code i wrote uses these arguments: int m = size of sorted list 1 int n = size of sorted list 2 int A[] = sorted list 1 int B[] = sorted list 2 int C[] = merged list of 1 and 2 I was asked to add this code to an existing file that uses these different arguments: IntVectorIt start1 IntVectorIt end1 IntVector...
Since it sounds like homework, I won't write the whole solution. However, here are some suggestions on migrating mymerge: Change the signature to void mymerge( IntVectorIt aStart, IntVectorIt aEnd, IntVectorIt bStart, IntVectorIt bEnd, IntVectorIt cStart, IntVectorIt cEnd ); Change the ru...
3,887,002
3,887,009
Update and multiple console windows
I want to write a simple c++/c console app, to show my process 1% 2%. for now, i print it line by line like finished 1% finished 2% and etc How can I just update percentage x% without printing a new line? Also, I want to open two console windows one show messages one show the process as above. How do I open another co...
On most-all terminals, you can print the ASCII carriage return '\r' (value 13 decimal) to return the cursor to the left of the current line, allowing you to overwrite the previous value. Or, you can send backspaces ('\b', ASCII 8) to move a single character left. Neither will automatically remove content already disp...
3,887,007
3,887,014
C++ Struct in array, help!
I have an iPhone app that used to use an array of several thousand small objects for its data source. Now, I am trying to make it use C++ Structs, to improve performance. I have written the struct, and put it in "Particle.h": typedef struct{ double changeX; double changeY; double x; double y; }ParticleStruc...
Since you have already typedefed it in Particle.h, drop the word struct from the array declaration line (the line where the error is). HOWEVER, In C++, you do not need to typedef it, just write struct Particle { /* members */ }; Why are you declaring an array without the length? Consider using std::vector (tutorial) w...
3,887,061
3,887,074
Do virtual functions have to be public?
Here is the way I have my base class working: class AguiWidgetBase { //variables AguiDockingEnum dockingStyle; std::string text; AguiRectangle clientRectangle; AguiColor tintColor; AguiColor fontColor; std::map<int,int,CmpIntInt> children; //private methods void zeroMemory(); vi...
Virtual functions can have public, protected, or private access. A discussion of them via the C++ FAQ. Should I use protected virtuals instead of public virtuals? When should someone use private virtuals?
3,887,064
3,918,893
QVariant to QObject*
I'm trying to attach a pointer to an QListWidgetItem, to be used in the slot itemActivated. The pointer I'm trying to attach is a QObject* descendant, so, my code is something like this: Image * im = new Image(); // here I add data to my Image object // now I create my item QListWidgetItem * lst1 = new QListWidgetIte...
The answer is this // From QVariant to QObject * QObject * obj = qvariant_cast<QObject *>(item->data(Qt::UserRole)); // from QObject* to myClass* myClass * lmyClass = qobject_cast<myClass *>(obj);
3,887,249
3,888,056
Fastest way to communicate between c++ and c#
We are building a new vision inspection system application. The actual inspection system needs to be c++ for a number of reasons. For that system we will be using Boost & Qt. For our UI, we are currently looking at using WPF/C# for the UI and SQL based reports. The complicating factor that UI has to run both local o...
If you're really looking for the fastest way to communicate with your c++ inspection system, then I would implement both cases. A local interface by using named pipes (see here Interprocess communication for Windows in C# (.NET 2.0)) and a remote interface using Google protocol buffers for situations where your inspect...
3,887,674
3,888,045
Is there a way to flag (at compile time) "overridden" methods whose signatures don't match base signature?
Basically, I want the C# compiler functionality of its override keyword in my C++ code. class Base { virtual int foo(int) const; }; class Derived : public Base { virtual int foo(int); // wanted to override Base, but forgot to declare it const }; As we all know, the above code will compile fine, but yield some s...
If you can't wait for C++0x, Visual C++ already has this override keyword. (Since 2005 I believe). There the syntax is: virtual int foo(int) override; You're not obliged to type it, however. And its a non-standard microsoft extension.
3,887,689
3,887,698
Linking with --whole-archive flag
This problem is related to This question I asked yesterday. Now it seems that the linker flag --whole-archive forces the test object to be included in the binary. However, in linking with, g++ main.cpp -o app -Wl,--whole-archive -L/home/dumindara/intest/test.a -Wl,-no--whole-archive I get the following error: /usr/lib6...
.a files are meant to be statically linked, and so are not compiled with -fPIC. Consequently, you cannot make a shared library from it.
3,887,702
3,887,840
How to port Java interface codes into C++ abstract base class?
Im new in OOP programming and C++ and Im currently into learning design patterns. Just grab the Head First Design Patterns book to learn from. Its actually great and Im already getting hold into the basic concepts.The first chapter talks about programming to an interface rather an implementation. Unfortunately for me ...
Dang - should have known the head first gang would port it. Anyway here's one solution: // HeadFirst.cpp : Defines the entry point for the console application. // #include "stdafx.h" class QuackBehavior { public: virtual void quack() = NULL; }; class Quack : public QuackBehavior { ...
3,887,759
3,887,788
Trouble understanding whence a copy constructor came
I have the following small code: template <typename T> class V { public: T x; explicit V(T & _x) :x(_x){} }; int main() { V<float> b(1.0f); // fails return 0; } And it happens to fail. The message returned by g++ 4.4.5 is: g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"main.d" -MT...
Other answers discuss why you're getting a compile-time failure (which is what most questions are about when such failures are the most prominent part of the question). However. regarding your explicit question, "whence the second constructor came?": 12.8/4 "Copying class objects" of standard says: If the class defin...
3,887,849
3,887,866
Using *this in C++ class method to fully overwrite self instantiation
Is the following code safe? (I already know it compiles properly.) void Tile::clear() { *this = Tile(); } int main() { Tile mytile; mytile.clear(); }
It might work. It depends on how Tile& operator = (const Tile&); is implemented. However, there's nothing intrinsically erroneous with assigning *this to a new value.
3,887,871
3,887,940
Is inheritance of concrete classes evil?
I use interfaces/abstract base classes for most of my types and don't often inherit from concrete classes but I've recently run into a situation where either inheritance or composition is desired. I've been aware of the adage "program to an interface, not an implementation" but recently decided to dig deeper. I've se...
Not a C++ guy (have professional experience with big enterprise systems in c#, java, and ruby), but here is my 2 cents anyways This isn't a black and white thing. The problem with inheritance is that it introduces tight coupling. Worse, that coupling is usually around encapsulated state. Changes in super classes can ha...
3,888,058
3,894,369
Function Templates - Explicit specialisation vs Global Functions (C++)
I know that Function Templates are used so as to make the functions portable and so that they could be used with any data types. Also Explicit Specialization of templates is done if we have a more efficient implementation for a specific data type. But then instead of Explicit Specialization we could also just code a No...
It sounds like you're confusing compile-time efficiency with run-time efficiency. The choice of which function to call is made at compile time, not run time, so it will make no difference to the run time of the program. Explicit Specialization is used when you have a special case that can benefit from special treatment...
3,888,069
3,888,106
Memory allocation for member functions in C++
#include<iostream> using namespace std; class A { }; class B { public: void disp() { cout<<" This is not virtual function."; } }; class C { public: virtual void disp() { cout<...
For each instance of the class, memory is allocated to only its member variables i.e. each instance of the class doesn't get it's own copy of the member function. All instances share the same member function code. You can imagine it as compiler passing a hidden this pointer for each member function so that it operates ...
3,888,082
3,888,237
Implicit conversion not happening
The last question I asked was something I stumbled upon when trying to understanding another thing... that I also can't understand (not my day). This is quite a long question statement, but at least I hope this question might prove useful to many people and not only me. The code I have is the following: template <typen...
As Edric pointed out, conversions are not considered during template argument deduction. Here, you have two contexts where the template parameter T can be deduced from the type of the arguments: template<class T> v<T> operator+(V<T> const&, V<T> const&); ~~~~~~~~~~~ ~~~~~~~~~~~~ But you try to invoke t...
3,888,154
3,888,366
Is it possible to have an animated QSystemTrayIcon?
I can't seem to find any info about this. but a lot of kde apps use animated icons. As i know it setting as QIcon a gif won't work, as only first frame will be displayed.
I didn't try this but it is probably possible by setting new icon every few milliseconds. /* list of frames */ QLinkedList<QIcon> frames; /* frames are icons created from images in application resources */ frames <&lt QIcon(":/images/icon1.png") <&lt QIcon(":/images/icon2.png"); /* set timer */ QTimer timer = new QTim...
3,888,197
3,888,291
How do I know when one is done entering cin with \n? (loop)
From Australian voting problem: A bot will keep putting information and it can reach 1000 lines. Example of what he'll enter: "1 2 3 2 1 3 2 3 1 1 2 3 3 1 2 " How do I know when he has finished entering information? There is an extra \n at the end and that's my only guess on where to go. cin doesn't seem to detect \n,...
std::string line; while( std::getline(std::cin,line) && !line.empty() ) { std::istringstream iss(line); int i1, i2, i3; iss >> i1 >> i2 >> i3 if( !is ) throw "dammit!" process_numbers(i1,i2,i3); } if( !std::cin.good() && !std::cin.eof() ) throw "dammit!";
3,888,215
3,888,249
How to build FLTK to using with Netbeans (Windows)
How to build FLTK to using with Netbeans (Windows), i have tried but not success. Help me
What problem did you run into, and what compiler? I'll assume you're using GCC and the Cygwin tools? From FLTK's own site There are three ways to build FLTK under Microsoft Windows. The first is to use the Visual C++ 5.0 project files under the "visualc" directory. Just open (or double-click on) the "fltk.dsw" file to...
3,888,409
3,888,460
How to resolve linker error "cannot find -lgcc_s"
I have 3 tiny files which I use to make a static library and an app: test.h #ifndef TEST_H #define TEST_H class Test { public: Test(); }; extern Test* gpTest; #endif test.cpp #include "test.h" Test::Test() { gpTest = this; } Test test; main.cpp #include "test.h" #include <iostream> using name...
I think -- is the problem here: -Wl,-no--whole-archive Try with -Wl,-no-whole-archive edit About not seeing the test symbol in your app with nm app: I think you don't need -L since you give full path and name of test.a - do either -Wl,--whole-archive -L/home/dumindara/intest/ -ltest -Wl,-no-whole-archive or -Wl,--w...
3,888,482
3,888,672
Pros and cons of 'inline'
First of all, I would like to state the facts I know about 'inline', so that you don't bother to restate them. An inline function is a special kind of function whose definition must be available in every translation unit in which the function is used. It is a hint to the compiler (which it is free to ignore) to omit ...
The only pro I know of is that (2.) may make the code faster. May being the operative word. Inlined functions may make certain code paths faster, yes. But an inlined function puts additional pressure on the instruction cache on most modern CPUs. If your function is too large to fit in the L1 instruction cache, it may...
3,888,611
3,888,696
QT separator widget?
Greetings all, Is there any widget to separate two QWidgets and also give full focus to a one widget. As shown in following figure ? Thanks in advance, umanga
How about QSplitter? QWidget 1, for exmaple, QListView. QWidget 2 is a combination of QWidgets (the left part is simple QPushButton with show/hide caption, and the right part another widget)... All you have to do, is to hide your QWidget2 when user clicked on QPushButton... If you need an example, I may post it. Upda...
3,888,694
4,179,500
Parsing <multi_path literal="not_measured"/> in TinyXML
How do I parse the following in TinyXML: <multi_path literal="not_measured"/> I am able to easily parse the below line: <hello>1234</hello> The problem is that the first statement is not getting parsed the normal way. Please suggest how to go about this.
Not 100% sure what youre question is asking but here is a basic format too loop through XML files using tinyXML: /*XML format typically goes like this: <Value atribute = 'attributeName' > Text </value> */ TiXmlDocument doc("document.xml"); bool loadOkay = doc.LoadFile(); // Error checking in case file is missing if(loa...
3,888,867
3,888,908
Why is this program overloading () operator?
Currently I am studying Standard Template Library (STL). In this program I am storing some long values in Associative Container and then sorting them according to unit's place (according to the number in unit's place). Code : #include <iostream> #include <set> #include <functional> using namespace std; class UnitLes...
The class's purpose is to implement a function that sorts the elements in the set in a given way. This is known as a predicate. It is implemented as a functor, i.e. by allowing the function operator to be used on an object (this is what std::set does beneath the hood). Doing so is the common way for STL and similar cod...
3,888,896
3,888,917
function try block. An interesting example
Consider the following C++ program struct str { int mem; str() try :mem(0) { throw 0; } catch(...) { } }; int main() { str inst; } The catch block works, i.e. the control reaches it, and then the program crashes. I can't understan...
Once the control reaches the end of the catch block of function-try-block of a constructor, the exception is automatically rethrown. As you don't catch it further in main(), terminate() is called. Here is an interesting reading: http://www.drdobbs.com/184401316
3,888,973
3,889,006
Converting arrays in stl like copy
It's time for another 'how do i do this in c++ without loosing my grip'-question! This time: Considering the following code taken from cplusplus.com: template<class InputIterator, class OutputIterator> OutputIterator copy ( InputIterator first, InputIterator last, OutputIterator result ) { while (first!=last) *resu...
yes, the type of *result is ('cause the type of result is OutputIterator ) typename std::iterator_traits<OutputIterator>::value_type of course, if OutputIterator is a pointer or a correctly written STL-compatible iterator. Otherwise, no, I think there is no way. In the upcoming C++0x, it would be much easier, that is...
3,889,016
3,889,079
Face Detection Library with C/C++ interface
Can you please point me to library(ies) for face detection (NO RECOGNITION NEEDED!)? Any good-working libraries except OpenCV(!!!). Preferably free of charge - open source is not required.
What bothers you about OpenCV? Their API or something else? There is libface which is an opencv wrapper for face detection and recognition.
3,889,082
3,889,251
What does the warning "alignment of a member was sensitive to packing" mean in C++
What does the warning "alignment of a member was sensitive to packing" mean in C++? I'm using Visual Studio 2005. How do I go about removing these warnings? I don't want to disable them btw.
Some data types must be aligned to a certain boundary. So for example: struct V { char a; double b; char c; double d; }; sizeof(char) is 1 and sizeof(double) is 8 but the size of that struct may be more than the expected 18 if it needs the doubles to align to an 8-byte boundary. In that case, and because the m...
3,889,403
3,889,427
How Can I pass message from DLL to Application
I have a ATLCOM Shell Extension which adds Right Click Extension to Windows Explorer. How Can I pass a message from my DLL to another MFC application. To Sumarize, I want to pass a Message from DLL to MFC application.
You can use Windows API SendMessage or PostMessage.
3,889,434
3,899,129
bitscan (bsf) on std::bitset ? Or similar
I'm doing a project that involves solving some NP-hard graph problems. Specifically triangulation of Bayesian networks... Anyway, I'm using std::bitset for creating an adjacency matrix and this is very nice... But I would like to scan the bitset using a bsf instruction. E.g. not using a while loop. Anybody know if this...
Looking at the STL that comes with gcc 4.0.0, the bitset methods _Find_first and _Find_next already do what you want. Specifically, they use __builtin_ctzl() (described here), which should use the appropriate instruction. (I would guess that the same applies for older versions of gcc.) And the nice thing is that bitset...
3,889,460
3,889,493
How to approach debugging a huge not so familiar code base?
Seldom during working on large scale projects, suddenly you are moved on to a project which is already in maintainance phase.You end up with having a huge code C/C++ code base on your hands, with not much doccumentation about the design.The last person who could give you some knowledge transfer about the code has left ...
If possible, step through it from main() to the problematic area, and follow the execution path. Along the way you'll get a good idea of how the different parts play together. It could also be helpful to use a static code analysis tool, like CppDepends or even Doxygen, to figure out the relations between modules and be...
3,889,531
3,891,175
init_priority attribute on variables in static libs
This is a new question after my long rant. The problem here is, I have a global vector<Base*> vObjs in my main application and I got Derived objs in each static lib linked to the application. If I specify the vObjs to have an init_priority of 101 and each obj in static libs to have say... 1000, is it guaranteed that vO...
Let me echo the other responses that you might want to reconsider using globals for this. However one possible (and I'm sure still flawed) improvement at least removes the need for init priority. Instead of using a global vector, you create a function that returns a reference to a static local. The C++ rules make sure ...
3,889,555
3,892,772
Progressive disclosure control
In the windows API, how do I implement a Progressive disclosure control?
Gonna be a lot of hand coding, probably. If you're using it for a message box, look into TaskDialog: it has something similar built-in. Otherwise you're probably on your own.
3,889,626
3,889,917
ld: duplicate symbol. g++
Ok I'm trying to get my head around g++ and librarys. I have a few files that I've compiled into a library from the make file $(CC) -fPIC -c -o $@ $< -O2 -D__PS2 then $(CC) -shared -o $@ $(OBJ_FILES) -O2 -D__PS2 this compiles fine. from the program that uses the lib $(CC) -c -o $@ $< -I./ compiles fine $(CC) -o $@ $...
A solution is to declare loggerInstance inline. This is the real use of the inline keyword. Your function will be inlined if the compiler wishes, but it won't be defined twice.
3,889,811
3,889,870
Function try blocks, but not in constructors
just a quick question. Is there any difference between void f(Foo x) try { ... } catch(exception& e) { ... } and void f(Foo x) { try { ... } catch (exception& e) { ... } } ? If no, why are function try blocks for (the case of initialization lists for constructors being put aside) ? What ...
Function try blocks are only ever needed in constructors. In all other cases exactly the same effect can be achieved by enclosing the entire body of the function in a normal try/catch block. If the copy constructor used to initialize a parameter throws an exception this happens before the function call. It cannot be ca...
3,890,047
3,890,362
Why is std::type_info polymorphic?
Is there a reason why std::type_info is specified to be polymorphic? The destructor is specified to be virtual (and there's a comment to the effect of "so that it's polymorphic" in The Design and Evolution of C++). I can't really see a compelling reason why. I don't have any specific use case, I was just wondering if t...
I assume it's there for the convenience of implementers. It allows them to define extended type_info classes, and delete them through pointers to type_info at program exit, without having to build in special compiler magic to call the correct destructor, or otherwise jump through hoops. surely that implementation coul...
3,890,081
3,890,128
White-box testing - friends or preprocessor?
Imagine we have a class like this: class Testee { public: void Func() private: void auxFunc() }; and we want to do white-box unit-testing on it. Which do you think is a better approach? To declare the tester class a friend of the testee class? Or use the preprocessor like this: class Testee { public: ...
How about: #ifndef UNITTEST_SYMBOL #define semiprivate private #else #define semiprivate public #endif and declare your class like:   class Testee     {     public:        void Func()     semiprivate:        void auxFunc()     }; or even, if you're daring enough, do #define private public when testing.
3,890,404
3,891,240
How can etags handle multiple directories
How it is possible under emacs and C++ to extend etags covering multiple directories? (I am not referring to recursive etgas which has a straight forward solution by using the -R option). Something like this is needed, for example, in the case where we are using a third party library, including its headers, that could ...
Answering the main question: use find to traverse your directories Example in my tagging script: find . \( -name "*[tT]est*" -o -name "CVS" -o -name "*#*" -o -name "html" -o -name "*~" -o -name "*.ca*" \) -prune -o \( -iname "*.c" -o -iname "*.cpp" -o -iname "*.cxx" -o -iname "*.h" -o -iname "*.hh" \) -exec etags -a {...
3,890,552
3,890,643
Problem when #import C++ Header File in iPhone/iPad Project
I have a C++ class I would like to use in an iPhone/iPad project. I created this file in different ways (like with "New File" => C++) and the error is always the same. When I compile the project without having any #import (of the .h C++ class), it's ok. But as soon as I #import the header file in one of my header objec...
Note: Xcode requires that file names have a “.mm” extension for the Objective-C++ extensions to be enabled by the compiler. Trying to use C++ in Objective-C code residing in a file with .m extension is the most probable cause of the problem because compiler just does not recognize C++ constructs according to th...
3,890,636
3,890,721
Convert from C++ style printing to my_printf()
C++ purists may want to look away now. You will hate this. I have been given an open source windows console app that I am merging with a pre-existing, very old, very large windows app of my own. My old program started life as pure C though recently has been tweaked so that it can compile as C++. My program makes extens...
You might find string streams useful. For example: std::ostringstream os; os << "Print " << whatever << data; my_printf( "%s", os.str().c_str() ); In case you were feeling adventurous, you could write your own streambuf instead that used my_printf underneath, and inject it into the stream object that is currently used...
3,890,720
3,890,821
'<function-style-cast>' : cannot convert from 'int' to 'CString'
This code was written in Visual Studio 2003, but now I compile it in 2008. int AFXAPI AfxMessageBox(LPCTSTR lpszText, UINT nType = MB_OK, UINT nIDHelp = 0); if(iiRecd == SOCKET_ERROR || iiRecd == 0) { iErr = ::GetLastError(); AfxMessageBox(CString(iErr)); goto PreReturnCleanup; } In 2003, it works fine, but in ...
It's a bit hard to help without any information, like the erroneous code and what you want to do there. Here's a guess: You want to convert an int to a CString, somehow like this: int i = 42; CString str = (CString)i; If you're using the MFC/ATL CString you could try the following int i = 42; CString str; str.Format("...
3,891,110
3,891,182
Mono c# vs c++ in opengl game development?
Which of these languages is better for opengl game with primary platform linux? I would like if you compared them in performance and libraries support.
C++ is a low-level, highly flexible and powerful language. It compiles native code (it's fast) and has a large array of helpful libraries. I would recommend it for any OpenGL project. You may also look into other c-family languages, that share many of the same benefits. (I sound like an ad)
3,891,131
3,891,170
Microsoft .net, is it worth it?
So with Microsoft .NET, you get the advantage of language interoperability. But I've heard that this is slower than native applications. What if you only need one language? Then what are the advantages. I am a C and C++ programmer, and .net seems to be heavily tied with C#. Is this the case? And is dot net portable, or...
'.NET is slow' is a misconception, along with 'Java is slow'. Yes, it used to be slower than native, and yes, you can get faster programs using hand-optimized assembly, but for nearly all cases short of core engine code for games, .NET is as fast as doing the same thing in C or C++, and can (in some cases) be faster. Y...
3,891,145
3,891,218
convert std::string to LPCSTR with trailing or leading '\0'
How can I convert std::string to LPCSTR while preserving '\0' characters? I want to use the result on OPENFILENAME.lpstrFilter which requires the filter to contain '\0' as delimiters. std::string.c_str() seems to strip and trim '\0' Thanks in advance! ========================== (How do I properly add a comment to the ...
C_STR doesn't strip the NUL characters. The error is likely in the way you are constructing the STD::string.
3,891,402
3,891,478
Operator overloading and namespaces
Possible Duplicate: Where should non-member operator overloads be placed? While browsing on SO, I often find questions or answer that involves overloading/defining a std::ostream& operator<<(std::ostream& os, const Foo& foo) or a Foo operator+(const Foo& l, const Foo& r). While I know how and when (not) to write the...
It should be in the bar namespace. You must consider what makes up the interface for the class, and group those together. "A class describes a set of data along with the functions that operate on that data." Your free function operates on a Foo, therefore it is part of Foo. It should be grouped with Foo in the namespac...
3,891,410
4,380,604
gSOAP does **not** close sockets?
I've an issue with gSoap - it's not closing the socket.. Here's the situation: the application is working fine, but when I call "reload" function, it cannot reconnect.. Here's a piece of code: soap_destroy( &m_soapObj ); soap_end( &m_soapObj ); soap_done(&m_soapObj); sleep(1); soap_init(&m_soapObj); //m_ptrThis shou...
You should find out exactly what error is being thrown. It is possible you are getting an "Address Already in Use" error from bind(). You can try to correct for this by using setsockopt() - or the equivalent soap call - with the SO_REUSEADDR option. This link provides a concise explanation.
3,891,529
3,891,549
c++ cast vector<Inherited*> to vector<abstract*>
class Interface{}; class Foo: public Interface{}; class Bar{ public: vector<Interface*> getStuff(); private: vector<Foo*> stuff; }; How do I implement the function getStuff()?
vector<Interface*> result(stuff.begin(), stuff.end()); return result;
3,891,712
3,891,775
Confused about use of 'HANDLE' in piece of Visual C++ code for Real-Time IIS 7.0 Event Logging
I'm relatively new to Visual C++. I'm trying to build a module to consume log events generated by the IIS 7.0 server in order to be able to analyze these logs in real-time. I found a Microsoft article which provides code that accomplishes the real-time capture: http://learn.iis.net/page.aspx/581/advanced-logging-for...
This line: private: HANDLE m_hEventLog; is declaration of the variable m_hEventLog. It means that when an object of type MyGlobalModule will be declared, that will contain a member named m_hEventLog. When the object is declared, or in other words, constructed, the constructor is called. It executes the following line:...
3,891,866
3,892,536
Thread-safe lazy get and release
I'm running into kindof an annoying problem and would need some advice... Let's say I have a bunch of small MyObject's, that can construct bigger MyExtendedObject's. MyExtendedObject's are big and CPU consuming so construction is lazy, and I try do remove them from memory as soon as possible: MyExtendedObject * MyObjec...
As Steve said, you basically want shared_ptr for the construction/destruction part. If you can't use boost, then I'd recommend copying the appropriate code from the boost headers (I believe the license allows this), or whatever other workaround you need to circumvent your dumb corporate policies. The other advantage of...
3,892,098
3,892,209
Ctor Initializer: self initialization causes crash?
I had a hard time debugging a crash on production. Just wanted to confirm with folks here about the semantics. We have a class like ... class Test { public: Test() { // members initialized ... m_str = m_str; } ~Test() {} private: // other members ... std::string m_str; }; Someone changed the initia...
The first constructor is equivalent to Test() : m_str() { // members initialized ... m_str = m_str; } that is, by the time you get to the assignment within the constructor, m_str has already been implicitly initialized to an empty string. So the assignment to self, although completely meaningless and ...
3,892,334
3,892,340
(C++) Looking for tips to reduce memory usage
I've got a problem with a really tight and tough memory limit. I'm a CPP geek and I want to reduce my memory usage. Please give me some tips. One of my friends recommended to take functions inside my structs out of them. for example instead of using: struct node{ int f() {} } he recommended me to use: int f(no...
No, regular member functions don't make the class or struct larger. Introducing a virtual function might (on many platforms) add a vtable pointer to the class. On x86 that would increase the size by four bytes. No more memory will be required as you add virtual functions, though -- one pointer is sufficient. The size o...
3,892,379
3,892,620
Causing a divide overflow error (x86)
I have a few questions about divide overflow errors on x86 or x86_64 architecture. Lately I've been reading about integer overflows. Usually, when an arithmetic operation results in an integer overflow, the carry bit or overflow bit in the FLAGS register is set. But apparently, according to this article, overflows r...
In C language arithmetic operations are never performed within the types smaller than int. Any time you attempt arithmetic on smaller operands, they are first subjected to integral promotions which convert them to int. If on your platform int is, say, 32-bit wide, then there's no way to force a C program to perform 16-...
3,892,549
3,892,572
boost::numeric::ublas::vector<double> and double[]
I'm using boost for matrix and vector operations in a code and one of the libraries I am using (CGNS) has an array as an argument. How do I copy the vector into double[] in a boost 'way', or better yet, can I pass the data without creating a copy? I'm a bit new to c++ and am just getting going with boost. Is there a ...
Contents between any two input iterators can be copied to an output iterator using the copy algorithm. Since both ublas::vector and arrays have iterator interfaces, we could use: #include <boost/numeric/ublas/vector.hpp> #include <algorithm> #include <cstdio> int main () { boost::numeric::ublas::vector<double> v (...
3,892,961
3,893,093
C++ and Embedded Python - NUL Terminated Strings
I'm working on embedding Python 2.6 into an existing c++ application. So far I have the Libraries linked in and am able to successfully initialize the Python Interpreter and can also transfer data to Python. I'm having trouble retrieving it, and hope someone can steer me the right direction. I'm working with this: P...
A few points: Don't use strings. You might even be able to make them work here with some contortions on *_StringAndSize() functions, but it won't be what you want. You should store your data in a custom data structure (or a buffer) that is just a sequence of bytes (do you really want clients performing string operat...
3,893,191
3,893,243
Passing a const char* character string from unmanaged to managed
I have two communicating components - one managed, the other unmanaged. The managed needs to retrieve a character string from the unmanaged implementation (the same string or just a copy). I tried the following code. // Unmanaged code const char* GetTestName(Test* test) { return test->getName(); } // Managed wrapp...
You're close but you have to use PtrToStringAnsi(). Auto uses the system default which will be Unicode.
3,893,975
3,894,192
Point in axis aligned rectangle test?
My rectangle structure has these members: x, y, width, height. Given a point x, y what would be the fastest way of knowing if x, y is inside of the rectangle? I will be doing lots of these so speed is important.
This is how I usually do it. Given a point that is outside of the rectangle, this will do fewer tests in 3 out of 4 cases. And sometimes only one test is done. if(point.x < rect.x) return false; if(point.y < rect.y) return false; if(point.x >= rect.x + rect.width) return false; if(point.y >= rect.y + rect.height) ret...
3,894,303
3,894,329
How to attach to a process as a debugger and query information?
I want to essentially write my own profiler which attaches to my process, freezes execution, inspects the state (current instruction pointer, some metadata, etc..) and write this information to a log. How do I get started with this? If I can get in and inspect this information and then resume execution, I can proceed f...
You need the Debugger API in Win32. An overview here. To get you going here is info on how to attach to a running process.
3,894,311
3,894,338
Querying the status of a bit flag?
I am trying to parse some files that have a bitwise flag column. There are 11 bits in this flag and I need to find out, for each row in the files, what is the value of the 5th bit (1-based).
if (flags & 0x10) .... how did I know that mask (0x10) here are 8 bits 0b00000000 here is the fifth one starting from one (from the right) 87654321 0b00010000 and in hex that is 0x10
3,894,491
3,894,526
How can I process several inputs at once using cin or getline(), while only pressing "Enter" once?
nodeType* buildSet() { nodeType *first, *newNode, *last; first = NULL; int num = 0; string input = ""; getline(cin,input); stringstream myStream(input); while(myStream >> num) // while(num != -999) { newNode = new nodeType; newNode->info = num; newNode->link = NUL...
I fixed the problem by deleting the second "getline(cin, input)".
3,894,630
3,894,698
c++ directx muliti textures
How can I set set more than one texture on a cube like the front of the cube has different texture from the back of it.... I tired to use the stages but it didn't work. for example, if i wanna make a dice i would have top would be 1 side be 2.............. D3DXCreateTextureFromFile(d3ddev, //Direct3D Device ...
What you do is create a texture and put the 6 faces of the dice into that one texture. Then for each face you use the UVs that correspond to the portion of the texture that has the dice side you want on it. Failing that ... you draw 6 times. Once for each texture. The former method is by far the best way to do it if y...
3,894,760
3,894,909
C++: ptr_container comparison
How can I customize the comparison of elements in a ptr_container? Using a ptr_set, I would like to define a function that checks for equality of elements. However, defining bool operator==(const Foo& other) (or a friend function) does not work. It just won't be invoked, although boost's unordered containers, on the o...
Set uses the < operator to insert items and test for equivalence (which is not quite the same as equality). This operator must define a strict weak ordering. Set will not use the == operator. Quoted from the description for set: Compare: Comparison class: A class that takes two arguments of the same type as the co...
3,895,022
3,895,039
Variable initialisation not happening everywhere on certain platforms
I have a program that I built for RHEL5 32 bit and ubuntu10 64 bit (c++ qt4.6). When I run the program on ubuntu, all the variables are initialized without me needing to code this initialization. But When I run the program on RHEL, some of the variables are not initialized, I have noticed that they are mostly integer...
Different compilers do different things. The standard doesn't state that all variables should be initialized automatically, so many compilers don't. This means they are typically filled with garbage. Sometimes you luck out and get a block of zeros, but it's rare. Don't count on it.
3,895,048
3,895,062
Iterating without incurring the cost of IF statements
My question is based on curiosity and not whether there is another approach to the problem or not. It is a strange/interesting question, so please read it with an open mind. Let's assume there is a game loop that is being called every frame. The game loop in turn calls several functions through a myriad of if statement...
there is a game loop that is being called every frame That's a backwards way of describing it. A game loop doesn't run during a frame, a frame is handled in the body of the game loop. my assumption is that a function pointer is always going to be faster than an if statement Have you tested that? It's not likely t...
3,895,204
3,895,224
Find edge that a rectangle is touching on another rectangle
given an edge enum such as this: none, top, left, bottom, right, Given 2 rectangles, how could I find which edge of rectangle A that rectangle B is intersecting? I do not need to know which edge of B hit an edge of A, I just need to know which edge of A that B hit. I found this algorithm but it does not return the sp...
Assuming you've used edgeIntersection to determine that an intersection has occurred, then: if (b.x < a.x) return left; if (b.y < a.y) return top; if (b.x+b.width > a.x+a.width) return right; return bottom;
3,895,278
3,895,286
Insert with object as key fails to compile?
I'm having trouble getting something to compile. I don't understand the error thrown out by the compiler. Some code to illustrate the problem is below. #include <map> using namespace std; class Thing { public: Thing(int n):val(n) {} bool operator < (const Thing& rhs) const { return val < rhs.va...
You need mymap.insert(std::pair<Thing,int>(t1,x));, where x is the value you want to map to t1.
3,895,305
3,895,365
WinAPI Double-buffering
A default winAPI application does not have double-buffering. Instead, it does a very, very good job of ensuring that only what needs to be drawn is drawn, and that gives it a seamless appearance. However, when you resize the window, the entire thing needs to be redrawn, and this causes flickering between the controls, ...
Create a bitmap the size of the window, render into that bitmap, and blit that back into the window when you're done. You can do a pretty straight-forward in-place replacement in your existing code. Instead of using a device context that renders into the window, use one that renders into the bitmap, and only use the or...
3,895,313
3,895,323
Trying to understand pointers and arrays
Possible Duplicate: What is the difference between char s[] and char *s in C? I was wondering what is the difference between char *p1 = "some string"; and char p2[] = "some string"; in terms of memory, can these not be treated in the same way? e.g. void foo(char *p); ... foo(p1); foo(p2);
All is explained here: http://c-faq.com/aryptr/aryptr2.html
3,895,448
3,897,791
Strange winAPI behaviour
I have sub classed a tab control to give it a background. I have used the clipping functions to clip the drawing area to the update region. This works, except for when I move the window of the screen and back again. When it does this, it occasionally sets the clipping region to the whole screen. This is fine except tha...
By "clipping region" I assume you mean the area that has to be redrawn that windows passes to you. Try this: The paint message handler should bitblit the area of the background image that corresponds to the part of the window that needs to be refreshed (so you don't draw over things that don't need updating). Then let ...
3,895,634
3,895,702
Fast file copy with progress
I'm writing an SDL application for Linux, that works from the console (no X server). One function I have is a file copy mechanism, that copies specific files from HDD to USB Flash device, and showing progress of this copy in the UI. To do this, I'm using simple while loop and copying file by 8kB chunks to get copy prog...
Don't synchronously update your UI with the copy progress, that will slow things down considerably. You should run the file copy on a separate thread from the main UI thread so that the file copy can proceed as fast as possible without impeding the responsiveness of your application. Then, the UI can update itself at...
3,895,647
3,895,662
Why const for implicit conversion?
After extensive reading of ISO/IEC 14882, Programming language – C++ I'm still unsure why const is needed for implicit conversion to a user-defined type with a single argument constructor like the following #include <iostream> class X { public: X( int value ) { printf("constructor initialized with %i",value);...
It doesn't really have much to do with the conversion being implicit. Moreover, it doesn't really have much to do with conversions. It is really about rvalues vs. lvalues. When you convert 99 to type X, the result is an rvalue. In C++ results of conversions are always rvalues (unless you convert to reference type). It ...
3,895,746
3,895,753
Proper way to build up a path using cstrings in C++
I need to build up a path to a file. I have the following class method: void Directory::scanDirectory(char *directory) { DIR *dirp; struct dirent *entry; char path[1]; if(dirp = opendir(directory)) { while(entry = readdir(dirp)) { if (entry->d_name[0] != '.') { strcp...
The buffer path needs to have enough space to hold the whole path. Right now it only has space for a single character. Try making it bigger. strcat doesn't allocate space itself. You have to manually manage that memory. As for a better way, you may want to look into using a string. You won't need to worry about memory,...
3,895,757
3,898,877
Python audio library for simultaneous audio creation and playback
I'm working on an audio creation framework. It'll be generating large audio files, say 3 minute long audio files that take about 1 minute to generate. So what I want is a system much like streaming audio from the internet, where I play the sound as I generate it. Pygame's mixer allows me to edit the sound as it's playi...
pymedia.audio does work with Python 2.6. Take a look at this SO post: Pymedia installation on Windows with Python 2.6 You can append audio to Output objects, as they are playing. So as each sample is generated, it can also be appended to the stream. The example in their documentation shows just how to do this: http://p...
3,895,840
3,896,794
style in binding a reference to object-or-dummy
What is the best way to bind an rvalue reference to either a given object or a temporary copy of it? A &&var_or_dummy = modify? static_cast<A&&>( my_A ) : static_cast<A&&>( static_cast<A>( my_A ) ); (This code doesn't work on my recent GCC 4.6… I recall it working before, but now it always ret...
Just avoid this whole mess with an extra function call: void f(bool modify, A &obj) { return [&](A &&obj) { real(); work(); }(modify ? std::move(obj) : std::move(A(obj))); } Instead of: void f(bool modify, A &obj) { A &&var_or_dummy = /* ??? */; real(); work(); } It's lambdas, lambdas, everywhere!
3,895,879
7,870,060
installing opencv on windows(W32) to be used with code blocks
i am trying to use opencv library with code blocks(8.02).i have installed opencv2.1. when i include the headers and link the library its all fine.i have gone through http://opencv.willowgarage.com/wiki/CodeBlocks tutorial as well.but when i compile the project it reports no error or warning.it just says exit with stat...
I had this exact same problem a couple of weeks ago and couldn't find an answer anywhere ! After messing around with it, I found out exactly how to do it. 1) Compile the library using Cmake. http://www.cmake.org/ 2) After your library is compiled you should have two different OpenCV libraries - a compiled one, and a n...
3,896,050
3,896,277
Does const help the optimizer? C++
Possible Duplicate: Constants and compiler optimization in C++ Let the holy wars begin: I've heard a number of differing opinions on the usefulness of const in C++. Of course it has uses in member function declarations, etc. But how useful is it as a modifier on variables (or rather, constants)? Does it indeed help ...
const does not help the optimizer. Since const can be cast away with const_cast, it's possible to write programs that use const in a number of places, then cast it away and modify variables anyway, with defined behavior according to the standard. The compiler therefore must look at the actual code of the program to de...
3,896,313
3,897,270
Simple interpreter to embed and extend inside an C++ Windows application
I need a simple interpreter which will do execution (evaluation) of simple expressions/statements and also call functions from main C++ applications. At the moment I do not need scripting of the application, but it may be useful later. It should also be strait-forward for other team members to pull my application from ...
Two great options you've already listed are Python and Lua. Here are some of the tradeoffs for your consideration: Python A much more complete and powerful language (IMHO!) with libraries for anything and tons of support and communities everywhere you look. Syntax is not entirely C-like Although Python wasn't designed...
3,896,357
3,897,217
Unordered (hash) map from bitset to bitset on boost
I want to use a cache, implemented by boost's unordered_map, from a dynamic_bitset to a dynamic_bitset. The problem, of course, is that there is no default hash function from the bitset. It doesn't seem to be like a conceptual problem, but I don't know how to work out the technicalities. How should I do that?
I found an unexpected solution. It turns out boost has an option to #define BOOST_DYNAMIC_BITSET_DONT_USE_FRIENDS. When this is defined, private members including m_bits become public (I think it's there to deal with old compilers or something). So now I can use @KennyTM's answer, changed a bit: namespace boost { ...
3,896,429
3,897,144
Deep copy of vector<Point> myArr
In order to make a deep copy of myArr, vector <Point> myArr; where Point is a class with 2 ints as members, Do I need to do something special? or is ok with vector <Point> otherArr = myArr; I need to delete some points in otherArr but at the same time I need all the points in myArr for later usage. thanks in advance
See Shallow vs Deep Copies and Effective C++ Point does not need deep copy. As a thumb rule, "deep copy" is required when a class has pointer members. The Point class have only two int members, so it does not require any special effort for "deep copy", the normal or "shallow copy" would do perfectly fine. In fact, it i...
3,896,484
3,896,912
Design pattern "Container Visitor" without virtual methods?
I am developing the design of an application and I thought I might apply some sort of the Visitor design pattern, but it turned out that it's not exactly what I am looking for. Maybe someone can point me to the variant I require in this case? Much of my code has a template argument "ContainerType" like template <class ...
If you can change the way container classes are defined, it looks like it could be very easy to achieve with Boost.Fusion For Example #include <iostream> #include <boost/fusion/container/vector.hpp> #include <boost/fusion/algorithm/iteration/for_each.hpp> struct A {}; struct B {}; struct C {}; namespace fusion = boo...
3,896,510
3,896,556
Subclassing tab control
What is the proper way to subclass a tab control in winAPI, having windows perform both the default drawing and your own. Because BeginPaint() and EndPaint() are calling within the default proc, I don't see a way to do this. I did get it working with GetDC(), but it had a very bugs which annoyed the hell out of me. If ...
Subclassing is not required in your situation. The tab control supports the TCS_OWNERDRAWFIXED style bit, which allows its parent window to handle WM_DRAWITEM messages and draw the tabs itself. There's a nice exemple on Codeguru. It uses MFC but don't let that stop you. Check out their CTabCtrlEx::DrawItem() method.
3,896,717
3,896,816
Example of how to use boost upgradeable mutexes
I have a multithreaded server application that needs mutex locks over some shared memory. The shared memory are basically sTL maps etc. Much of the time I'm just reading from the map. But, I also need to occasionally add to it. e.g. typedef std::map MessageMap; MessageMap msgmap; boost:shared_mutex access_;...
You said that your application is multithreaded, so you should use boost::thread not boost::interprocess. From the documentation (not tested) you should do it this way: typedef boost::thread::shared_mutex shared_mutex; boost::thread::upgrade_lock<shared_mutex> readLock(access_); // Read access... boost::thread::upgra...
3,896,799
3,896,830
Process Start Limitation
I have create a simple application which using C++ and produce a executable file. I would like to ensure the process cannot be start twice. How to enforce a process/service is start once only ? Thanks.
Write a temporary file and use it as a lock. Edit: To answer the comment: If you are on a Unix system, write a file /tmp/my_application_lock_file. If it already exists, stop your program with an appropriate message. On exit of the creator of the file, delete it. #include <sys/stat.h> #include <errno.h> #include <unistd...
3,896,872
3,896,909
C++ check if a list contains a sublist
I need a container in which I can check if a sequence of elements are present or not. Same thing as substring matching, just for generic collections. I know it's not hard to write, but if it's implemented in some lib already, I wouldn't bother (maybe Boost has something like this?)
Any sequence container will do. You just need to use std::search algorithm to do the search of the sublist: vector<int> sequence = ...; vecter<int> sublist = ...; vector<int>::iterator pos = std::search( sequence.begin(), sequence.end(), sublist.begin(), sublist.end()); if(pos == sequence.end()) // not ...
3,896,997
3,897,094
Creating and using dll's: __declspec(dllimport) vs. GetProcAddress
Imagine we have a solution with 2 projects: MakeDll (a dll app), which creates a dll, and UseDll (an exe app), which uses the dll. Now I know there are basically two ways, one is pleasant, other is not. The pleasant way is that UseDll link statically to MakeDll.lib, and just dllimports functions and classes and uses th...
MakeDll.lib contains a list of studs for the exported functions and their RVAs into the MakeDll.dll MakeDll.dll is loaded into the application based on what type of loading is defined for the dll in question. (e.g. DELAYLOAD). Raymond Chen has an interesting article on that. You can use the new updated version of Mak...
3,897,070
3,897,147
Disable aero fade-in effect on dialog
I have a modal dialog I'm creating with MFC. When it appears, the Aero theme does it's fade-in transition for a new window appearing. In my particular case I'm switching immediately from one dialog to another and the fade effect is distracting. Is there a way it can be disabled so the window immediately appears, lik...
The DwmSetWindowAttribute function might be able to help you. It lets you modify a number of window attributes related to the DWM. In particular, the DWMWA_TRANSITIONS_FORCEDISABLED attribute mentions "Enable or forcibly disable DWM transitions", which just might do the trick. HRESULT hr = S_OK; LPCVOID dwAttribute = ...
3,897,229
3,899,092
Extending Protobuf with my own methods
How should I add methods a Protobuf message? Suppose I have in my .proto file: package proto; message Person { required string name = 1; required int32 id = 2; optional string email = 3; } and I want to add a method, say, string concatenateNameEmail() to the message. What I do right now is I create my own C+...
Google Protobufs are specifically not intended to be extended. Here's a paragraph from the documentation (in the middle of this: http://code.google.com/apis/protocolbuffers/docs/cpptutorial.html): Protocol Buffers and O-O Design Protocol buffer classes are basically dumb data holders (like structs in C++); they...
3,897,248
3,974,886
Are there any Oracle Stored Procedure Accessor Generators for C++?
I've been spending more and more time writing DB Wrappers for Oracle access. This seems to be quite generic procedure, and I was wondering is there already are code generators that generate access routes to Oracle PL/SQL Stored Procedures in C++? I'm looking for a configurable generation tool that would be capable of m...
You might also want to have a look at: http://orclib.sourceforge.net http://otl.sourceforge.net/ http://www.codeguru.com/cpp/data/mfc_database/oracle/article.php/c4305
3,897,273
3,897,280
sizeof(): the size of a class isn't the same as the size of it's members together?
First of all, on my system the following hold: sizeof(char) == 1 and sizeof(char*) == 4. So simply, when we calculate the total size of the class below: class SampleClass { char c; char* c_ptr; }; we could say that sizeof(SampleClass) = 5. HOWEVER, when we compile the code, we easily see that sizeof(SampleClass) = 8....
Compilers usually add padding to structures to align them on word boundaries (because accessing word-aligned locations requires fewer memory accesses and hence is faster). So even though the char takes only 1 byte, c_ptr is shifted to the next 4-byte boundary, hence the result of 8 bytes.
3,897,675
3,897,703
How to append different files and extract them for verification in my code?
if i have both encrypted message and signature (let's say two different size files), i just want to append them and store in a file together but later i will use the same "only one file" to extract the files and verify in my code. in that way my code will get only one file as an input but can understand which is encryp...
Uhm,... I think what you want to do is store two files in one and then extract both files from that one, but please do correct me if I misunderstood. You could just use zips (gzip, 7zip, whatever) with no compression. If you want to code it yourself, you can store the following information in a file: offset 0 - 3: a 4-...
3,897,682
3,898,495
c++ how to make two vectors one with data the other points and reads only
In C++ I have 2 STL vectors A and V. A has data and is able to change it, V only points to data but reads only and can't modify it. So if these two vectors are inside a class what will be the syntax of Variables definition assigning A reference into V get_A() and get_V() will it return a reference or a pointer? Als...
The vectors will be declared as vector<Data> A; vector<const Data *> V; (Note that V cannot be a vector of const Data & because references are not Assignable, and vector requires an Assignable template type.) Assigning a reference from A into V would look like this: V[i] = &A[i]; I'm not sure what you mean by get_A...
3,897,702
3,897,724
Why does msvc let me do this but not gcc / g++?
In msvc, I have functions like this and it builds but in gcc it doesnt like it. void classname::a(std::string &text) { stdStringFromClass = text; } void classname::b(char *text) { a(std::string(text)); } The issue here is in the &, gcc I think is worried that since I just created that std::string, that passin...
I have no idea why Visual studio allows you to compile this, but you can't pass a reference to an anonymous object. Edit: Its ok for const reference, cause you can pass the temporary object as reference, just being able to modify it doesn't make sense. That's why we have rvalue references in C++0x. Edit2: To your edit,...
3,897,839
3,917,033
How to link C++ program with Boost using CMake
What should my CMake file look like for linking my program with the Boost library under Ubuntu? The errors shown during running make: main.cpp:(.text+0x3b): undefined reference to `boost::program_options::options_description::m_default_line_length' The main file is really simple: #include <boost/program_options/option...
In CMake you could use find_package to find libraries you need. There usually is a FindBoost.cmake along with your CMake installation. As far as I remember, it will be installed to /usr/share/cmake/Modules/ along with other find-scripts for common libraries. You could just check the documentation in that file for more ...
3,898,060
3,898,080
Why is this loop only running once?
Why is this loop only running once? noteDatabaseItem just takes a node and fills in the data. the xml has 3 notes in it. XML: <?xml version="1.0" encoding="utf-8"?> <noteCollection> <note name="Test Note 1">This is test note 1 content!</note> <note name="Test Note 2">This is test note 2 content!</note> <note name...
Shouldn't it be node = node->NextSiblingElement("note")? noteCollection has only children, not siblings, right?
3,898,158
3,898,171
error: cast from 'Foo*' to 'unsigned int' loses precision
I'm trying to cast a pointer to an int (or unsigned int) and no matter what I try it doesn't want to work. I've tried static_cast<intptr_t>(obj), reinterpret_cast<intptr_t>(obj), and various combinations of C style casts, intptr_t's, unsigned int's, and I'm including stdint.h. From what I've read, one of the many thin...
You're either on a platform where sizeof (Foo*) > sizeof (unsigned), or your compiler is set to warn about non-portable code. Note that most 64-bit compilers, both LP64 and LLP64, fall into this category. There's no requirement that a pointer fit in an int. That's the whole point of intptr_t. If you're using a third-...
3,898,173
3,898,219
Creating my object takes too long. Is it bad practice to create a ton of instances at startup to speed things up later?
I have a wizard class that gets used a lot in my program. Unfortunately, the wizard takes a while to load mostly because the GUI framework is very slow. I tried to redesign the wizard class multiple times (like making the object reusable so it only gets created once) but I always hit a brick wall somewhere. So, at this...
In games, we often first allocate and construct everything needed in a game session. Then we recycle the objects if they have short life-time, trying to get 0 allocations/deallocations while the game session is running. So no it's not really a hack, it's just good sense to make the computer do less work to get faster. ...
3,898,287
3,898,305
C++ #include <atlbase.h> is not found
When I compile my C++ program in Visual Studio Express it says that it can't find atlbase.h. Am I missing some SDK or something?
Microsoft ATL (Active Template Library), which includes the header atlbase.h is included with the Windows 2003 SDK, but it is not included with any newer Windows SDK release. It is also included with Professional editions of Visual Studio.
3,898,306
3,898,319
initialization of the static variables
I've just read that if I want to be sure about the initialization order it will be better to use some function which will turn global variable into local(but still static), my question, do I need to keep some identifier which tells me that my static object has already been created(the identifier inside function which p...
As far as the standard is concerned, initialization of a function-scope static variable only happens once: int *gettheint(bool set_to_four) { static int foo = 3; // only happens once, ever if (set_to_four) { foo = 4; // happens as many times as the function is called with true } return &foo; }...
3,898,435
3,898,451
Labels in GCC inline assembly
In my ongoing experimentation with GCC inline assembly, I've run into a new problem regarding labels and inlined code. Consider the following simple jump: __asm__ ( "jmp out;" "out:;" : : ); This does nothing except jump to the out label. As is, this code compiles fine. But if you place it inside a f...
A declaration of a local label is indeed a number followed by a colon. But a reference to a local label needs a suffix of f or b, depending on whether you want to look forwards or backwards - i.e. 1f refers to the next 1: label in the forwards direction. So declaring the label as 1: is correct; but to reference it, yo...