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
6,855,943
6,856,319
Problem with binary ==
I've run into strange problem with binary operator==. I have a function which returns: Type< Colors >* get();, T is of type enum Colors {Red,Black} and I have an operator== defined as: bool operator==(Type<Colors>* left, Colors right) { //... } Now, in code I have line: if (get() == Red) { // } but here I'm getti...
(This is more diagnostic than an answer per se... but too much for a comment.) Works ok for me with GGC 4.5.2: enum Colour { Red, Black }; template <typename T> struct Type { }; bool operator==(Type<Colour>*, Colour) { return true; } int main() { Type<Colour>* p; return p == Black; } Please try the above on...
6,856,141
6,858,846
Display XP Style CFileDialog in Windows 7
I want to display CFileDialog like the image below in Windows 7. As per msdn if OFN_ENABLETEMPLATE is set and OFN_EXPLORER flag is not set, the system uses the template to create an old-style dialog box that replaces the default dialog box. But even after doing that what I get is something like this. Please help!
Try this: CFileDialog fd(1,0,0,0,0,0,0,FALSE); fd.m_ofn.lStructSize = sizeof(OPENFILENAME_NT4); fd.DoModal(); The last parameter to CTOR specifies Vista-style to be false, and structure size of sizeofed with to reflect NT4 file-dialog.
6,856,347
6,856,393
C++ basic exception question
Could someone please describe what's the correct way to handle the following situation: wchar_t* buffer = new wchar_t[...]; if (!something) { throw std::runtime_error("Whatever"); // Now, at this point I'm leaking memory allocated for the 'buffer'. } // Perform actions. delete[] buffer; The obvious way to so...
Your insight is right. The pattern Acquire some resource Do something Release resource is fundamentally wrong, since Do something can potentially throw an exception and leak the resource. Moreover, you have to remember to release the resource, which is a fertile source of errors. The correct way, as you point, is to a...
6,856,436
6,856,748
error at tinyxml when deserialize
I have the following xml: <Name /> <Sur> mmm </Sur> When I deserialize I wrote: TiXmlElement* section; section=handle.FirstChild("Name").ToElement() if (section) {} The problem is that the if condition is runned though field Name is null. WHY? Where am I wrong? Appreciate. THX
Maybe you should define a root element of your XML code, like <Person>: <Person> <Name /> <Sur> mmm <Sur /> </Person>
6,856,488
6,856,784
Destructors and inheritance in C++?
I use Borland C++ Builder. And i had o problem #include <Classes.hpp> class TMyObject : public TObject { __fastcall TMyObject(); __fastcall ~TMyObject();//I would like to inherite my destructor from TObject }; __fastcall TMyObject::TMyObject() : TObject()//it will inherited my constructor from TObject { } And ...
This can be solved at TObject's level. Its destructor has to be virtual: #include <Classes.hpp> class TObject { __fastcall TObject(); virtual __fastcall ~TObject(); }; This way you can either do: TObject * pobj = new TMyObject(); delete pobj; or TMyObject * pobj = new TMyObject(); delete pobj; Both destructo...
6,856,750
6,856,804
What is the purpose of pure virtual destructor?
Possible Duplicates: Under what circumstances is it advantageous to give an implementation of a pure virtual function? Why do we need a pure virtual destructor in C++? Compiler doesn't force the Child class to implement a destructor when its Base has pure virtual destructor. struct Base { virtual void foo () = 0; ...
Sometimes an abstract base class has no virtual methods (= often called a “mixin”) or no methods at all (= often called a “type tag”). To force those classes to be used as abstract base classes, at least one method needs to be pure virtual – but the classes don’t have virtual methods! So we make the destructor pure vir...
6,856,873
6,857,385
covariant return types with multiple inheritance. how does this code work?
Can anyone tell me how does return type covariance work in the following code? class X { public: int x; }; class Y: public OtherClass, public X { }; static Y inst; class A { public: virtual X* out() = 0; }; class B : public A { public: virtual Y* out() { return &inst; } }; void...
By "how does it work", I presume you're asking about what the generated code looks like. (In a typical implementation, of course. We all know that the generated code can vary somewhat between implementations.) I'm aware of two possible implementations: The compiler always generates code to return a pointer to the ba...
6,856,913
6,856,998
A point from iso C++ n3290 : Argument dependant Name Lookup:
A point from iso C++ n3290 :Argument dependant Name Lookup: section 3.4.2, para 4 When considering an associated namespace, the lookup is the same as the lookup performed when the associated namespace is used as a qualifier (3.4.3.2) except that: — Any using-directives in the associated namespace are ignored. — Any ...
I think the lookup should have always worked like that and is more of a clarification than actual change. I am not sure whether it was added because some other wording was added elsewhere that requires to make this clearer, compilers actually differed in some corner cases or some body questioned what is correct impleme...
6,857,222
6,867,527
Sampling data from a shadow map texture using automatic comparison via the texture2D function
I've got a sampler2DShadow in my shader and I want to use it to implement shadow mapping. My shadow texture has the good initializers, with GL_TEXTURE_COMPARE_MODE set to GL_COMPARE_R_TO_TEXTURE and GL_TEXTURE_COMPARE_FUNC set to GL_LEQUAL (meaning that the comparison should return 1 if the r value of my coordinates ar...
You don't say how you generated your depth values. So I'll assume you generated your depth values by rendering triangles using normal projection. That is, you transform the geometry to camera space, transform it to projection space, and let the rasterization pipeline handle things from there as normal. In order to make...
6,857,303
6,857,843
exploiting poppler in Qt creator - help
I am trying to compile a Qt project that uses poppler library for pdf (linux). I put #include in the mainwindow.cpp I put poppler folder in my project folder besides mainwindow.cpp poppler-qt4.h is in poppler-0.16.7/qt4/src I do not need to recompile poppler, I just need to link the library through its headers but I d...
You have a good example, completed with source code, here: Poppler: Displaying PDF files with Qt Along with including the header files where apropriate, you need to link to the poppler library. To do so, you need to edit your .pro file and include something like: INCLUDEPATH += /usr/include/poppler/qt4 LIBS +=...
6,858,215
6,858,249
Will a statically compiled library (.lib) in Visual Studio be linkable into an iOS app?
From this question it appears it's possible (but perhaps with issues). My question is, can I do this the other way aorund, compile a C/C++ lib in Visual Studio then link it up to xcode and run it on an iOS device. Will Apple have an issue with this if it actually works? I know they're not big fans of DLLs and I'm not t...
You can't do this because the Microsoft compiler targets a different architecture from the architectures that iOS runs on. And that's just for starters. There are no doubt a gazillion other reasons that it won't work, but the architecture is the most obvious block.
6,858,247
6,858,294
Should ALL global variables be volatile-qualified?
In this example, does correctness require global_value to be declared volatile? int global_value = 0; void foo () { ++ global_value; } void bar () { some_function (++global_value); foo (); some_function (++global_value); } My understanding is that volatile is "intended" for pointers to mapped memory ...
No, the volatile keyword is not necessary here. Since global_value is visible outside the function bar, the compiler must not assume that it remains the same if another function is called. [Update 2011-07-28] I found a nice citation that proves it all. It's in ISO C99, 5.1.2.3p2, which I am too lazy to copy here in its...
6,858,371
6,858,435
Visual Studio preprocessor only works if /P is set
I'm having an awkward problem in Visual Studio 2008. I'm trying to define a string-to-enum mapping using a config header (call it param_defines.h) file which looks something like this: DEFINE_ITEM( A, BOOLEAN ) DEFINE_ITEM( B, INT ) DEFINE_ITEM( C, INT ) And so on. This is then referenced in a second header (enums.h) ...
No, it doesn't compile at all. /P suppresses the compilation (the file is only preprocessed, at which point there is no syntax checking), just like /c suppresses the linking. Since you didn't show us what the output actually looks like, I'm going to be guessing: you're missing semicolon at the end of #define DEFINE_ITE...
6,858,446
6,858,601
Add gui to c++ project (visual studio 2010)
I created a c++ project, and now I want to add a Graphical Interface to it. When I click on Project-->Add New Item, and choose to add Windows Form, it creates a header and source file but with a lot of errors such as: (problems with "public, privte, this - 'this' may only be used unside a nonstatic member functio...
There are 2 types of native C++ ways of making a gui (using the win32 api); MFC, and straight API. MFC has a lot of pre-made components and classes - what you did (adding a form to a regular project) didn't work since the project wasn't set up for MFC. When you create a new win32 project (not mfc or console) - the meth...
6,858,524
6,858,585
Convert char * to LPWSTR
I am trying to convert a program for multibyte character to Unicode. I have gone through the program and preceded the string literals with L so they look like L"string". This has worked but I am now left with a C style string that won't conform. I have tried the L and putting it in TEXT() but the L gets added to the va...
The std::mbstowcs function is what you are looking for: char text[] = "something"; wchar_t wtext[20]; mbstowcs(wtext, text, strlen(text)+1);//Plus null LPWSTR ptr = wtext; for strings, string text = "something"; wchar_t wtext[20]; mbstowcs(wtext, text.c_str(), text.length());//includes null LPWSTR ptr = wtext;...
6,858,546
6,858,616
Error control in constructors
There is such class: class Circle{ int x; int y; int radius; public: Circle(int x_, int y_, int radius_){ x = x_; y = y_; if(radius < 0) signal error; radius = radius_; } }; It is not possible to create circle with radius less than zero. What is a good method to signal error in construc...
A good method is not to allow the error to compile! Unfortunately, merely using unsigned will not prevent a negative value from being passed to the constructor – it will just be converted implicitly to an unsigned value, thus hiding the error (as Alf pointed out in a comment). The “proper” solution would be to write a ...
6,858,575
6,858,632
how to set a text in line edit Qt Creator?
I am working in c++ Qt Creator. I have a form with labels and lineEdits. I would like to set as default in each lineEdit a text. It would be more efficient than writing the same stuff each time I run the application. Can you please tell me how to do this?
Use void setText( const QString & ) You can set it in the constructor or maybe set all those defaults in an init() function.
6,858,887
6,858,968
how to over come the issue of object slicing in c++
How should I get rid of the problem with object slicing in c++. In my application if the derived class has some dynamically allocated pointer and derived class object is assigned to base class object, the behavior is memory corruption!
It depends on your design. You may have to change certain design criteria to get rid of it. One of the options is to have an overloaded operator = and copy constructor in your base class for particular derived class. class Derived; class Base { //... private: Base (const Derived&); Base& operator = (const Derived&)...
6,858,942
6,859,022
C++ string uses maximum buffer allocated?
I declare a variable string s; and do s = "abc"; now it has buffer of 3 characters. After s = "abcd" it has a buffer of 4 characters. Now after the third statement s = "ab" question is will it keep the buffer of 4 characters or will it reallocate a 2 character buffer? If it will allocate 2 character buffer is there...
s = "ab" question is will it keep buffer of 4 words or will it reallocate 2 word buffer ? It will not reallocate the buffer. I don't know if it's mentioned in the standard, but all the implementations I have ever seen issue a reallocation only if they need to increase the capacity. Never to decrease. Even if you ha...
6,859,130
6,859,152
How can I run make command by using specific gcc compiler?
I have to run make command using specific version gcc compiler (using gcc-4.1 because after that versions will give deprecated method warnings or errors).. Now, there are several versions of gcc installed in the server. Can anybody help, how can I run it (make command) to a specific version gcc compiler (means on gcc-4...
You can do: CC=gcc-4.1 make That will fill the $(CC) variable of your make. Also, you can write: make CC=gcc-4.1
6,859,201
6,860,649
Subclass specific access in Factory pattern
I have a design based question where I want to avoid dynamic_cast but still want to know how to get to loose coupling. class Prod { // Prod has lot of subclasses public: void method() {//Some Implementation } }; class Prod_X : Prod { int special_variable; public: ...
In an ideal design, publicly inherited classes have an "is a" relation and not an "is an extension of" relation in the sense that they may be extended but you don't notice it from the interface point of view. This is best achieved if you actually order objects to do something and you don't get/set them. In that case ...
6,859,267
6,864,946
valgrind unhandled instruction bytes: 0xF 0xB 0xFF 0x85
I tried to run my program compiled with Apple GCC 3.2.1 (forced 32-bit mode, x86 only) under valgrind 3.6.1, but I get the following error during initialization phase: vex x86->IR: unhandled instruction bytes: 0xF 0xB 0xFF 0x85 ==80746== valgrind: Unrecognised instruction at address 0x2a6c2a9. ==80746== Your program ju...
The byte sequence 0xF 0xB is the opcode UD2. This is a defined "Undefined Instruction", if that makes any sense: there are many possible opcodes that are not legal, but this one is specifically reserved as an instruction which is guaranteed to raise a #UD invalid opcode exception, even on future processors. There is on...
6,859,317
6,859,456
User defined messages
Here is the code: //h file class MyClass: public CView { public: afx_msg LRESULT OnMyMess(WPARAM, LPARAM); } //cpp file BEGIN_MESSAGE_MAP(MyClass, CView) ON_MESSAGE(WM_USER+100, OnMyMess) END_MESSAGE_MAP() LRESULT OnMyMess(WPARAM, LPARAM) {return 0}; //Somewhere in the programm SendMessage(WM_USER+100, 0 ,0...
First, LRESULT OnMyMess(WPARAM, LPARAM) {return 0;} should be LRESULT MyClass::OnMyMess(WPARAM, LPARAM) {return 0;} but I guess it's just a typo. Second, SendMessage should work as expected, only if it's in the MyClass that you're calling it; otherwise, you should specify the window to which you want to send the m...
6,859,631
6,859,682
C++ embedded python PyArg_ParseTuple fails with string args
I'm trying to add embedded python to a OpenGL/SDL application. So far everything works fine, like entering a string via SDL keyboard events and executing it with the embedded python interpreter. I'm now into adding functions to call C/C++ functions like void set_iterations(int c); is invoked on the python interpreter ...
Try: static PyObject* test_addignore(PyObject *self, PyObject *args) { char* ignorestring; if (!PyArg_ParseTuple(args,"s", &ignorestring)) //Note the & return NULL; //Never ignore errors add_global_ignore(ignorestring); Py_RETURN_NONE; //Always use helper macros ...
6,859,759
6,871,892
c++ cygwin and eclipse - binary not found error
I've spent hours looking up how to fix this problem but nothing has worked. I have eclipse Indigo with CDT and ive downloaded cygwin and packages such as g++, make file, etc. When I try to execute any code I end up with the error Launch failed. Binary not found. I've also set the system path C:\cygwin\bin. How can I se...
Found the problem, I didn't press the hammer button to build the project first. I've only used eclipse for java and I could just hit run and everything would work fine.
6,859,915
6,860,113
Mysterious behavior of unordered_map in Visual Studio
I want to store ~3,000,000 double values at unsigned int indices under VS2010 C++. I use a std::tr1:unordered_map<unsigned int, double> for this purpose. Unfortunately, when I try to store value number 2^21, an exception is thrown (as if there is only space for 2^21-1 , i.e., some index can only use 20 Bits). I tried t...
The following bug on Connect appears to be related to your problem: Visual C++: std::unordered_map Destructor Performance in Debug Configuration The same problem occurs not just in the destructor, but also when the unordered_map is resized. It seems to have something to with invalidating iterators if iterator debugging...
6,859,934
6,860,100
Override standard function which is friend of class
There is such class: #include <iostream> #include <cmath> class Element { private: int val; public: Element(int val_){ val = val_;} friend Element std::pow(Element a, int exp); }; I'd like to override standard function pow, which is friend of class Element, to work with objects of my class. However, there is fo...
First of all, you don't override, you overload. The term override relates to virtual functions, and overload to choosing the right function basing on parameter types. The solution is simple: don't write std::pow, just write a pow. Or yournamespace::pow, if you prefer - doesn't matter. Yes, it's just that. Then: double ...
6,860,429
6,877,962
Access violation when calling some MFC default constructors
I am attempting to ask this question again due to my failure to state the question clearly yesterday. Basically, I have an access violation error described in the comment in the code below... any idea why? Class A { private: BOOL a; BOOL b; int i; public: A() {a = FALSE; b = FALSE; i = 0;} .... } Cla...
I've found the solution to my problem. The cause of the problem is that Class A is built to a dll with a different struct alignment than class B and C.
6,860,525
6,860,557
C++: What is faster - lookup in hashmap or switch statement?
I have a code pattern which translates one integer to another. Just like this: int t(int value) { switch (value) { case 1: return const_1; case 3: return const_2; case 4: return const_3; case 8: return const_4; default: return 0; } } It has about 50 entries currently, ma...
A switch construct is faster (or at least not slower). That's mostly because a switch construct gives static data to the compiler, while a runtime structure like a hash map doesn't. When possible compilers should compile switch constructs into array of code pointers: each item of the array (indexed by your indexes) poi...
6,860,877
6,861,277
how to remove substring from string c++
I have a string s="home/dir/folder/name" I want to split s in s1="home/dir/folder" and s2="name"; I did: char *token = strtok( const_cast<char*>(s.c_str() ), "/" ); std::string name; std::vector<int> values; while ( token != NULL ) { name=token; token = strtok( NULL, "/" ); } now s1=name. What about s2?
Several points: first, your use of strtok is undefined behavior; in the case of g++, it could even lead to some very strange behavior. You cannot modify the contents of an std::string behind the strings back and expect to get away with it. (The necessity of a const_cast should have tipped you off.) Secondly, if you'r...
6,861,046
6,897,479
compiler support for stateful allocators in STL containers
The new C++11 standard requires STL implementations to support stateful allocators in containers. Do main STL implementations (Visual Studio 2008, 2010, libstdc++) comply to this requirement now? I found nothing about this in MSDN or in libstdc++ documentation.
Looks like the feature of stateful allocators in STL containers is widely supported already. In most cases statefullness of the allocator does not cause trouble. What is not widely supported yet is the new standard's way of handling the problematic situations (swap of a container(whether to swap the allocator too), spl...
6,861,060
6,861,118
Abusing cin in while loops for int assignment
simply trying to compare two user defined vectors to see if they are equal, current code: vector<int> ivec1, ivec2; //vectors, uninitialized int temp1; cout << "Enter integers to be stored in ivec1." << endl; while(cin >> temp1) //takes input from user and creates new element in the vector to store it { ivec1.pu...
You would have to do cin.clear() to reset the stream state. Then you will have to make sure that the offending character is read from the stream (using one of the techniques described here), so that the next input operation does not fail as well.
6,861,089
6,861,195
How to split a vector into n "almost equal" parts
I have a problem that I would like to merge a large number of images using ImageMagick's convert.exe, but under Windows I have a 8192 byte long command line limit. My solution to this is to split the task into smaller sub-task, run them, and do a final task which combines them together. My idea is to write a function...
To get a base number for the size of each part, simply divide the total by the number of parts: 11/3 = 3. Obviously some of the parts will need to be bigger than that to get the proper total, but that's just the remainder: 11 % 3 = 2. So now you know that 2 of the parts will be size 3+1, and whatever's left over will b...
6,861,331
6,861,395
What's an AoB (Array of Bytes)
I have encountered this term a couple of times now, and I have googled for explanations, but couldn't find any. I'm accessing the memory of a running software-game. I do have an address but I'm also given an AoB, for example 89 8B ? ? 00 00 8B 50 ? 89 93 ? ?. What do I do with it? I'd appreciate it if you could giv...
An array of bytes is best explained in C/++ as an array of [unsigned] char. The values you see are only hexadecimal representations of these bytes or unsigned char's.
6,861,612
6,861,723
Multiple inheritance of virtual classes
Suppose I have the following code: class a { public: virtual void do_a() = 0; } class b { public: virtual void do_b() = 0; } class c: public a, public b { public: virtual void do_a() {}; virtual void do_b() {}; } a *foo = new c(); b *bar = new c(); Will foo->do_a() and bar->do_b() work? What's the m...
Why shouldn't they? The memory layout will typically be something like: +----------+ | A part | +----------+ | B part | +----------+ | C part | +----------+ If you convert your foo and bar to void* and display them, you'll get different addresses, but the compiler knows this, and will arrange for the this point...
6,861,722
6,865,628
Automatically populate "Edit" menu in menubar with current focus widget context menu
I've been looking for ways to implement the "Edit" menu of Qt application. The "Edit" menu contains items such as "Copy", "Cut", "Paste", etc. and which need to forward to the currently active widget. I can't seem to find a standard or elegant way to do this. According to this question, it's not possible: How to implem...
well, if you just need to create menu, you can always take actions from actions of a widget. To create edit actions for widgets, you can do something like this: void MainWindow::addActions (QWidget* widget) { QAction * copyAction = new QAction("copy",widget); if(connect(copyAction,SIGNAL(triggered()),widget,SL...
6,861,762
6,862,000
Simulating Thread with fork()
What's your idea about simulating thread with "fork() function" and a "shared memory" block ... Is it possible ? How much is it reasonable to do this for a program ? ( I mean , Will it work well..?)
Yes, it is possible, but I cannot imagine it being a good idea, and it would be a real pain to test. If you have a shared heap, and you make sure all semaphores etc. are allocated in the heap, and not the stack, then there's no inherent reason you couldn't do something like it. There would be some tricky differences th...
6,861,776
6,861,920
Why is zero-length array allowed only if it's heap allocated?
I notice that it's not allowed to create non-heap allocated arrays of zero length. // error: cannot allocate an array of constant length zero char a[0]; I also notice that it's allowed to create heap allocated arrays of zero length. // this is okay though char *pa = new char[0]; I guess they're both guaranteed by the...
A 0 length array isn't very useful. When you're calculating the dimension, it can occur, and it is useful to not have to treat the case specially in your code. Outside of new, the dimension of the array must be a constant, not a calculated value, and if you know that the constant is 0, why define it? At least, that's...
6,861,780
6,861,946
C++ Error: does not have a class type
I am having a bit of trouble with C++ classes. I am writing a class (cSpline) to do a cubic spline fit on a set of input points. I want to use a cSpline object within another class (ss304, which provides properties of type 304 stainless steel as a function of temperature). I have four files. Here is the code I have ...
You can't initialize a data member in the constructor by calling the data member's constructor. You will need an assignment or initialization method for the object: SS304::SS304() { static const double alpha1[Na1] = {13.6e-6, 16.1e-6, 17.15e-6, 17.8e-6, 18.65e-6, 19.2e-06, ...
6,861,909
6,862,040
popen vs system: is popen as evil as system?
popen buffers output while system does not. is that the only difference? I understand that popen and system both run the command through the shell. However, is popen() as evil as system()?
Look, the whole thing about "system being evil" is, at heart, people who don't think about the security consequences of their particular use case. The only reason system is "more evil" than doing your own fork/dup/exec is that used badly, it's possible for someone to introduce a malicious command line. So, for exampl...
6,861,961
6,862,046
Creating a COM dll in visual basic 2008 and using it in a C++ project
I followed this tuorial to create a COM dll in Visual Basic. http://www.codeproject.com/KB/COM/Basics_of_Idl_file.aspx I now want to use this dll in a C++ project. I used OLE/COM Viewer to create an .idl file as is described in the second half this tutorial. http://www.codeproject.com/KB/COM/vb_from_vc.aspx I compiled ...
If you did not get to the last part of creating a Type Library, that is important. You then need an #import statement in your C++ code to use the .tlb file (or .dll if the type library is embedded in the dll, which is common). #import is the equivalent to including a header file with COM, but generates a .tlh file (hea...
6,862,026
6,862,097
Create a simple GUI for c++ project
I created a project in c++ that run for hours. I want to make a simple GUI (For Windows) that will let the user to choose between some inputs,and click on "start". and then, show him a progress bar which represent the percent of the computation that has been done. (and probably a small animation). What is the best way...
What is the best way to do this? I never made a Graphical interface before. The easiest way is to use the Visual Studio 2010 IDE and create a new WinForms Application templated project. I try to use Visual Studio 2010: In new Project I choose Win32 Project, and I found where i change the menu, but I don't know h...
6,862,538
6,862,660
Iterating through collection of different types in C++
Situation I have a template class TIppImage<T> for image of type T. I have singleton class CIppMemoryManager which can store a number of images of different size and type. class CIppMemoryManager { public: /// ... Singleton interface ... template<class T> TIppImage<T>* GetImage(width, height); private: CIppMem...
What's wrong with polymorphic CIppImageContainer<T> (make them all share a common base class) and a smart pointer ? Or some kind of boost::variant ?
6,862,657
6,864,070
C++: Removing all asterisks from a string where the asterisks are NOT multiplication symbols
So basically, I might have some string that looks like: "hey this is a string * this string is awesome 97 * 3 = 27 * this string is cool". However, this string might be huge. I'm trying to remove all the asterisks from the string, unless that asterisk appears to represent multiplication. Efficiency is somewhat import...
Fully functioning code: #include <iostream> #include <string> using namespace std; string RemoveAllAstericks(string); void RemoveSingleAsterick(string&, int); bool IsDigit(char); int main() { string myString = "hey this is a string * this string is awesome 97 * 3 = 27 * this string is cool"; string newString ...
6,862,672
6,862,990
GDB cannot show the stack and shows "#1 0x0000000000000000 in ?? ()"
I have a multi-threaded C++ program that deadlocks in some rare cases. The problem is hard to reproduce and I can only reproduce it in a remote machine. The method I want to use for solving this problem is run the program wait for deadlock send abort signal to it for generating core dump copy the dump back to my local...
Note that you can also use gcore to create a core file without aborting. Have you tried running pstack on the remote host (assuming it's installed) to see if you can get a backtrace that way? Otherwise, if the shared objects used by your application are different on your local host and remote host, gdb won't be able to...
6,862,825
6,862,932
Getting cannot allocate memory error
I am getting this error in my program... mprotect: Cannot allocate memory ulimit -a gives the output: core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited scheduling priority (-e) 20 file size (blocks, -f) unlimited pending signals (-i) 16382 ...
Return Value On success, mprotect() returns zero. On error, -1 is returned, and errno is set appropriately. Errors EACCES The memory cannot be given the specified access. This can happen, for example, if you mmap(2) a file to which you have read-only access, then ask mprotect() to mark it PROT_WRITE. EFAULT The mem...
6,862,844
6,862,967
How bad rand from stdlib.h is?
I'm making a monte carlo simulation in C++ and I was using Boost for random numbers. I used GSL a bit too. But it turns out random number generation is one of my biggest runtime inefficiencies, so I just started using good old rand() from cstdlib. How badly am I risking to have poor random number properties on my simu...
There are two issues: (1) because RAND_MAX is only guaranteed to be at least 32767, there might not be many possible values (not necessarily bad for some applications), and (2) poor implementations. If you need what is known as a secure random number generator you will need to look somewhere else. But for many apps, r...
6,863,183
6,863,221
Unhandled Exception due to Class slicing
I'm getting an unhandled exception reading location 0x00000008 (reading NULL value) on the noted line below, relevant methods leading up to the error are included (continued below examples): Event Methods: Event::Event(Event::EVENTTYPE type) : eventType(type) { } KeyEvent Methods: class KeyboardKeyEvent : public Event...
One solution to avoid slicing is to make the destructor of base class virtual, so in your case you can make ~Event() virtual: class Event { public: //... virtual ~Event() {} }; By the way, I'm wondering why you do the following: //YOUR CODE : its causing the problem! Event* EventHandler::DequeueEvent() {...
6,863,715
6,864,007
Problem converting endianness
I'm following this tutorial for using OpenAL in C++: http://enigma-dev.org/forums/index.php?topic=730.0 As you can see in the tutorial, they leave a few methods unimplemented, and I am having trouble implementing file_read_int32_le(char*, FILE*) and file_read_int16_le(char*, FILE*). Apparently what it should do is load...
Yes, *buffer will read in Xcode's debugger as 0x72, because buffer is a pointer to a char. If the first four bytes in the memory block pointed to by buffer are (hex) 72 00 00 00, then the return value should be 0x00000072, not 0x00000027. The bytes should get swapped, but not the two "nybbles" that make up each byte. T...
6,863,859
6,863,910
Is copying automatically prohibited in classes derived from classed derived from Boost noncopyable?
For example: class Foo : boost::noncopyable { // ... }; class Bar : public Foo { // ... }; Is Bar non-copyable?
By default it is non-copyable, unless you create a custom copy-constructor and avoid calling a base copy-constructor there. See also Explicitly-defaulted and deleted special member functions introduced in C++11. Even though making a copy constructor/operator private solves the problem, the compiler generates a diagnost...
6,863,986
6,864,009
What is the type of a named rvalue reference?
Consider the following code: int&& x = 42; static_assert(std::is_same<decltype( x ), int&&>::value, "&&"); static_assert(std::is_same<decltype((x)), int& >::value, "&" ); So, what is the type of x? Is it an int&& or an int&? (I asked myself this question after reading this answer.)
The type of x (of the variable) is int&&. So decltype(x) yields int&&. The type of the expression x is int. If the expression is an lvalue, decltype((x)) yields a lvalue reference to the type of the expression. So decltype((x)) yields int&.
6,864,011
6,864,139
How can std::runtime_error::runtime_error(const std::string&) meet std::exception's requirement of throw()?
std::exception requires that its constructor be throw(). Yet std::runtime_error accepts a std::string as its argument, which indicates that it's storing a std::string somewhere. Therefore, an assignment or copy construction has to be going on somewhere. And for std::string, that's not a nothrow operation. How then does...
(Here's the same thing in a minimal-ish testcase.) runtime_error::runtime_error(string const&) doesn't need to meet throw(). It doesn't inherit from or override exception::exception(), and by the time string's copy constructor is invoked, exception::exception() has completed. If copying the string were to throw an exc...
6,864,053
6,864,702
Multiply Large Complex Number Vector by Scalar efficiently C++
I'm currently trying to most efficiently do an in-place multiplication of an array of complex numbers (memory aligned the same way the std::complex would be but currently using our own ADT) by an array of scalar values that is the same size as the complex number array. The algorithm is already parallelized, i.e. the ca...
You can do this fairly easily with SSE, e.g. void cmult_scalar_inplace(fcomplex *values, const int start, const int end, const float *scalar) { for (int idx = start; idx < end; idx += 2) { __m128 vc = _mm_load_ps((float *)&values[idx]); __m128 vk = _mm_set_ps(scalar[idx + 1], scalar[idx + 1], sc...
6,864,082
6,864,536
Fast ascii block to integer
Is there any command in stl that converts ascii data to the integer form of its hex representation? such as: "abc" -> 0x616263. i have the most basic way i can think of: uint64_t tointeger(std::string){ std::string str = "abc"; uint64_t value = 0; // allow max of 8 chars for(int x = 0; x <...
You want to pack ASCII characters from a string into a 64-bit integer. Since std::string is not an intrinsic type, for safety, copy the data into a buffer: uint_64 values[100]; // Allocate memory on a 64-bit boundary. char * p = (char *) values; // Point to the memory as characters. std::string example("beethoven"); ...
6,864,093
6,864,122
Parsing ampersands with expat fails. Invalid token?
I get an expat error when parsing specific characters only. Other HTML code is parsed just fine. I'm using the UTF-8 library of expat libexpatMT.lib and I'm working with char and std::string in a wrapper. No wide chars etc. used. // The ampersand leads to: Expat error: *not well-formed (invalid token)* <a href="http://...
In XML, you escape ampersand, even in entities. So the valid value is <a href="http://www.myurl.com?a=b&amp;c=d">Link</a> Correct Web pages do that. Browsers are quite tolerant for the error you made, though.
6,864,181
6,864,236
Advice on a simple random number generation problem.
I have a simple integer vector, with only 4 values. I want to loop through the vector, assigning either 0 or 1 to each value. I want it to be random to the point that its different every time. I thought the following would suffice: for (int i = 0; i < (int)numberVect.size(); i++) { numberVect[i] = rand() % 2;...
You need to seed the random generator, before using it. For that you need srand() I usually do that with passing current time to srand() as: #include <time.h> srand(time(NULL)); //seeding! //now use int whatever = rand(); Now everytime, you run this code you'll get different random sequence,even if there is one seco...
6,864,364
6,864,407
vector constructor creating vector with one less element
I am trying to split a vector into "almost equal" parts, and create subvectors for those parts. I have asked the original question here: How to split a vector into n "almost equal" parts but I found a really good solution, what I am trying to use, from here: Best way to extract a subvector from a vector? I wrote this f...
The vector constructor (and all STL constructors that accept pointer ranges, for that matter) are designed to take in a range of STL-style iterators. When using iterators, you specify a range by providing a pointer to the first- and the past-the-end elements, not the first and last elements. If you wanted to create a...
6,864,394
6,864,450
What requirements does the standard place upon a type thrown in an exception?
I thought exceptions imposed a bit more on the thrown type than the standard actually imposes. I want to clear up this confusion. What is actually imposed on those types?
The C++ ISO spec, §15.1/3, states that The type of the throw-expression shall not be an incomplete type, or a pointer or reference to an incomplete type, other than void*, const void*, volatile void*, or const volatile void*. Except for these restrictions and the restrictions on type matching mentioned in 15.3, the ...
6,864,422
6,948,870
ActiveX html control not calling code
I have an ActiveX HTML Object as defined here: <object id="HSMBTPrintX1" width="350" height="350" classid="CLSID:68d05400-18a6-4b39-b3ff-a17d77c1eddf" codebase=".\HSMBTPrintX.ocx"> And a button: <input type="button" name="Print" value="Print" onclick="PassParameter()" /> This button calls some javascript defined a...
I think the issue was with my HTML object... i now have the version number, and all caps for the class id: <object id="HSMBTPrintX1" width="350" height="350" classid="CLSID:68D05400-18A6-4B39-B3FF-A17D77C1EDDF" codebase=".\HSMBTPrintX.ocx#1,0,0,1"> everything is working fine now...
6,864,483
6,864,505
c++ syntax error when declaring an array of bytes
Im trying to declare an array of bytes so I can go through them and use each one of them seperatly. This is the array const BYTE keybyte[] = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57 0x58, 0x59, 0x5A, 0x30, ...
You are missing a comma between 0x57 and 0x58.
6,864,550
6,864,855
C++ Inheritance via dominance warning
I'm trying to implement a rather large object that implements many interfaces. Some of these interfaces are pure virtual. I may have a problem in diamond inheritance. Visual Studio is reporting a warning of C4250 ('class1' : inherits 'class2::member' via dominance). First of all these classes are inherited virtually as...
Everything is absolutely valid. A compiler is allowed to warn about valid code, no problem here. You can try silencing the warning with a using declaration. If this doesn't work (probably due to an MSVC bug), silence it with a pragma.
6,864,621
6,864,664
Getting most derived type during object construction
In my project, I have an abstract base class "Base". I would like to track all of the dynamic allocations/deallocations of objects that derive from "Base". To this end, I've overridden the new/delete operators in "Base". After successfully allocating memory in the overridden new operator, I'd like to notify the object...
You're right, it's not possible this way, as new operator just allocates memory, nothing more. The right place to do such thing is constructor, not allocator, where you should be able to use RTTI to determine type of built object (and thus it can be done in Base constructor, not in every child class constructor).
6,864,759
6,864,861
Determining the Newline character for the environment a C++ program is being compiled on
How does one determine the environment newline1 in C++? Google yields many results for C# and .NET but I didn't see any way to do it for non-CLI C++. Additional info: I need to scan a const char* for the character(s). 1By "environment newline" I mean \r\n on Windows, \n on Linux, and \r on Mac.
std::endl inserts a newline appropriate for the system. You can use a ostringstream to determine the newline sequence as a string at runtime. #include <sstream> int main() { std::ostringstream oss; oss << std::endl; std::string thisIsEnvironmentNewline = oss.str(); } EDIT: * See comments below on why thi...
6,864,789
6,864,877
How to fix stack overflow error in visual C/C++?
I am writing a file in C/C++ which generates 100000 lines of records (name, int[5] grade, double[5].value). The code should generate 100000 random characters for name and integer for value. I am getting stackoverflow error. Can anyone pls help?
Do not use a recursive function to generate or process the records and do not allocate the records on the stack. Recursion can be replaced by iteration, and a stack array can be replaced by std::vector.
6,864,821
6,864,925
Disable Command Prompt When Running LibVLC with QT on Windows
I have a c++ program that uses libVLC and QT. When the program starts it creates the QT UI but it also opens a command prompt that holds any VLC errors. Does anyone know a way to suppress to CMD window?
Don't use "--extraintf=logger" as command to libvlc.
6,864,880
6,865,139
std::forward vs std::move while binding lvalue to rvalue reference
is there a difference between move and forward here: void test(int && val) { val=4; } void main() { int nb; test(std::forward<int>(nb)); test(std::move(nb)); std::cin.ignore(); }
In your specific case, no, there isn't any difference. Detailed answer: Under the hood, std::move(t) does static_cast<typename std::remove_reference<T>::type&&>(t), where T is type of t (see §20.2.3/6). In your case, it resolves to static_cast<int&&>(nb). forward is a little bit tricky, because it is tailored for use i...
6,865,011
6,865,379
Code::Blocks building problem
Hi I have a problem building a program in Code::Blocks. The problem is when I build the code it starts giving me all kind of unrelated errors like these: main.cpp:(.text+0x12): undefined reference to `system' main.cpp:(.text+0x1e): undefined reference to `system' main.cpp:(.text+0x37): undefined reference to `ZSt4cout...
I see two possibilities: a) more likely: you try to compile your project at a location shared between Win7 and Linux without make clean. The object files the compiler generates are different on each platform, thus you try to link with incompatible object files. Just do a Rebuild all. b) less likely: the project might b...
6,865,016
6,866,068
move semantics and Lifetime of variables when binding lvalue to rvalues reference
just to be sure to well understand what is under the hood... questions are in the code as comments void test(int && val) { val=4; }//val is destroyed here ? int main() { int nb; test(std::move(nb)); //undefined behavior if I reference here nb ? std::cout << nb; nb=5; std::...
The moved-from value is left in a valid, but unspecified, state. That basically means, as far as I know, that it may contain any value, but it must contain some value, and accessing it is legal and defined behaviour.
6,865,263
6,865,301
binding of lvalue into rvalue reference move ctor and return of function
According to what I know it is not valid to bind a lvalue into a rvalue reference. And secondly, a lvalue expression is recognizable by the fact it can be prefix by adress-of operator, (&) I'm a little bit in trouble if this two sentences arecorrect with the following codes : #include<iostream> struct Foo { Foo(F...
return_foo() returns a prvalue (because it returns unnamed temporary object). Quote from §3.10/1, emphasis mine: A prvalue (“pure” rvalue) is an rvalue that is not an xvalue. [ Example: The result of calling a function whose return type is not a reference is a prvalue. The value of a literal such as 12, 7.3e5, or ...
6,865,398
6,865,426
Inserting endline into a stringstream
We know that when inserting \n in a file stream, the appropriate end-of-line sequence for the system will be written to the file (e.g. \r\n for Windows). Does inserting an endline in a std::stringstream result in the system-appropriate end-of-line sequence being written to the string? For example: #include <sstream> i...
The system specific line endings are only relevant for text files. As long as the stream is only in memory, it is just '\n'.
6,865,571
6,879,642
Info on CrossPlatform
I have looked at some of the info on cross platform design. I can't find the answer to one question I have however. What I would like to do is design my UI's in Delphi (Windows) and X-Code (Mac) with the underlying guts of the program being OS agnostic C++ code. Is this possible to achieve? I see lots of talk about Cr...
If you are comfortable working with Object Pascal take a look to the FreePascal compiler and Lazarus which is a free cross-platform IDE (available for Windows, Linux, Mac OS X).
6,865,727
6,865,743
Weird mod operator (%) result when using #define
int temp1,temp2,temp3; temp1 = 199; temp2 = 200; temp3 = 199%temp2; CString txt; txt.Format(_T("temp3 = %d"),temp3); AfxMessageBox(txt); Output is 199 as expected. #define WIDTH 100 #define BUFFERWIDTH 200 int temp1,temp2,temp3; temp1 = 199; temp2 = BUFFERWIDTH; temp3 = 199%BUFFERWIDTH; CString txt; txt.Format(_T("t...
Read up about operator precedence, and note that you are saying 199 % 2 * 100. . . . or should I say, (199 % 2) * 100...
6,865,921
6,866,189
How to turn off RTTI in Visual Studio 2008
I am not sure about other versions, but, in VS 2008 even with RTTI disabled I can query the information by calling typeid(T).name() on the type. It works with all types, internal and user created. Our project has RTTI disabled but I was surprised to find that this still worked. Is this a Visual Studio bug or is the /GR...
Is it possible that you used typeid on an expression whose type is known at compile time? If so you would bypass the "run-time" aspect of RTTI altogether. From the Microsoft documentation on typeid: If the expression is neither a pointer nor a reference to a base class of the object, the result is a type_info refere...
6,866,038
6,866,114
compiler error C2448 returning a std stream
I have a Visual Studio 2008 C++ program where I have my own stream implementation. Something like this: class Foo : public std::ostream { public: Foo( int a ) : std::ostream( &buf_ ) { }; Foo( boost::shared_ptr< int > a ) : std::ostream( &buf_ ) { }; private: std::filebuf buf_; }; class Bar { public: F...
Your Foo class is inheriting from a non-copyable class, yet you are not implementing the copy constructor. You are bound to get into trouble when you pass instances of Foo by value, as you do in the getter functions. The reason that GetFoo works might be that return-value optimization is eliding the copy construction, ...
6,866,078
6,866,317
How to send raw binary data using boost::asio
I'm writing a TCP client using boost::asio. I want to send an array of floats in their binary representation. Does boost provide a nice way to convert data to their binary representation for placement it in a boost::array or something? I have used Qt QDataStream in the past and it worked well; I'm sure boost has somet...
#include <boost/asio.hpp> #include <boost/foreach.hpp> #include <boost/lexical_cast.hpp> #include <iostream> int main( unsigned argc, char** argv ) { if ( argc < 3 ) { std::cerr << "usage: " << argv[0] << " host port" << std::endl; exit( EXIT_FAILURE ); } boost::array<float, 5> foo = {1....
6,866,118
6,866,143
Literal string works but string doesn't in file.open()
This works: file.open("Levels\\test.txt"); This doesn't: string pathname = "Levels\\test.txt"; file.open(pathname); It outputs the following error: no matching function for call to 'std::basic_ifstrea<char, std::char_traits<char> >::open (std::string&)'
That member function takes a char const*, not a std::string; you would need to pass it pathname.c_str(). (In C++0x, there is an overload of open that takes a std::string, so your code will someday work as is; your implementation apparently does not support this yet.)
6,866,146
6,866,179
Why does one need a null shared_ptr and how can it be used?
In Scott Meyers's Effective C++, item 18 Make interfaces easy to use correctly and hard to use incorrectly, he mentioned the null shared_ptr: std::tr1::shared_ptr<Investment> pInv(static_cast<Investment*>(0), getRidOfInvestment) and a vogue assignment operation pInv = ... //make retVal point to the correct object ...
There is no need to use that hack to get a null (empty) shared_ptr. Simply use the default constructor: std::shared_ptr<Investment> pInv; // starts null To assign a pointer to a shared_ptr, either do it at construction time: std::shared_ptr<Investment> pInt(new Investment); // not allowed due to explicit annotation on...
6,866,183
6,866,310
When does a deep copy happen to a QList?
In a class I'm working on, I am juggling several QLists. I have heard that Qt tries not to make deep copies of lists whenever possible. From what I understand, that means that no deep copy happens when you do this: QList<int> myList; myList << 1 << 2 << 3 << 4; QList<int> otherList = myList; // No deep copy In some...
QLists are implemented using implicit sharing. Object assignment (with operator=()) for implicitly shared objects is implemented using shallow copies. This means that assignment alone will never cause the contained data to be copied. However, writing to a shared instance will cause the source object to be copied. T...
6,866,192
6,866,234
How do archive containers work?
For learning purposes, I want to make a simple archive format where I can put in files and extract them. No compression. What resources, or techniques would be recommended for creating something like this? The result wold be something like files.bin Thanks
Put a header at the beginning of the archive with offsets to where each file lies inside archive. Or just store them sequentially, putting the size before each file.
6,866,206
6,866,927
Volatile and CreateThread
I just asked a question involving volatile: volatile array c++ However my question spawned a discussion on what volatile does. Some claim that when using the CreateThread(), you don't have to worry about volatiles. Microsoft on the other hand gives an example of volatile when using two threads created by CreateThread()...
What volatile does: Prevents the compiler from optimizing out any access. Every read/write will result in a read/write instruction. Prevents the compiler from reordering the access with other volatiles. What volatile does not: Make the access atomic. Prevent the compiler from reordering with non-volatile accesses. ...
6,866,243
6,866,683
C++ Macro improperly terminated macro invocation
In C++ is there a mechanism to allow non terminated macros to be expressed? This is a contrived example: #define MACRO(x, y) x + y #define MACROC1(x) MACRO(x, #define MACROC2(y) y) //...expecting 3 int foo = MACROC1(1) MACROC2(2); I receive the error improperly terminated macro invocation from MSVC. When I run cl -E ...
I don't think this is possible. The C precompiler expands macros depth-first, so the MACROC1 will be full expanded before the MACROC2 is even considered. Then, it will find the MACRO with and incomplete argument list and throws an error. Generally speaking, you should avoid defining macros that build other macro calls....
6,866,277
6,866,337
Once a function name has been declared as 'virtual', can it ever be be made un-virtual again?
So let us say I have some chain of classes where each class is derived from the class before it. For whatever reason, they all like to use the same name for some member function. Kinda like this: class C1 { public: void f() { cout<<"C1"; }; }; class C2 : public C1 { public: void f() { cout<<"C2"; }; }; cl...
Once a function has been declared virtual (at some point in the chain of inheritance) can it ever be reverted back to being non-virtual (further down the chain of inheritance)? No. Once a function signature has been made virtual somewhere along the line of inheritance, it will stay that way: every function with the s...
6,866,464
6,868,828
COM SAFEARRAY of GUID's returned from C++ to C#
I'm currently running into an issue of needing to pass a SAFEARRAY(GUID) as a return value from C++ to C#. Currently the C# side is using an Interop dll generated from Tlbimp.exe (Type Library Importer). The IDL is: HRESULT GetGuids( [out]SAFEARRAY(GUID)* guids); I've also tried [out, retval] The function signatur...
You're absolutely right - the problem is that VT_CLSID isn't allowed in either VARIANT or SAFEARRAY. It boils down to GUID not being an Automation-compatible type. I often need to do the same thing that you're trying. The easiest way around the problem is to convert the GUID to a string and then pass SAFEARRAY(VT_BSTR)...
6,866,550
6,866,721
Does Visual Studio have a namespace-sensitive macro-substitution option?
What I'm talking about is to find a way to avoid the macros in <windows.h> from polluting whatever project I'm writing. Excerpts from windows.h: #ifdef UNICODE #define LoadImage LoadImageW #else #define LoadImage LoadImageA #endif // !UNICODE #ifdef UNICODE #define GetMessage GetMessageW #else #define GetMessage G...
Macro substitution are basically simple textual replacements, done before the proper compiler even starts to parse the code. Therefore they are not aware of namespaces or any other parts of the C++ syntax above the pure lexical level. The straight forward way to avoid replacement of your identifiers is to remove the ma...
6,866,861
6,866,903
posix threads and O3 optimisations
I am working on a program that uses mpi (openmpi 1.4.3) and pthreads, working in c++ under linux. some of the mpi nodes have a queuing system implemented with pthreads. Idea is simple one thread adding elements into queue, and few other "working" threads picking up objects and doing their job on them (not a rocket scie...
I'm guessing you are seeing a bug based on assumptions about instruction ordering when you check if the queue is empty - when you turn up the optimization the ordering changes and it breaks because the mutex you have hasn't put up a memory barrier protecting this from occurring.
6,866,929
6,866,944
Dynamic memory allocation in C++ require the new operator new?
int d; cin >> d; int asdf[d]; Is this considered dynamic memory allocation? According to http://www.cplusplus.com/doc/tutorial/dynamic/, it seems like I shouldn't even be able to compile this, because arrays without using the new operator can only be declared with constant size, maybe I read it wrong. (I'm using CodeB...
int x[n]; is a variable-length array (VLA), which has automatic storage duration (i.e. "on the stack"). It is not valid in C89 or C++98/03, but it was introduced in C99 and is commonly available as an extension, e.g. in GCC. The functionality can also be mimicked on some platforms with the non-standard alloca() functio...
6,867,178
6,867,789
C++ UDP. Why is recvfrom() is not blocking?
I am writing some simple client/server code using UDP. The program works fine, but if I only start the client, the recvfrom method does not block. However, when I remove the sendto method, recvfrom starts to block. Any idea of what is going on? Here is the client side code: int server_length; /...
There are a variety of ways that sendto can fail. Some, such as arp failure, will cause an error during sendto. Other, such as ICMP port unreachable, may be reported when you next use the socket. Your recvfrom call could actually be fetching the ICMP packet sent in response to your outgoing packet. Does a second recv...
6,867,349
6,867,407
C++ Recursive function for printing a ruler not working.
I've been trying to teach myself C++ from a book. The following piece of code has been a problem, as I can't figure out what I'm doing wrong.The code is an example from the book, and yet it won't bring the same result. The function subdivide() is supposed to use the divide and conquer method for dividing the array at m...
In your subdivide function, you have a semicolon after the if: if (level==0); return; The indentation is deceiving, and what your code is actually doing is if (level==0); //does nothing return; // always returns (before modifying the ruler) Change it to if (level==0) //no semicolon here return;
6,867,559
6,879,315
Recover Parent from Pointer-to-member
Suppose that we have a pointer-to-class member pointing at a field of a class. We also have a pointer to that specific field in a particular instance of the class. For example, we might have something like this: class A { B inner_object; } A* myA = /* ... */ B* ptr = &myA->inner_object; B A::* memPtr = &A::inne...
After a decent amount of research... This is actually done in most industrial intrusive list implementations. It does require some hackery, however. Boost intrusive structures use the following (and yes, it is implementation specific) template<class Parent, class Member> inline const Parent *parent_from_member(const Me...
6,867,618
6,867,663
Why doesn't this compile
#include "base.h" #include <Poco/SharedPtr.h> #include <Poco/AutoPtr.h> #include <vector> using Poco::SharedPtr; using Poco::AutoPtr; namespace kroll { class Value; class KObject; class KMethod; class KList; class StaticBoundObject; class StaticBoundMethod; class StaticBoundList; cl...
Line 66 should be this: KAutoPtr() : AutoPtr<C>() And similarly for the other constructor calls.
6,867,693
6,867,722
Change floating point rounding mode
What is the most efficient way to change the rounding mode* of IEEE 754 floating point numbers? A portable C function would be nice, but a solution that uses x86 assembly is ok too. *I am referring to the standard rounding modes of towards nearest, towards zero, and towards positive/negative infinity
This is the standard C solution: #include <fenv.h> #pragma STDC FENV_ACCESS ON // store the original rounding mode const int originalRounding = fegetround( ); // establish the desired rounding mode fesetround(FE_TOWARDZERO); // do whatever you need to do ... // ... and restore the original mode afterwards fesetround(...
6,867,842
6,867,912
You can 'promote' access specification through inheritance, can you ever 'demote' access specification?
By 'promote' I mean make access more restrictive and by 'demote' I mean make less restrictive. For example, when class B is derived from class A using : protected or : private then the public members of A get promoted, to protected and private, respectively. Could some class C ever come in and derive itself from class ...
If you're using protected derivation, then class C could indeed give access to the protected members, by creating an appropriate wrapper: class A { public: void F(); }; class B : protected A { }; class C : public B { public: using B::F; }; This also can be made to work with data members: class A { public: int ...
6,867,903
6,867,932
using a 2d vector as value type in a c++ map
I need to to have a map where the key is a string type and the value is a 2d vector. I tried map<string, vector<vector<double> > > myMap; but doesn't seem to work.
The following code compiles fine for me in g++ 4.5.0: #include <string> #include <map> #include <vector> int main() { std::map<std::string, std::vector<std::vector<double> > > map; return 0; } Perhaps you made a syntax error?
6,868,153
6,868,174
Simple question about header files in C++
Lets say I have 3 files: add.h, add.cpp and main.cpp. This is a common example on C++ training sites where add.h contains the prototype of a function called "add". Add.cpp contains the declaration of the prototype and main.cpp includes add.h and then calls the add() function to add two numbers (x and y) together. My qu...
I think you are mixing Java with C++. In Java (editors like Eclipse) there is a general restriction that, your class name should same as the file name. i.e. // Add.java class Add { } In C++ there are no such restrictions. Your file name can be any meaningful name. The only thing you have to take care is that your impl...
6,868,245
7,122,278
How to drag & drop lots of files without taxing system resources?
One of the features that the program that I'm working on is the ability to drag objects from its main window and drop them onto Windows Explorer as files. To do this, we override COleDataSource::OnRenderGlobalData() and, when the format is CF_HDROP, we save each object as a file. This works fine when the number of obj...
Instead of creating files, drag virtual data that is generated at drop time. Offer CFSTR_FILEGROUPDESCRIPTOR and CFSTR_FILECONTENTS. Here's an example.
6,868,279
6,868,312
is there anything in qt to handle registering an application?
I'm writing an app using C++ and the Qt Framework 4.7 to run on Windows, Mac and Linux desktop. When someone installs or runs my app the frist time, I need to gather some registration information, and return a registration code or something so on subsequent runs, the app knows it has already been registered. I have no...
No, Qt doesn't provide any of this type of functionality. For Mac OS X, you can have Apple take care of most of the registration and payment details by providing your application through the Mac App Store. For Windows and Linux though, you're mostly on your own.
6,868,363
6,868,389
How to (re)call a constructor of an initialised object?
I'm writing some code that is checking if a specific midi device is plugged in, and if it isn't the code rechecks every 5 seconds until it is plugged in. My problem comes about in checking the list of devices - the external library has no function to re-check the ports, as it only does it in the constructor of the clas...
By using placement new you can re-call the constructor: bool foo::recheck() { new (&midiIn) ofxMidiIn(); midiIn.listPorts(); } The line new (&midiIn) ofxMidiIn() will re-construct midiIn in its own memory region, by calling the constructor of ofxMidiIn. However, this approach will create problem if ofxMidiIn ...
6,868,509
6,868,587
Some boost thread questions C++
I am using boost::thread, and I meet some problems. The thing is, are there any ways I can join a thread before the last join finish? for example, int id=1; void temp() { int theardID = id++; for(int i=0;i<3;i++) { cout<<theardID << " : "<<i<<endl; boost::this_thread::sleep(boost::posix_tim...
You can use Boost.Thread's condition variables to synchronize on a condition more complex than what join can provide. Here's a example based on yours: #include <iostream> #include <boost/thread.hpp> #include <boost/thread/locks.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/condition_variable.hpp> boost...
6,868,768
6,869,062
Is there any use case for class inside function after introduction of lambda?
From the wikipedia article about Lambda functions and expressions: users will often wish to define predicate functions near the place where they make the algorithm function call. The language has only one mechanism for this: the ability to define a class inside of a function. ... classes defined in functions do ...
Is there any use case for class inside function after introduction of lambda ? Definitely. Having a class inside a function is about: localising it as a private implementation detail of the code intending to use it, preventing other code using and becoming dependent on it, being independent of the outer namespace. ...
6,868,826
6,868,858
C++ design pattern platform specific api
I am working on Windows. I have to see certain set of API's for Windows 2008 and above and different set of API's for other flavors of Windows. I want to know what is the best way to design such kind of stuff, so that my main driver code do not have #ifdef For Example: In Windows 2008 We have API EVT_HANDLE WINAPI Ev...
You can write an Platform Abstraction Layer, which will expose a common interface for all api types and for each port then you can implement the interface. You can provide the abstraction as an separate library for each port which ensures that your calling application remains the same only the library to be linked chan...