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
5,447,972
5,448,010
Concatenate four string constants into one
I have two string constants const char * like this: const char * p1 = "abcd"; const char * p2 = "efgh"; I want to convert these into a single string so that it becomes a file name: const char * filename = "abcd_efgh.txt"; I tried to concatenate the char * but failed. Kindly guide me as to how to do this. Thanks
I would go with sprintf() char buffer[strlen(p1) + strlen(p2) + 6]; sprintf(buffer, "%s_%s.txt", abcd, efgh); (You're adding 6 for the _, .txt, and the \0 to terminate the string; 1 + 4 + 1)
5,448,153
5,448,163
Unhandled exception while reading structures
The program throws an unhandled exception on this line: }else if(s == "backpack"){ cout << "\nEquipped items: " << endl; cout << weapon->Name << endl << cArmour->Name << endl; //this line It prints 'Equipped items: ' then throws an exception. This file - Player.h - includes Library.h, which in turn includes Gl...
I'm guessing either weapon or cArmour is null or point nowhere. That's all more likely since you're not storing your "None" weapon and armor in your global hash. Try printing out the pointer for those two "None" objects, then the pointer values for the object members weapon or cArmour.
5,448,282
5,448,360
making an VC++ .exe to DLL .is it possible?
I have an VC++ win 32 application which compiles into an EXE. But now I want to convert it into dll so that I can load that in another application.I tried changing in Visual Studio properties from .EXE to .DLL which successfully converted it but whn i use GetProcAddress it always returns NULL . I am not sure what I am...
You need to export the functions you wish to access using the __declspec dllexport keyword. So if you add the manifest constant 'BUILDING_MY_DLL' to the project, the header file that declares the functions you care about can be used in both the DLL project and any code that uses the DLL: #ifdef BUILDING_MY_DLL #define ...
5,448,341
5,448,435
Is QThread on user level, kernel level or both?
I'm writing portable code for multicore machines and I want kernel level threads so the threads can use more than one cpu. After reading QThread documentation on Qt Assistant I still haven't found any hints. On Windows XP the multithreading example (mandelbrot) from the QtSDK used only one core. So I guess on XP only u...
I don't know about Windows, but on Unix it is using pthreads. QT isn't exposing API for CPU affinity because it needs to be platform- and hardware-independent. The QThread distribution across CPUs is left to the OS scheduler, you can't hint it via some QT API.
5,448,708
5,448,775
Confusion with typename and therefore errors
//more code omitted that is not relevant, the IF template is not completely shown here template <bool condition, typename ThenType, typename ElseType> struct IF { typedef typename ChooseSelector<condition>::RETURN Selector; }; template <bool condition> struct ChooseSelector { ...
Put your IF template after the ChooseSelector template. When compiling the IF template, ChooseSelector need to exist as a template, you're using ChooseSelector<condition> which is parsed first pass. The typename is needed to tell the compiler that RETURN, which is fully evaluated on instantiation when specializations a...
5,448,754
5,448,781
Recommended way to use C++ class into Objective-C class minimizing using of Objective-C++?
I'm mixing Objective-C and C++. However I want to minimize using of Objective-C++. Because it has some kind of limits in both of Objective-C and C++. Currently, I'm using it like this. // A.h, Objective-C #import "B.h" @interface A { B* b; } @end // B.h, Objective-C++ @interface B { void* c; } // C.h, C++ cla...
There are a couple of ways of doing this, but in my opinion the best method is to use the 'PIMPL' idiom, which is fairly common in C++. Make the headers pure Objective-C and pure C++, with pointers to a forward-declared struct containing the actual implementation. This is defined in the .mm file, and can then use Objec...
5,448,930
5,448,948
Issue with Default Arguments
In the Book C++ Primer by Stanley B. Lippman*,* Josée Lajoie in Chapter 14.2 of Class Constructors it states: Should we also provide support for specifying an opening balance but no client name? As it happens, the class specification disallows this explicitly. Our two-parameter constructor with a default second argume...
This isn't about constuctors, this is about default arguments. void f(int x, int y = 5) { //blah } when you call it providing less arguments, it uses the values of default arguments. E.g. f(3); //equivalent to f(3, 5); If one of the function parameters has a default value, then all successive parameters must have...
5,448,998
5,449,337
CUDA conditional thread synchronization
The CUDA programming guide states that __syncthreads() is allowed in conditional code but only if the conditional evaluates identically across the entire thread block, otherwise the code execution is likely to hang or produce unintended side effects. So if I need to synchronize threads with a conditional br...
If you need to go this route you could split the body into two phases: if (condition) { // code before sync } __syncthreads(); if (condition) // or remember a flag or whatever { // code after sync } Alternatively you could use the condition to set a flag that disables certain operations, for example if you're ...
5,449,198
5,449,204
Qt closing tray icon after application stops
I've a little problem with tray icon under windows. After my Qt application stopps (normal exit) the icon still remains in system bar. It disapears only when I move mouse cursor over it. I tried to hide it in the destructor of my window but it fails: I tried .setVisible(false). Any ideas? Thanks. P.S. I remember I had ...
I wouldn't hide it in the destructor. It will likely be an invalid reference at that point. I would put it in where your event for "Exit" happens.
5,449,234
5,458,104
google test EXPECT_EQ and boost::make_recursive_variant
I have a boost recursive variant as below. When I compare two recursive variant object using assert, it works fine but with EXPECT_EQ, it gives compile error. typedef boost::make_recursive_variant<bool, boost::uint8_t, boost::uint32_t, boost::int32_t, double, std::string, boost::uuids::uuid>::type rvariant_type; ...
gtest makes heavy use of streams for output but it seems that the boost::variant support for printing via an overloaded operator<< is very limited, if not nonexistant. Take a look at this: #include <boost/variant.hpp> #include <boost/cstdint.hpp> #include <boost/uuid/uuid.hpp> #include <iostream> typedef boost::make_re...
5,449,276
5,449,315
C++, fastest method of getting angle into a specified range?
what's the fastest way of getting a variable into a given range? For example, make sure that an angle "double alpha" is always within (0.0, 2*Pi). I found two solutions myself, one of them is much slower and the other looks way to complicated for such an easy task. There must be a better way, or not? //short, but very ...
Instead of implementing this by hand, I suggest you use the fmod() family of functions: http://linux.die.net/man/3/fmodf which does exactly this. You'll still need to take care of negative results yourself, though: alpha = fmod(alpha, 2.0 * M_PI); if (alpha < 0.0) alpha += 2.0 * M_PI; return alpha;
5,449,368
5,449,379
Is this a proper use of a temporary std::string?
std::string getMyString() { return <make a string>; } ... HANDLE something = OpenSomething(getMyString().c_str(), ...); I've read Guaranteed lifetime of temporary in C++ and I believe that the temporary string will live until the assignment has been evaluated, i.e. plenty long enough to make this work as expected. H...
Yes, this is fine. :-) The string will be destroyed at the end of the statement, at the semi colon.
5,449,404
5,449,449
What type for operations on pointers
I've searched quite a bit, but couldn't find anything helpful - but then I'm not sure I'm searching for the right thing. Is there any scalar defined by the standard that has to be at least as large as a pointer? I.e. sizeof(?) >= sizeof(void*). I need it because I'm writing a small garbage collector and want something ...
You could include <stdint.h> (or <cstdint>) and use uintptr_t or intptr_t. Since MSVC refuses to support C99, you may need to include <Windows.h> and use ULONG_PTR or LONG_PTR instead. (See C99 stdint.h header and MS Visual Studio) (Also, please use CHAR_BIT instead of 8.)
5,449,649
5,452,977
problem with Fmod wrapper (soundManager) for Ogre3d
I have a problem with Soundmanager (class) (wrapper) for fmod in ogre3d engine. Here is the code just in case : ISoundManager.h If somebody wants I will upload it but I can't upload more than 2 hyperlinks now. SoundManager.h http://codeviewer.org/view/code:18c9 SoundManager.cpp http://codeviewer.org/view/code:18ca I ...
I believe the SoundManager needs to get updated and this is done by frameStarted(). This means for your sound to start playing you have to start running your Ogre application using root->startRendering();. Have you tried that? The above code is either incomplete (in which case you really do have a problem) or you just ...
5,449,674
5,523,308
Read Excel sheet using ADO on Visual C++
We have an old application written using VC++ that uses ODBC driver to read the excel data. There are problems in current code with mixed data type and limitations of ODBC driver. SO I am planning to use Jet OLE DB driver and use ADO The code I have opens ADO connection and reads excel sheet.No issues here.. The bigges...
Three options spring to mind: Use Automation to open the spreadsheet in a hidden window. I.e. you can create an instance of the Excel application, hide the main window, and open the spreadsheet in that window. Use the ISAM driver instead of the JET driver. That may change the behaviour in undesirable ways though. Liv...
5,449,867
5,449,921
Class interaction tips
I am puzzled by some issues when trying to design interacting classes. If a class A needs some data from class B, either in the form of a pointer or standard container format, (or even lets become more ambitious and say in the form of some shared_ptr members to stl containers.), my way is to use a function that returns...
It rather depends on what A is, conceptually. If A can be validly viewed as a sequence of int, then I'd implement size_t size() const and int &operator[](size_t) (+ its const counterpart) on it. These can just delegate their activities to v.size and v[] or v.at. In B, you can then define static void B::print_contents(A...
5,449,946
5,450,035
OpenCV C++ and cvSmooth
Anyone know what could be problem: cvSmooth(origImage, grayImage1, CV_BLUR,3); I received error: error: cannot convert `cv::Mat' to `const CvArr*' for argument `1' to `void cvSmooth(const CvArr*, CvArr*, int, int, int, double, double)' If I use: cvtColor(origImage, grayImage, CV_BGR2GRAY); All worked fine. capturing i...
cv::Mat is a new structure from the C++ version of OpenCV. cvSmooth() is from the old C API. Do not mix the C interface with the C++! I'll suggest that you take a moment to read the introduction. Also, if you check opencv/modules/imgproc/src/smooth.cpp you'll see that cv::boxFilter() is the equivalent for cvSmooth(CV_B...
5,449,986
5,450,033
operator overloading c++ / where to put my code?
Today I overloaded the << operator in one of my classes: #ifndef TERMINALLOG_HH #define TERMINALLOG_HH using namespace std; class Terminallog { public: Terminallog(); Terminallog(int); virtual ~Terminallog(); template <class T> Terminallog &operator<<(const T &v); private: }; #endif As you c...
It is possible to keep implementation in cpp file, but you need to declare usage of your template for every type you are using it with. Please see Parashift C++ Faq for more detailed explanation. In your case, you have to write that line somewhere in your cpp file: template Terminallog &Terminallog::operator<<(const ch...
5,450,527
5,450,622
Confusion between boost::bind and boost::phoenix placeholders
The boost::spirit documentation has this important warning There are different ways to write semantic actions for Spirit.Qi: using plain functions, Boost.Bind, Boost.Lambda, or Phoenix. The latter three allow you to use special placeholders to control parameter placement (_1, _2, etc.). Each of those libraries h...
Did you maybe write a using namespace boost::spirit; somewhere at the top of that file? Because if yes, both the spirit as well as the bind placeholders are now in global namespace. The direct use of qi:: may support my assumption, but that might aswell be a simple namespace qi = boost::spirit::qi.
5,450,607
5,450,693
XML C++ library for simple messages
I need a XML library for constructing simple XML messages. I come from a Java background. I've found some suggestions pointing at Xerces-C++ XML library as it was transferred. Other suggested libraries have their advantages in memory in speed, but all of this is none of my needs. I need an API which supports an easy co...
A simple XML library would be TinyXML, see http://www.grinninglizard.com/tinyxmldocs/tutorial0.html for an example (under section 'Building Documents Programatically') edit: If the XML is really simple, you can also just output the XML tags from your code. Something like: std::stringstream s; s << "<tag>" << var << "</...
5,450,633
5,450,653
What does this mean? int foo = foo + 4;
#include <iostream> int main(int argc, char** args) { int foo = foo + 4; std::cout << foo << std::endl; } And a follow up question, is there a compiler flag to stop this sort of thing? I found -Wall works sometimes, better would be to prevent it entirely. My compiler: g++ -v Using built-in specs. Target: ...
No there is no guaranteed way to stop this sort of thing. It is an integral part of C++ and C that the variable's name is visible in its initializer. It allows you to do such things as T *t = malloc(sizeof(*t)); There is an issue report on the C++ issues list to require diagnostics in simple cases, but currently compi...
5,450,742
5,451,094
Is it possible in C++ to loop over all subclasses of an Abstract class?
I have an abstract class in C++ with several subclasses. Is it somehow by Macros or template metaprogramming possible to do something like that: foreach subclass of Base: mymap[subclass::SOME_CONSTANT] = new subclass();
No, you cannot. What you want, apparently, is a Factory (or perhaps Abstract Factory). In C++, you setup a Factory class and register builders. class FooFactory { public: typedef std::function<Foo*()> Builder; /// returns true if the registration succeeded, false otherwise bool Register(std::string const& key, B...
5,450,797
5,450,829
Outer class containing inner class - instantiate the inner class as a member of the outer class
Currently I am trying to get the following code to compile: terminallog.hh #ifndef TERMINALLOG_HH #define TERMINALLOG_HH #include <string> #include <sstream> #include <iostream> class Terminallog { public: Terminallog(); virtual ~Terminallog(); class Warn { public: Warn(); private: ...
Warn this->warn(); is not valid C++ syntax - if you want to initialize the warn member, use an initialization list (you don't need to in this case - the default constructor is called implicitly!). Terminallog::Terminallog() : warn() { // other constructor code } // note that `Warn::Warn()` is invoked implicitly on...
5,450,799
5,450,887
Encoding text file to appear on IBM Mainframe
I have a C++ program that sends data via FTP via ASCII mode to an IBM Mainframe. I am now doing this via C#. When it gets there and viewed the file looks like garbage. I cannot see anything in the C++ code that does anything special to encode the file into something like EPCDIC. When the C++ files are sent they are v...
It sounds like you should indeed be using an EBCDIC encoding, and then probably transferring the text in binary. I have an EBCDIC encoding class you can use, should you wish. Note that \015\012 is \r\n - they're characters 13 and 10 in decimal, just different ways of representing them. If you think the C++ code really ...
5,450,876
5,450,884
recursively check if number is a prime
I'm trying to check whether the number is a prime(by dividing it by all numbers below n). Here's my attempt : bool isPrime(int n, int d){ if (d == 1) return true; else{ if (n % d == 0){ return false; } else return (n,d-1); } } n - the number to check...
You aren't recursively calling your function. return (n,d-1); should be return isPrime(n,d-1);
5,450,928
5,451,910
How to set the environment in which python snippet can run in c++ program?
I have created two files embed.py useEmbed.cppin my home directory. embed.py import os print os.getcwd() useEmbed.cpp #include <iostream> #include "Python.h" using namespace std; int main() { Py_Initialize(); PyRun_SimpleFile("embed.py"); Py_Finalize(); return 0; } Command g+...
On linux, you can use python-config to get the compiler flags (python-config --cflags) and linker flags (python-config --ldflags). For example: #> python-config --cflags -I/usr/include/python2.5 -I/usr/include/python2.5 -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes #> python-config --ldfla...
5,450,943
5,451,294
Rotate Over Own Axis
I'm trying to build a car and I'm starting with a polygon. The physics of the car is pretty much done however the car isn't facing the right position when it's steering. So I tried using GLRotated with glRotated(_angle, 0, 0, 1); where _angle is the angle of the car in degrees but it's not rotating over it's own axis. ...
glRotate* rotate around the origin. You can translate back to the origin, rotate and translate out again but you'd probably be best just not adding _position for yourself: void Car::draw(){ Vector2d min = - _size/2.0; Vector2d max = + _size/2.0; glColor3d(0.8, 0, 0); glLoadIdentity(); glTranslated(_...
5,450,950
5,450,960
Help with C++ linker error
I've been struggling with a linker error that i cant seem to figure out, I'm implementing the bellman ford algorithm as a part of my homework. Here's the code i've written so far, it'd be great if someone could explain why i'm getting that error, I've pasted my code on mozilla pastebin, the two files are graph.h : http...
You didn't implement Vertex::Vertex() or Edge::Edge() - they're only declared. Implement them like this: class Vertex { private: char vertex_name; public: Vertex() {} ... class Edge { private: Vertex source,destination; int weight; public: Edge() {} ... You'll also get errors if you inclu...
5,451,096
5,451,154
Accessing c++ maps using a different class than the index
Suppose you have a class: class SomeClass{ public: int x; SomeClass(){ x = rand(); } bool operator<(const SomeClass& rhs) const{ return x < rhs.x; } }; And then you have this: map<SomeClass, string> yeah; Obviously this will work: yeah[SomeClass()] = "woot"; But i...
map's [] operator only takes the templated class as its parameter. What you want instead is some way of generating a specific instance of your class that has the values you want. In this example, add a constructor that lets you specify the value x should have. class SomeClass{ public: int x; SomeClass(){...
5,451,305
5,451,334
How to make function argument container independent
I'm writing a utility function which will take a vector of elements (could be string, int, double, char) and concatenate into a single string and return it. It looks like this: template<typename T> std::string convert2Str(std::vector<T> const& vec) { std::ostringstream sStream; for (size_t k=0; k<vec.size(); +...
Step 1, as you said, use iterators: template<typename T> std::string convert2Str(std::vector<T> const& vec) { typedef std::vector<T> container; std::ostringstream sStream; for (typename container::const_iterator it = vec.begin(); it != vec.end(); ++it) { sStream << *it << " "; } return sStream.s...
5,451,413
5,784,241
Using boost - put it in the source control or let any developer to install by himself?
Currently we use Boost in our SVN under a 3rd party directory. The problem is that updating the whole tree takes quite a lot, and I blame Boost's gazillion files (among other culprits). Alternatively, I can let any developer install it by himself, but then I must force them to install to the same location (which is qu...
I took Ralf's offer to use property sheet following is the complete solution. Note that this is VS2010 only. The vsprops file resides at my source control's 3rd_party_folder\boost. In the property sheet, two macros are defined - boost_include_path and boost_lib_path. Each of these macros uses the $(MSBuildThisFileDire...
5,451,430
5,451,688
How to create a TTF or OTF font programmatically [C / C++]
How do you go by creating a bitmap font with C or C++? I made some software that creates letterforms with your body and converts that to vector shapes (or bitmaps). I would like to output that result to a TTF, OTF or similar font file. You can see a video of the software here: http://vimeo.com/21396223
See the specs for OTF and TTF. Also, there's an open source app for creating fonts called FontForge, you can look at its implementation.
5,451,435
5,451,621
no match for call when using c++0x Lambda expressions
This is the problematic function: void Molecule::initSimilarity(int depth) { int m = 1; for (int j = 0; j < depth ; j++) for (int i = 0 ; i < _size ; i++) //for any atom A if (!getSetMask( //put all atoms which are equivalnt but not similar to A in their own ...
I see references in the argument type of the lambda, and no references in the functor types needed by getSetMask. Does your error persist if you make those consistent? i.e. if you want action to modify the Atom, you need std::function<void (Atom&)> action
5,451,447
5,467,108
Quadruple Precision in C++ (GCC)
Just recently, the GCC 4.6.0 came out along with libquadmath. Unfortunately, GNU has supported Fortran, but not C or C++ (all that is included is a .so). I have not found a way to use these new features in C++, however, GNU C does support the __float128 type for guaranteed quadruple-precision floats. GNU C does not ...
Apparently, this seems to have been an installation error on my part. While the core C/C++ portion of the GCC includes libquadmath.so, the Fortran version supplies libquadmath.a and quadmath.h, which can be included to access the functions. #include <quadmath.h> #include <iostream> int main() { char* y = new char[100...
5,451,489
5,451,556
C++ weird problem, Undefined reference
getting error: neljastest.cpp: undefined reference to Vector2::Vector2(float, float) neljastest.cpp: #include <cstdlib> #include <iostream> #include "../include/Vector2.h" #include "../include/neljas.h" using namespace std; int main (int argc, char* argv[]) { Vector2 p1 (1.0, 2.0); Vector2 p2 (0.0, 0.0)...
C/C++ are case sensitive for headers too. It seems that on vector2.cpp and neljastest.cpp you must change the include from: #include "../include/Vector2.h" To: #include "../include/vector2.h" I pasted all your sources on the same folder and successfully compiled them with: g++ neljastest.cpp vector2.cpp -o neljastest...
5,451,530
5,451,543
Unhandled Exception Error, Memory Violation
My program crashes as soon as a new MyString object is created. When the stringArray[0] is set to a null char in the constructor, I get a memory access violation. Any ideas? Here is the constructor MyString::MyString() { stringSize = 0; stringCap = 16; stringArray[stringCap + 1]; stringArray[0] = '\...
This line does not allocate memory: stringArray[stringCap + 1]; You need to replace it with: stringArray = new char[stringCap + 1]; Don't forget to delete the memory. Also Rule of 3 applies here as you have RAW memory owned by the object. Alternatively if you don;t want dynamic allocation but rather fixed size string...
5,451,676
5,451,696
How to add strings to a 2d array of char elements?
I have the below program written in C++: #include <iostream> using namespace std; int main() { int age[5]; char name[5][10]; age[0]=10; age[1]=20; age[2]=30; age[3]=25; age[4]=40; name[0]="abc"; name[1]="abc"; name[2]="abc"; name[3]="abc"; name[4]="abc"; cout<<n...
You are treating the name array as if it was defined thus: char *name[5]; So either define it that way, or use the following code to populate it: strcpy(name[0], "abc"); strcpy(name[1], "abc"); strcpy(name[2], "abc"); strcpy(name[3], "abc"); strcpy(name[4], "abc"); I prefer the former choice. The point being you are...
5,451,695
5,451,742
<bad ptr> Overloading + Operator
The debugger is giving me 'bad ptr' when I create a new string array in this constructor, but only when my overloading operator method creates a new MyString object... confused. Here is my constructor MyString::MyString() { stringSize = 0; stringCap = 16; stringArray = new char[stringCap + 1]; strin...
Since from your code snippet, nothing seems wrong, my sixth sense tells me that you've NOT written copy-constructor, and are working with the default one generated by the compiler, or possibly stringArray is not a null-terminated string! EDIT: In your copy-constructor, this is wrong: stringArray = s.stringArray; //wron...
5,451,748
5,452,034
How to include boost::filesystem into a VS2010 project without adding a dependency on bjam?
According to this answer, the intended way to include non-header-only parts of Boost into a Visual Studio 2010 project require the use of bjam to build the correct libraries. What is unclear to me is whether this is a one-time-only thing, where I just check in the lib files produced by bjam, or whether anyone who wants...
You don't need bjam. Like yasouser answered, you can download the installer from boost pro, the downsides being that you need to register though that's quick and easy it's usually/sometimes a release or two behind the latest boost release. What is unclear to me is whether this is a one-time-only thing, where I jus...
5,451,826
5,451,858
easy c++ loop with pause but output is very weird!
I'm just trying to write a program which outputs a series of numbers overwriting one another on the same line of the console screen. like 10 9 8 7 6 etc. I'm using xcode and compiling in xcode. And this outputs "10 121469 121468", what am I doing wrong? Why doesn't it seem so obvious? #include <iomanip> #include <iost...
I don't know if this answers your answer but I've seen that your CR is wrong. cout << '/r'; // CR is 2 characters (which is your 12146 printed on the screen). The correct value must be cout << '\r'; // CR
5,452,045
5,452,090
error C2664: 'strcmp' : cannot convert parameter 2 from 'char' to 'const char *'
I need help about that script. BOOL Checking(LPCSTR MacID) { char ClientMacs[18] = { "11:22:33:44:55:66",}; for(int x=0; x < 10; x++) { if(!strcmp(MacID, ClientMacs[x])) { printf(MacID," Successed!"); return true; } } return false; } I'm getting error C2664: ...
Not if(!strcmp(MacID, ClientMacs[x])) { } but if(!strcmp(MacID, &ClientMacs[x])) { ... } Arg 2 has to be a char *, but you have it as char. If your arg 2 were plain ClientMacs // compiler understands that this is shorthand for &ClientMacs[0] it would be fine. But when the index is other than zero, you have to...
5,452,188
5,452,298
switch/case statement in C++ with a QString type
I want to use switch-case in my program but the compiler gives me this error: switch expression of type 'QString' is illegal How can I use the switch statement with a QString? My code is as follows: bool isStopWord( QString word ) { bool flag = false ; switch( word ) { case "the": flag = true ; break ; case "...
How can I use the switch statement with a QString? You can't. In C++ language switch statement can only be used with integral or enum types. You can formally put an object of class type into a switch statement, but that simply means that the compiler will look for a user-defined conversion to convert it to integral o...
5,452,316
5,452,393
C#/C++ - Memory Leak
I have a C++ DLL (no source code / .pdb available for C++ DLL) in production. It is being called by a C# application using P/Invoke mechanism. Now, there is a leak in the C++ DLL. And, after executing for 20-22 times, the application crashes everytime. Now, how can I gracefully handle this such that I continue to use t...
In order to me, if it is absolutely impssible to modify / replace the c++ dll, and you are sure there is no problem in the PInvoke layer, the only option iif the performance remain acceptable, is to insulate the dll call in an executable communicating with the main one with some IPC ( Remoting for example ) so you can ...
5,452,479
5,455,217
Hide console in eclipse
It is posible to create a project with no console in Eclipse? Or can I hide it so it doesnt appear at all ? I tried ShowWindow(), FreeConsole() but the console still appears for a fraction of a second. I also tried using WinMain,still no change. I know that I can do it in VS2010 by creating a Windows Application(not co...
Eclipse has to be passing /SUBSYSTEM:CONSOLE to the linker, if using WinMain is still giving you a console. Look in the settings for an option to change the parameters it invokes cl with and change /SUBSYSTEM:CONSOLE to /SUBSYSTEM:WINDOWS.
5,452,773
5,452,835
Advantages/Disadvantages of Header Files
What are the advantages and disadvantages of using header files in a language like C or C++ verses a language like Java? I think classes should be designed from the outside in, so it is nice to have header files and not have to wade through implementation details. However, then again, each function declaration is dup...
Taken from a related blog post by Eric Lippert, who puts it very well: I would have asked the equivalent question why does C++ need header files? Header files seem like a huge potential point of failure; all the time I edit C++ code and change the signature of a method; if I forget to update the header fil...
5,452,839
5,452,849
include string, string doesn't name a type
I have included string and just after call a string variable in a struct in an header file. I get the 'string doesn't name a type' for string Origin and Destination City, despite calling string just before it //sortedListClass.h (a few lines of comments) #include <string> struct flightRec{ int flightnumber; str...
It's called std::string unless you put in a using directive (which you shouldn't do in a header).
5,452,840
5,452,864
Functions that do nothing and compiling with Level 4 warnings
Sometimes you have a class that is designed to be inherited, but not all its functions are expected to be used all the time. Therefore, to make for more readable and easier to maintain derived classes, the inheritable functions are defined, but are empty (instead of being pure virtual). An example from RakNet virtu...
Another way is to not name the parameters. That shows that the function has no intention to use them: virtual void OnDirectSocketReceive(const char* /*data*/, const BitSize_t /*bitsUsed*/, SystemAddress /*remoteSystemAddress*/) { }
5,453,015
5,453,050
C++ overloaded operator linked sorted list ADT
I have been trying to overload the equal (==) and less than (<) operators for a linked sorted list. I am not sure if I understand exactly if what I am doing makes sense. I have a struct with a string variable for DestinationCity, of which these operators have to compare. I have used strcmp in an attempt to make it work...
// I'm not sure if flightRec.DestionationCity is what I should write. You shouldn't:-). If you want to define operator< on some class you do not do this in container class, but in the class which objects you want to compare. Here it would be flightRec. bool flightRec::operator< (const flightRec& other) { // co...
5,453,071
5,453,074
XCode 4 only displaying cout statements with endl
I have a really weird issue with my cout statements. I've only tried this out with XCode 4. For instance, if I write, cout << "this works" << endl; cout << "this doesnt"; cout << memorySizeLimit << " blocks of memory available." << endl; I see all three output statements in my debugger console. However, if I change th...
std::cout is an stream and normally it is buffered for performance. If you print endl the stream gets flushed (cout << endl is the same as cout << "\n" << flush. You may flush the stream manually by cout << flush (or cout.flush()). So that should print: cout << "this doesn't" << flush;
5,453,170
5,453,262
Usage of union inside a class
I saw some code as follows: class A { private: union { B *rep; A *next; }; // no variables of this anonymous defined! void func() { A *p = new A; p->next = NULL; // why p has a member variable of 'next'? } }; I have compiled the above code with VS2010 without any ...
Because that's pretty much what an anonymous union does, it defines zero-or-more variables in the enclosing namespace (which in a class declaration makes them field names) which occupy overlapping memory. Hence in use it's the same as if you'd declared class A { private: B *rep; A *next; void func() {...
5,453,186
5,453,433
The size of char type on Intel 64 (EM64T) system
I heard somewhere about 16 bit long char type on some of 64 bit systems. What is the size of char type on Intel 64 (EM64T) system?
There are two 64-bit ABIs in common use on EM64T / AMD64 systems: The standard ABI used by Linux (and, as far as I'm aware, other Unix variants), which defines char as 8 bits (see section 3.1.2). The Windows x64 ABI, which also defines char as 8 bits (see Types and Storage -> Scalar Types). But the C standard does al...
5,453,361
5,453,413
c++ template specialization - linker error multiple definitions
My third question here today ;-), but I am really new to c++ template programming and operator overloading. I am trying the following: terminallog.hh //snipped code class Terminallog { public: Terminallog(); Terminallog(int); virtual ~Terminallog(); template <class T> Terminallog & operator<<(con...
This function Terminallog &Terminallog::operator<<(const char v[]) { std::cout << std::endl; this->indent(); std::cout << v; return *this; } is not a template, but a regular member function. If this .h file is included in several .cpp filtes, it will cause the multiple definition error you're seeing. I...
5,453,424
5,453,480
C++ how to overwrite a character in console, return carriage to start of line doesn't seem to work
My question is, how do I get the numbers 10 - 0 to print out on the same line, overwriting each other using either a WIN32 or GNUC compiler in a simple manner like my code below: This is what I have so far: #include <iomanip> #include <iostream> using namespace std; #ifdef __GNUC__ #include <unistd.h> #elif defined _W...
I did some really trivial modification (mostly just to clean it up and make it more readable): #include <iomanip> #include <iostream> using namespace std; #ifdef __GNUC__ #include <unistd.h> #define pause(n) sleep(n) #elif defined _WIN32 #include <cstdlib> #define pause(n) _sleep((n)*1000) #endif int main() { cout...
5,453,569
5,453,622
c++ primer 4th edition - String question
I'm reading page 86 in this book about string and literals and i don't understand why it says the following about string s1 and s2. string s1("hello, "); string s2("world\n"); string s3 = s1+s2; .. it says s1 and s2 included punctuation directly. Punctuation? What punctuation. Also on page 87. string s1 = "hello...
I actually went in and looked at the book in question. The author is considering the "," and the "\n" to be "punctuation." The very next sentence on page 86 said: The strings s1 and s2 included punctuation directly. We could achieve the same result by mixing string objects and string literals as follows: string s1("...
5,453,594
5,510,915
Resizing a double buffered widget?
Right now, my text widget is double buffered ( it draws the text to a bitmap when an event occurs) . This works great except when I resize the widget. When I resize, I al_destroy_bitmap and create a new one with the new dimensions This is very slow. How do most double buffered guis such as Windows and Mac OSX avoid thi...
I recently did double-buffering for the purpose of collision detection in Flash. It had a similar problem, creating bitmap data structures was relatively slow (this in itself is sad since allocating raw memory should be fast, for Flash and in your case). What I did was to simply cache the backing bitmaps and reuse them...
5,453,645
5,456,916
Change BSON field value (C++)
I'm testing BSON as a wire protocol, and I need to be able to change some values on a already created BSONObj... the problem is I can't find a way to do this other than recreating the BSONObj from scratch! Any tips?
I received a reply from Dwight Merriman, from 10gen: generaly they are immutable -- the common usage is to serialize/deserialize from a cpp object of your choice. See also $set and $inc but those are server-side. So... there we have it :)
5,453,864
5,453,870
Is this destructor declaration a typo in C++ Primer (Stanley Lippman)?
In - C++ Primer, Third Edition By Stanley B. Lippman, Josée Lajoie It says in: 15.1 Operator Overloading As we have seen in the examples in previous chapters, operator overloading allows the programmer to define versions of the predefined operators (as discussed in Chapter 4) for operands of class type. For example,...
Yes. Looks like a typo to me. Did you copy the code from an accompanying cd-rom or something?
5,453,950
5,454,003
C++ STL Comparison class: how to parameterize comp-class behaviour?
i want to use a std::priority_queue container with a custom data-type and several comparison-criterions (i defined a functor for each of them; each of them are working on the same types). The comparison criterion itself used should be configurable through a function parameter (avoiding if_then_ initializations of the q...
You are missing the definition of Compare's constructor: explicit Compare(const comp_type & comp) : comp(comp) { } Other than that, it builds and runs for me. Also, Compare appears to be redundant. It just wraps comp_type with an identical interface. The code still builds and runs after removing the Compare class and ...
5,453,980
5,454,000
Instantiating an object on the Heap
I receive the error: hashing.cpp: In function ‘int main(int, char**)’: hashing.cpp:96: error: expected type-specifier before ‘Linked_HashTable’ hashing.cpp:96: error: cannot convert ‘int*’ to ‘LinkedList_HashTable*’ in initialization hashing.cpp:96: error: expected ‘,’ or ‘;’ before ‘Linked_HashTable’ When compiling I...
Should LinkedList_HashTable *chain_div_hash = new Linked_HashTable(sizeDiv); be LinkedList_HashTable *chain_div_hash = new LinkedList_HashTable(sizeDiv); ? (Note the missing List in your code).
5,454,066
5,454,186
Getting error: no match for operator <<, when using operator ++ concurrently
I'm trying to overload many operators for a class assignment and need to get the << and ++ operators working together. Below is a sample of the code I'm dealing with. Let me know if you have any ideas. decaring generic template template (class T) class Vector { public: class VectIter { frie...
Your iterator operator++ returns a T rather than an iterator, so your iterator's operator<< isn't getting called. Most likely Mystring doesn't have an operator<< declared/defined OR Mystring's operator<< takes a non-const reference as its second parameter and can't accept the temporary returned from your operator++. ED...
5,454,081
5,454,436
Internationalization with MSWin resources (dialog/menu/strings)
I'm wondering what approach to i18n folks have found useful for windows items that are typically included in a native C++/WTL MSWin application via the resource compiler? I have some experience, albeit circa 2005, with the "traditional" approach to dealing with these things, roughly speaking: duplicate the resource fil...
Windows itself doesn't have any layout managers, but some UI libraries to use with Windows do. Just for one obvious example, Qt makes i18n quite a bit simpler than working with the Win32 API directly. It has managers for grid layout, flow layout, etc. It also has classes to directly support translation, including a QTr...
5,454,127
5,454,222
stl compliant container
I've been curious as to what entails an stl-compliant container (or boost-compliant, my understanding is that their either the same, or very similar). I've seen a few examples of what people call stl-compliant (for example, this one over at codeproject, and obviously the actual stl containers), but I'm not exactly sure...
Iterators: the standard library defines iterator categories. You want to supply iterators that model one of those categories. Depending on your viewpoint, the istream_iterator and ostream_iterator allow streams to be containers that don't supply bidirectional iterators. Basically, you use the allocator's allocate(n) t...
5,454,225
5,454,238
How do I express that I want to do something "if a function returns true/false"
I am making a dictionary program. Before adding a word to the dictionary, the AddWord function calls the SearchForWord function, if the search functions discovers that the word passed to it is already in the dictionary it returns true. In the add function I want it to move on to the part where it actually adds the wor...
You want; if(SearchForWord(word) == false) not if(SearchForWord(word) = false) As a point of style it would be better to go; if( !SearchForWord(word) ) Or maybe even better; bool word_found = SearchForWord(word); if( !word_found ) I find it really useful to introduce well named boolean variables like that, it enhan...
5,454,232
5,454,384
fstream::exceptions unexpected behaviour
In the code below; any idea why the ifs becomes bad when std::copy is performed? #include <iostream> #include <fstream> #include <algorithm> #include <iterator> int main(int argc, char* argv[]) { std::fstream ifs(argv[1], std::fstream::in | std::fstream::binary); std::fstream ofs(argv[2], std::fstream::out | s...
The (default constructed) end iterator you've given as the place to stop copying will only compare equal to the other iterator when attempting to read the specified data from the file fails. In this case, it's converted all the data in the file and reached EOF. That means everything has succeeded, but the stream is now...
5,454,370
5,454,385
Updating screen to render camera position
I have converted C++ source from using GLUT to using SDL/OpenGL The problem is since I have changed from GLUT the 'camera's position is not getting updated, so rather than moving around using the keyboard, the screen just sits there renders what it needs and does not update. The keyboard strokes are working as I have s...
CCamera() just creates a temporary camera. (Which you then move.) Then the temporary goes away. Perhaps you meant to modify Camera?
5,454,727
5,454,741
_beginthread In Parent Constructor
Given the situation: class A {}; class B : A; B b; If the default constructor for class A creates a thread using _beginthread, is it possible for that thread to have started executing before the constructor for class B has finished instantiating?
The thread will certainly have been created since the constructor of A is completely executed before the constructor of B begins execution. That thread may or may not have started, though: that would depend on how the threads are scheduled and what you do in the constructor after you create the thread. It certainly ...
5,455,211
5,456,176
Choosing between template instantiation with pointer arguments
Look at the following test code: template<class T> struct Wrap {}; template<typename T> inline void fun (T *&Int) // **choice 1** {} template<typename T> inline void fun (Wrap<T> *&Int) // **choice 2** {} int main() { int i = 6; fun((char*&)(i)); // **call 1** fun((Wrap<char>*&)(i)); // *...
While the code might look like a template specialization, that is not the case. The language does not allow for partial template function specializations. The two are unrelated templates that happen to be overloads. The compiler will lookup up the call to fun( (Wrap<char>*&) i ) with the usual lookup mechanisms, will f...
5,455,395
5,455,415
How do I know which STL string implementation I'm using?
Item 15 of Effective STL says that there are at least 6 different implementations of std::string. But if I have to be aware of which implementation I'm using, how do I find out which implementation I'm using? std::string of gcc does not show the source code (it's all in the .so file), so how do I find out? Couldn't fin...
Look at the <string> header and watch the copyright? I'll add that, from what I know, std::string is a typedef of basic_string<>, so of a template class. Now, from what I remember, only Comeau C++ supports "export" templates, so all other compilers need to have template classes defined AND implemented in header files. ...
5,455,926
5,456,609
Compiling and running a Qt program
I'm new to Qt, and trying to compile and run this Qt program I typed from the Programming with Qt book: #include <qapplication.h> #include <qlabel.h> int main(int argc, char *argv[]) { QApplication myapp(argc, argv); QLabel *mylabel = new QLabel("Hello",0); mylabel->resize(120,30); myapp.setMainWidget(mylabel); mylabel...
Qmake can generate some default project file like this: qmake -project qmake make First line generates project file, second generates makefile from the project file and make builds the project.
5,456,149
5,456,187
Input validation loop in C++ with strings
I'm just learning C++ (1 week of experience) and was trying to write an input validation loop that ask the user to enter "Yes" or "No". I figured it out but have a feeling there's a better way of approaching this. Here's what I came up with: { char temp[5]; // to store the input in a string int test; // to be...
I think you want a do while loop: bool test = false; do { cout << "Yes or No\n"; cin.getline(temp, 5); if (!(strcmp(temp, "Yes")) || !(strcmp(temp, "No"))) // checks the string if says Yes or No { cout << "Acceptable input"; // displays if string is indeed Yes or No test = true; } else ...
5,456,169
5,456,377
C++: Do I need to use cin.get() before I use cin.ignore?
Does cin.ignore(100,'\n') work if I just use standard cin through the stream? Example: cin >> temp; //enter key input if(cin.fail()) { cin.clear(); cin.ignore(100,'\n'); } or do I have to use cin.get()? Example: temp=cin.get(); if(cin.fail()) { cin.clear(); cin.ignore(100,'\n'); } Or will these codes produce...
Ah, stupid me, I made a function to call the clearing void clear() { cin.clear(); cin.ignore(100,'\n'); } and in my program, it called function clear() more than once. In the cases where clear() was called twice in a row without input from cin, it prompted for input in a blank line. I'm guessing this is what cause...
5,456,295
5,456,346
convert std::string to nsstring issue
Hi I use the following to convert std::string to NSString but it return (null) while trying to display the value of the nsstring I need it to return instead of (null) empty at conversion time any suggestion StudyDate=[NSString stringWithCString:studyDate length:strlen(studyDate)]; any suggestion to avoid null val...
Edit: The syntax @"string" is used only for constructing NSString. With std::string you should use the standard "string" syntax. NSString* aConstantNSString = @"foo"; const char* aConstantCString = "foo"; std::string aConstantStdString = "foo"; CFStringRef aConstantCFString = CFSTR("foo"); +stringWithCString:length:...
5,456,409
5,456,434
Calculate how many ones in bits and bits inverting
Possible Duplicate: How many 1s in an n-bit integer? Hello How to calculate how many ones in bits? 1100110 -> 4 101 -> 2 And second question: How to invert bits? 1100110 -> 0011001 101 -> 010 Thanks
You can loop while the number is non-zero, and increment a counter when the last bit is set. Or if you are working on Intel architecture, you can use the popcnt instruction in inline assembly. int count_bit_set(unsigned int x) { int count = 0; while (x != 0) { count += (x & 1); x = x >> 1; ...
5,456,453
5,469,151
Compatibility of classes with distinct owners
Given: class Foo1 { public: typedef Foo2 owner; }; class Foo2 { public: typedef Foo1 vassal; typedef Foo3 owner; }; //... and so on class FooN { public: typedef FooNm1 vassal; typedef ExternalType owner; // problem owner* owner(); }; Question: How to associate class hierarchy with external owner, pre...
I ended up with double dispatch. If I add virtual void apply(FooOwnerVisitor*) = 0; function to FooOwner and define FooOwnerVisitor interface nearby, then I can add any functionality for FooOwner derivatives without affecting FooN hierarchy and without dynamic_cast. So my problem actually wa two problems tha have own s...
5,456,801
5,456,816
C++ int float casting
Why is m always = 0? The x and y members of someClass are integers. float getSlope(someClass a, someClass b) { float m = (a.y - b.y) / (a.x - b.x); cout << " m = " << m << "\n"; return m; }
Integer division occurs, then the result, which is an integer, is assigned as a float. If the result is less than 1 then it ends up as 0. You'll want to cast the expressions to floats first before dividing, e.g. float m = static_cast<float>(a.y - b.y) / static_cast<float>(a.x - b.x);
5,456,863
5,456,947
C++ 2d vectors Issue inside a "for" loop
I understand there are issues when you try to change size of 2d vector objects but I'm facing a rather weird issue here. Code fragment is attached below : for (int iter = 0; iter < J; iter++) { cout << "iter " << iter << endl; rows_n = rows_n / 2; cols_n = cols_n / 2; ...
You have 2 varibales named sig2, one outside of the loop and one inside ! From your code : ///You clear a global sig2 sig2.clear(); ///You create a local sig2 ! vector<vector<double> > sig2(rows_n, vector<double>(cols_n,0.0));
5,456,907
5,457,878
Removing the border from an owner-drawn listbox
I've made an owner-drawn listbox by deriving CListBox, but I don't want it to have a border. Instead the border will be painted in the background of the parent dialog, so my listbox will look like it has a custom border. How can I remove the border? Is there a flag or a function to override in my derived class?
You need to remove the WS_BORDER window style.
5,457,388
5,457,432
memory leak xerces use
I have a leak in my application and I've come to reduce my code to the following and it's leaking about 12kb per iteration. I cannot see if this is a problem with my code or a problem with the xerces library itself. But looking at the Private Bytes in Perfmon I can only see growth and no shrinkage, so it's obviously ...
Where does impl get deleted? I know nothing more about the API than googling the docs, but they suggest to me that you should not be calling Terminate() - in a real program, other code elsewhere, possibly in other threads, may still be using the xerces library. The DOMImplementation is returned as a pointer and has a d...
5,457,423
5,457,510
template method overrides non-template method
I want to put any kind of Object (Object, Object etc.) into one shared_ptr. So I created base class and use shared_ptr. But, how can I declare T getMember(); within the base class so I can call ObjectBase.getMember? class ObjectBase { public: //virtual getMember HOWTO? }; template<typename T> class Object : public...
You can't. How should such a declaration look, that it can return all kinds of types? It's just not possible. You'd have to cast the ObjectBase* to the correct Object<T>* and then use the getMember function. It's only possible if all T share a common base class, so you could return a pointer to that. But that would put...
5,457,673
5,457,718
C++ pimpl idiom and static method and fields
I would like to better understand how to use static field an method in the presence of PIMPL idiom. Consider the following code. MyClass.h file: #ifndef MYCLASS #define MYCLASS class MyClass{ public: void method(); static void static_method(); private: Type field; static Type *static_fie...
Show us actual code that you've verified produces the same error Don't put static in front of the function definition in the .cpp file You don't have a static_field - you have two field
5,457,690
5,468,199
Boost timer stopped working, because of the British summer time
We changed time this weekend here in the UK. Since then my boost timer have stopped working on my PC. Here is what I should do if I want to run a 10 second timer: boost::asio::io_service service; boost::asio::deadline_timer timer(service); boost::posix_time::ptime time = boost::posix_time::microsec_clock::l...
The problem you're experiencing is caused by the default timer in asio, which uses boost.date_time's clock, which is a wall clock timer. It represents the actual time as your wall clock would show. If you look at the default time_traits used by the asio deadline_timer (boost/asio/time_traits.hpp) you'll see that its im...
5,457,806
5,457,856
Use typdefs of STL classes like map, list etc
In a current project I am programming C++, and I am using the STL classes map, set and list quite often. Now I am interested if there is a way to clean up some code by using the internal data types. For example: std::map<uint64_t, std::list<int32_t> > mymap; // add something to the map for (std::map<uint64_t, std::list...
typedef std::map<uint64_t, std::list<int32_t> > mymaptype; mymaptype mymap; for (mymaptype::const_iterator ...
5,457,837
5,458,035
OpenCV: reading image from std::in?
Is there some way of using OpenCV's imread function to read from std::in? Mat imread( const string& filename, int flags=1 ); Function accepts only filename, but is there some "magic" value for stdin?
OpenCV provides imdecode functions that work on buffers instead of filename. You would need to read stdin into a buffer first. http://opencv.willowgarage.com/documentation/cpp/reading_and_writing_images_and_video.html
5,457,858
5,457,928
error: size of array ‘u’ has non-integral type ‘double’|
i have the following code and i am receiving the error " size of array ‘u’ has non-integral type ‘double’|" #include <iostream> #include <cmath> #include <cstdio> #include <cstdlib> #include <fstream> #define steps 1000.0 #define time 1000.0 using namespace std; int main() { double u[steps][time]; double a; int ...
Concerning data[k].open("Data"data[k]".dat");. In C and C++, you can join string literals by writing "foo" XXX "bar", but this does not work with values that are not known until runtime. Instead, you have to use std::string and the + operator, for example: std::string filename = "Data"; filename += data[k]; filename +=...
5,457,955
5,459,493
How to safely store strings (i.e. password) in a C++ application?
I'm working on a wxWidgets GUI application that allows the user to upload files to an FTP server and a pair of username/password is required to access the FTP server. As far as I know, STL strings or even char* strings are visible to end user even the program is compiled already, using hex editors or maybe string extra...
This is actually independent of the programming language used. FTP is a protocol that transfers its password in plain text. No amount of obfuscation will change that, and an attacker can easily intercept the password as it is transmitted. And no amount of obfuscation, no matter the protocol used, will change the fact t...
5,458,044
5,458,089
Segmentation fault in small text processing program
I have a c++ function read_inputdata to read some inputfile and write the values to a an array. I first declare an array of appropriate length, and with the function I fill it with the values in the inputfile. But I get a segmentation fault. Anybody an idea what I did wrong? #define MAX 140160 void read_inputdata(doub...
Probably running out of stack. Please use pointers, dynamic allocations and even better, std::vector. #define MAX 140160 void read_inputdata(double *input, char *files); char inputfiles1[40] = "input/Hesse04/FR_Hes_rad.txt"; std::cout << "Declaring the arrays" << std::endl; double *input1 = new double[MAX]; std::cout ...
5,458,204
5,458,283
Unsigned int reverse iteration with for loops
I want the iterator variable in a for loop to reverse iterate to 0 as an unsigned int, and I cannot think of a similar comparison to i > -1, as you would do if it was a signed int. for (unsigned int i = 10; i <= 10; --i) { ... } But this seems very unclear, as it is relying on the numerical overflow of the unsigned i...
You can use for( unsigned int j = n; j-- > 0; ) { /*...*/ } It iterates from n-1 down to 0.
5,458,302
5,464,205
shared_ptr problems returning an up-cast version from a member function
I've recently been trying out shared_ptr and I've run across a bit of a weird case. What I want is a template member function which is capable of returning a shared_ptr of its derived type. I'm running visual studio 2010 which has access to some of the new c++0x standard, but I assume the boost shared_ptr behaves sim...
To expand on Stuart's answer and to (possibly) explain why you were crashing, my best guess is that you were calling getType on a stack-alloc'd instance. It's a major pitfall to using enable_shared_from_this. #include <memory> class Base : public std::enable_shared_from_this<Base> { public: virtual ~Base() {} ...
5,458,320
5,458,788
Specialized C++ template method never called
And another template specialization problem, which I can't resolve: terminallog.hh //stripped code class Terminallog { public: Terminallog(); Terminallog(int); virtual ~Terminallog(); template <class T> Terminallog & operator<<(const T &v); template <class T> Terminallog & operator<<(cons...
My bet is that conversion rules are applied here. Since there is no exact match for int [5] (which is the actual type of your array), your array will decay to int* and the overload with const T& will be chosen, since it will be a better match than const T v[] (which is treated as const T* v). See @sth 's answer for a ...
5,458,383
5,458,419
C++ Debugging "smell"
I was debugging an odd problem where an objects VMT suddenly seemed to point to the base object's methods. class Base { virtual void foo() {} } class Derived: public Base { void foo() {} } Derived * d = new Derived; ... much complex fettling ... d->foo(); // Help! called Base::foo()!!! It turned that a bug ...
Not sure what the question is – but I’d say that this: I was 'lucky' that the memory hadn't been trampled on... is wrong: you weren’t lucky – you were unlucky. Had the memory been trampled on during deletion, you would probably had the code crash much closer to the actual problem and the error would have been much cl...
5,458,552
5,458,564
Freeing a pointer from another function
Given the code: #include<iostream> using namespace std; class String { char *pstr; unsigned size; public: String(){ pstr=0;size=0;} String(const char *); void show(){ cout << pstr << endl ; } ~String () { cout << "In Dtor" << endl; delete [] pstr; }...
You should not invoke the destructor manually - it's invoked when s goes out of scope at the final '}' An assertion failure means that something called assert(somecondition) and somecondition was false. It's a technique used to validate your assumptions - if your code depends on some specific condition being true, and ...
5,458,659
5,459,017
error LNK2019 using VS2008 static lib with VS2005 in the same mode /MDd
I am using the FlashToDirectX.lib which generated with Visual Studio 2008, and my project is in Visual Studio 2005. My Project Options: /Od /I "e:\WORK\WORK\Project\MagicCamera\MixCenter\\..\Common" /I "C:\boost_1_45_0" /I "D:\lib\glog-0.3.1\src\windows" /I "E:\SDK\tinyxml" /I "E:\WORK\WORK\Project\MagicCamera\Incl...
I Converted the lib solution to VS2005 using the outstanding tool ProjectConverter. Problem solved.
5,458,906
5,459,032
How to use copy function in Vector?
I want to copy collection of structures from one vector to another vector in mfc. My Vector Structure is typedef vector<CLog *> CLogData; typedef vector<CLog * > tLogData; how to copy the TYPE CLog* from CLogData to tLogData? Regards, Karthik
If you want a shallow copy of the CLog* pointers, use the answer MacGucky gave. If you need a deep copy of the actual data the CLog* pointers point to, you need to do it manually in a loop: CLogData cl; tLogData tl; // fill cl for(size_t i = 0; i < cl.size(); ++i){ // invokes the copy ctor of CLog CLog* plog = new ...
5,459,048
5,459,072
turning off run-time check in visual studio 2008
I have an application developed in linux(fedora6-13) it uses MITK, ITK, VTK, QT3. I installed VS2008 and also MITK, ITK, VTK, QT3. When i run the application it works fine however after every action i make (clicking on button, changig state of a slider) i get the following error: Run-Time Check Failure #2 - Stack arou...
That runtime check tells you that you have a bug - don't turn off the check, fix the bug. If you want to have random behavior, aka not fix the bug, then you can disable the check in project properties: C++/Code Generation/Basic Runtime Checks. Be aware that this will lead to all sorts of weird problems - you won't be ...
5,459,306
5,459,340
std::map::iterator references non-existing object?
Considering the following code: class MyClass { public: int someInt; MyClass() : someInt(666) { } }; int main() { std::map<int,MyClass> myMap; std::map<int,MyClass>::iterator it = myMap.end(); const MyClass& ref = it->second; std::cout << ref.someInt << std::endl; } Since the map i...
what Object does it->second reference? Is this an invalid reference because it = myMap.end()? Indeed. myMap.end() is a valid iterator but it must not be dereferenced. it->second attempts to do exactly that and causes undefined behaviour. map<int,MyClass> does not create an instance of MyClass. True, but irrelevant....
5,459,526
5,478,086
How to find caller assembly name in unmanaged c++ dll
I have an unmanaged c++ dll. I am calling external methods of this unmanaged dll from c# (.net 3.5) I am looking for a way to find witch c# assembly is calling my unmanaged c++ dll (into my c++ dll) (at least, name of assembly) And sure, I don't want to pass any additional parameter to methods. Thanks in advance
Finally I found the solution. I was looking for a way to restrict not allowed access to my unmanaged dll. So I crawled the stack trace for my caller assembly location. Finally I decided to check public key token of caller assembly (found this way) and validate it. Thanks from you time and answers...
5,459,602
5,460,438
How to center widget inside QStackedLayout?
I have a QProgressBar that I need to be centered inside QStackedLayout. How can I achieve it, given that QStackedLayout::setAlignment doesn't have any effect, and the widget is always in the top-left?
Place the QProgressBar in a container (i.e. QWidget) that allows it to be centered with an additional layout.
5,459,678
5,459,761
passing integer array in thread function
I am working on multiple producer and Single consumer problem.I wanted to pass Thread like 1,2,3 in the thread function so that individual thread can be named based on these number. But the program is crashing after count 7 while creating thread.I think problem is due to variable nThreadNo; if i limit the count less t...
You are zeroing out the first 20 bytes of nThreadNo, not the first 20 * sizeof(int) bytes as you should be doing. There are other arrays you are indexing into in this code: hWndProducer, dwProducerThreadID. Are there enough elements in those as well?
5,459,759
6,059,134
Full-expression boundaries and lifetime of temporaries
Possible Duplicate: C++: Life span of temporary arguments? It is said that temporary variables are destroyed as the last step in evaluating the full-expression, e.g. bar( foo().c_str() ); temporary pointer lives until bar returns, but what for the baz( bar( foo().c_str() ) ); is it still lives until bar returns, o...
Temporaries live until the end of the full expression in which they are created. A "full expression" is an expression that's not a sub-expression of another expression. In baz(bar(...));, bar(...) is a subexpression of baz(...), while baz(...) is not a subexpression of anything. Therefore, baz(...) is the full expressi...
5,460,118
5,460,196
boost::variant usage
I am developing GUI application via wxWidgets. It has 2 parts: GUI part and "Logic" part. I want to have Logic part totally independent on wxWidgets. But one component in the GUI returning wxVariant and I need to use it in the Logic part. So I am looking for a way to "convert" wxVariant to boost::variant wxVariant work...
Simple answer? No. You cannot convert via strings, this induces a loss of information and boost::variant does not automatically attempt to parse strings. I don’t know whether wxVariant offers an explicit conversion – in general, it may be difficult to convert to boost::variant without testing for special cases.