question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,926,078
1,926,246
C++ OOP Library for Programming the Lego NXT
A while back, I got a LEGO Mindstorms NXT set for Christmas, and now I would like to program it in C++. I have looked around, here and other places, and could not find a cross-platform, open source, OOP C++ library that "felt right", including lestat and nxtOSEK. So, I have decided that unless I can find one I do like, then it would be a great learning experience for me to write my own library. I have done a little research, and decided it would be easiest to communicate with it over bluetooth, rather than compiling my programs to the NXT machine code. I would also like this to be done in OOP style, meaning the NXT brick, motors, sensors, etc would exist as objects. So, my question is: what do I need to know before embarking on this? where can I get good references (besides here, and specific to the NXT)? What are other decent "basic" libraries* for things like Bluetooth communication? *I am all for using boost and the STL, if necessary, by the way. Alternatively, I believe in not reinventing the wheel if I don't have to, so if there is a decent C++ OOP bluetooth-communicating NXT library out there, let me know!
I've taken a look at doing this before. Start looking here: http://bricxcc.sourceforge.net/ On this page you can download the source for it. What I ended up doing is compiling my C source code down to byte codes that the NXT brick can understand. This allowed me to add some custom extensions to C though I did spend alot of time compiling C down to a compact enough form in byte codes that fit into the NXT's memory:) If you want to use an existing C implementation then check out this chart: http://www.teamhassenplug.org/NXT/NXTSoftware.html For a list of the NBC(Next Byte Codes) start with this page. I found it extremely helpful. http://bricxcc.sourceforge.net/nbc/
1,926,311
1,926,580
Cygwin in Visual Studio
I'm trying to port an old program I wrote for class from KDev in Ubuntu to Windows Visual Studio 2008 using Cygwin as a personal learning exercise. I have the include path configured to include C:\cygwin\usr\include but it doesn't read the .h files properly. Namely I'm curious as to how one would go about using unix sockets.h functionality in a Visual Studio environment using Cygwin. Has anybody ever got this working or have an easier way to go about doing this?
There are several ways to go about this that could be made to work, depending upon your exact goals. The simplest way is probably just to create a Visual Studio "makefile" project that fires off a custom build command to run a makefile you've built. But that keeps you away from a lot of the nice benefits of Visual Studio as an IDE, so I'm guessing that's not really what you're after. If you want a more fully integrated solution, you're going to need to do two things. First of all, you're going to need to change out all of your include/library paths to avoid the Microsoft ones and go after the Cygwin ones instead. You can do this by selecting "Tools->Options" from the menu, then choosing "Projects and Solutions->VC++ Directories" from the tree on the left hand side of the window that comes up. You'll have options to change the search directories for executables, headers, libraries, etc. For what you're trying to do, I'd suggest removing everything and adding in just the cygwin directories. Second, you'll have to tell Visual Studio to use the gcc/g++ compiler. This is a bit trickier. VS supports custom build rules for custom file types... but it seems to have C++ hardwired in for the Microsoft compiler. I don't really know a great way around that except to use your own custom file extension. You can try the standard unix extensions of .c (C files) and .cc (C++ files), but I suspect Visual Studio will automatically pick up on those. You may have to go with something totally foreign. If you right click on your project in the Solution Explorer and select "Custom Build Rules" you'll be given an interface that will let you create your custom build rules for the file extension you've chosen. The interface is relatively straightforward from there. This might not get you exactly what you wanted, but it's probably about as close as you're going to get with Visual Studio.
1,926,355
1,926,395
Making Photoshop-like drop shadows in a game
I'm making a game where the game's size varies, so I want to make my own shadows. The api i'm using can fill rectangles, make ellipses, horizontal lines etc. And supports rgba. Given this, how could I make a drop shadow? I tried making a black to white gradient and setting the alpha to 20%, but it didnt look very good... I'm not sure how they are done. Thanks
I would suggest: copy the object, move it in the opposite direction of the light source and use its distance as a weight, turn it totally black, blur it using the light source's distance as a weight, too, put it behind the object, lower the alpha if you want. ????? profit.
1,927,231
1,933,895
Remote access to Hypertable from C++
I have sucessfully installed Hypertable on top of Hadoop on a small cluster of Ubunto servers. At this point the only way to access the Hypertable is via the 'ht shell' command on one of the HT servers. Thats all very interesting, but now I want to access the hypertable database from a PC thats not part of the cluster. Preferably from C++ - preferably on a Windows box. It looks like I need a Vistual Studio compatible build of libHypertable.
According to the mailing list, if you use the Thrift interface, you only need Client.h, ThriftHelper.* and gen-cpp/* from the src/cc/ThriftBroker directory to build a VS project. Native client would need more than libHypertable.a and is currently not yet ported to Windows. BTW, there are reports on the mailing lists that C# works fine via the thrift interface.
1,927,477
1,927,566
Can a heap-allocated object be const in C++?
In C++ a stack-allocated object can be declared const: const Class object; after that trying to call a non-const method on such object is undefined behaviour: const_cast<Class*>( &object )->NonConstMethod(); //UB Can a heap-allocated object be const with the same consequences? I mean is it possible that the following: const Class* object = new Class(); const_cast<Class*>( object )->NonConstMethod(); // can this be UB? is also undefined behaviour?
Yes. It's legal to construct and destroy a const heap object. As with other const objects, the results of manipulating it as a non-const object (e.g. through a const_cast of a pointer or reference) causes undefined behaviour. struct C { C(); ~C(); }; int main() { const C* const p = new const C; C* const q = const_cast<C*>(p); // OK, but writes through q cause UB // ... delete p; // valid, it doesn't matter that p and *p are const return 0; }
1,927,573
1,927,665
"I'm busy please wait" window - no buttons
I want to pop up a window to show that a program is busy with a particular time consuming task. But I don't want any buttons on it. I just want to pop it up, do the task, then remove it. I'm not sure what such a window is called and so don't know what to search for in MSDN etc. Is there some ready made API for this kind of thing or do I need to cook my own? EDIT: In answer to some comments... I'm not using MFC. The program is for my own use - the answer does not have to look pretty. The reason I don't just rely on the hourglass is that the hourglass only shows when the cursor is on top of the applications small window, and I work on a system with four very large monitors and the cursor is often not on the window in question.. If I don't see an hourglass then my program looks like its crashed. Its quite disturbing. I work on this program continuously as my job, and have done so for many years. The operation that takes a long time is performed only occasionally, I may go months without using it. So if it locks up doing this task I'm worried that I will have forgotten that its just busy and assume there's some bug and go on a wild goose chase trying to fix a problem that does not exist.
This is actually a more profound question than simply dialogs. If you are engaging in work which may take a long time, then you don't want it on the main thread. On Windows versions prior to Vista, the Window won't paint - you end up with "white window" syndrome, which is very ugly. Far better to create a worker (non-ui) thread and have it post a message back to the main window when it's done. Obviously you have to have some sort of timeout in case it never finishes. If you do it this way, then the "dialog" problem becomes an issue of simply putting up a window and pulling it down again when the thread sends you its "done" message. You can try looking at the MSDN documentation for "modeless dialog", a dialog which can you can create and destroy at will (remember to disable the main window). There are some nits with implementing this in MFC, but you don't say whether you're using that or not.
1,927,655
1,927,928
How to read Lotus Notes mail archives (*.nsf)
Does anyone know how to read these files without using the interops or COM interaction? Just the direct way. Is there any spec of this format or reverse engineered stuff that could help on this? Thanks.
There is Lotus API (which is in C). It provides access to everything there is in an NSF - documents, design elements, security elements, etc) http://www.ibm.com/developerworks/lotus/downloads/toolkits.html?S_TACT=105AGX13&S_CMP=LSDL Read all you choices here: Is the NSF file structure documentation available anywhere online?
1,927,853
1,927,915
How to check if there is anything in cin [C++]
is there any way to check if there is something in cin? I tryied peek() but if there isn't anything peek() waits for input and that isn't what I want. Thank you
You cannot use cin to read keystrokes, and then go on to do something else if there is nothing available, which I think is what you may want. cin is a buffered stream and simply does not work in that way. In fact, there is no way of doing this using Standard C++ - you will have to use OS specific features.
1,928,090
1,928,119
Unable to build any C++ projects on VS 2010?
When I try to "Build" a project it says: The operation could not be completed. Unspecified error When I try to debug the debugger says: The debugger cannot continue the process I really don't understand what is wrong with that? The project is fine and it compiles perfectly on VS 2008.
Without more context information it's hard to help. VC10 is in Beta2 state so you should report this problem with context (environement + projects infos) to the Microsoft Connect website.
1,928,152
1,928,200
Passing a C++ object with an Objective-C (Cocoa) event (performSelector)
How to pass a C++ object with the performSelector method? This method only allows you to pass 'objc_object*' objects, I can't cast them. I could build a wrapper, but I don't know the overall superclass for all C++ objects, so I don't know how I could build a generic wrapper (I don't want specific knowledge about the object in the wrapper).. Any hints?
Try just using +[NSValue valueWithPointer:].
1,928,169
1,928,263
Function template specialization in derived class
I've a base class with a function template. I derive from base class and try to have a specialization for the function template in derived class I did something like this. class Base { .. template <typename T> fun (T arg) { ... } }; class Derived : public Base { ... } ; template <> Derived::fun(int arg); and in .cpp file I've provided implementation for the template specialization. This works fine with MSVC 8.0 and g++-4.4.2 complains about lack of function declaration fun in Derived class. I do not know which compiler is behaving correctly. Any help in this is greatly appreciated. Thanks in advance, Surya
You need to declare the function in Derived in order to be able to overload it: class Derived : public Base { template <typename T> void fun (T arg) { Base::fun<T>(arg); } } ; template <> void Derived::fun<int>(int arg) { // ... } Note that you may need to inline the specialisation or move it to an implementation file, in which case you must prototype the specialisation in the header file as: template <> void Derived::fun<int>(int arg); otherwise the compiler will use the generalised version of 'fun' to generate code when it is called instead of linking to the specialisation.
1,928,431
1,928,502
How do I call a pointer-to-member-function?
I'm getting a compile error (MS VS 2008) that I just don't understand. After messing with it for many hours, it's all blurry and I feel like there's something very obvious (and very stupid) that I'm missing. Here's the essential code: typedef int (C::*PFN)(int); struct MAP_ENTRY { int id; PFN pfn; }; class C { ... int Dispatch(int, int); MAP_ENTRY *pMap; ... }; int C::Dispatch(int id, int val) { for (MAP_ENTRY *p = pMap; p->id != 0; ++p) { if (p->id == id) return p->pfn(val); // <--- error here } return 0; } The compiler claims at the arrow that the "term does not evaluate to a function taking 1 argument". Why not? PFN is prototyped as a function taking one argument, and MAP_ENTRY.pfn is a PFN. What am I missing here?
p->pfn is a pointer of pointer-to-member-function type. In order to call a function through such a pointer you need to use either operator ->* or operator .* and supply an object of type C as the left operand. You didn't. I don't know which object of type C is supposed to be used here - only you know that - but in your example it could be *this. In that case the call might look as follows (this->*p->pfn)(val) In order to make it look a bit less convoluted, you can introduce an intermediate variable PFN pfn = p->pfn; (this->*pfn)(val);
1,928,475
1,928,510
Concat Macro argument with namespace
I have a macro, where one of the arguments is an enum value, which is given without specifying the namespace scope. However somewhere inside the macro I need to access it (obviously I must define the namespace there), but I can't seem to concat the namespace name with the template parameter. Given the following samplecode the compiler complains that pasting :: and Val doesnt give a valid preprocessor token (it works fine for concating get and a to getVal though). namespace TN { enum Info { Val = 0 }; } #define TEST(a) TN::Info get ## a(){return TN::##a;} TEST(Val) So is there any way to make this work without using another argument and basically specifying the value to be used twice (e.g. #define TEST(a,b) TN::Info get ## a(){return b;})?
## is a token pasting operator, i.e. it should make a single token out of multiple bits of token and as the compiler says, ::Val isn't a single token, it's two tokens. Why do you need think you need the second ## at all? What's wrong with this. #define TEST(a) TN::Info get ## a () { return TN::a; }
1,928,517
1,928,562
Why is my recursiveMinimum function not working?
#include <iostream> using namespace std; int recursiveMinimum(int [], int n); int main () { int theArray[3] = {1,2,3}; cout << recursiveMinimum(theArray, 0); cout << endl; return 0; } // pass in array and 0 to indicate first element // returns smallest number in an array int recursiveMinimum (int anArray[], int n) // nth element is smallest element in anArray { while (anArray[n+1] != NULL) { int smallest = n; if (anArray[n+1] <= anArray[n]) smallest = n + 1; //if last element has not been reached return recursiveMinimum(anArray, smallest); } } My function exits, but it doesn't return anything. I tried to set the base case to when the outside of the array is reached. The return 0 line in main is reached so I'm pretty sure the base case in my function is being reached. Here is the working function: #include <iostream> using namespace std; int recursiveMinimum(int a[],int min,int index,int size); int main() { int a[6] = {8, 2, 55, 3, 11, 9}; cout << recursiveMinimum(a,a[0],1,6) << endl; return 0; } // pass in the array, the first element, // 1 to indicate 2nd element, and the number of elements int recursiveMinimum(int a[],int min,int i,int size) { if(i == size ) return min; else if(i < size) { if(a[i] < min) recursiveMinimum(a,a[i], i + 1, size); else recursiveMinimum(a,min, i + 1, size); } } Thank you to everyone who helped. Due to time constraints I sent out a SOS (Stack Overflow distress Signal), however next time I will definitely step through the debugger prior to asking a question.
You are recursing within the while loop: while( condition ) recursive call while( condition ) recursive call . . . Instead what you probably were thinking was if( condition ) recursive call recursive call recursive call you see? Get rid of the while and replace it with an "if" statement.
1,928,536
1,929,608
How to serialize shared/weak pointers?
I have a complex network of objects connected with QSharedPointers and QWeakPointers. Is there a simple way to save/load them with Boost.Serialization? So far I have this: namespace boost { namespace serialization { template<class Archive, class T> void save(Archive& ar, QSharedPointer<T> const& ptr, unsigned version) { T* sharedPointer = ptr.data(); ar & BOOST_SERIALIZATION_NVP(sharedPointer); } template<class Archive, class T> void load(Archive& ar, QSharedPointer<T>& ptr, unsigned version) { T* sharedPointer = 0; ar & BOOST_SERIALIZATION_NVP(sharedPointer); ptr = QSharedPointer<T>(sharedPointer); } template<class Archive, class T> void save(Archive& ar, QWeakPointer<T> const& ptr, unsigned version) { T* weakPointer = ptr.toStrongRef().data(); ar & BOOST_SERIALIZATION_NVP(weakPointer); } template<class Archive, class T> void load(Archive& ar, QWeakPointer<T>& ptr, unsigned version) { T* weakPointer = 0; ar & BOOST_SERIALIZATION_NVP(weakPointer); ptr = QSharedPointer<T>(weakPointer); } } } This is not working because the shared pointers are always constructed from raw pointers so they all think the reference count is 1. It also immediately frees weak pointers. With some effort I can convert the classes to use boost::shared_ptr and boost::weak_ptr. Will that do any good?
The question is what do you really want to achieve by serializing pointers? What is your expected output? Note that pointers point to a place in memory -- several may point to the same place in memory. Serializing the address won't work. You can't just write down the exact memory address, because there's no way to guarantee that objects on the next run will be able to take the same space (another program may have already reserved that place). Serializing the pointed object in each place where we have a pointer wont work: This would be a lot more data that we'd need to serialize If we had weak pointers creating a circular dependency we wouldn't be able to stop and retrieve that connection later. There is no way to merge the same objects into one when deserializing Now that you think about it, you can try the official answer of boost::serialization: boost::serialization on shared_ptr boost::serialization on shared_ptr 2
1,928,570
1,928,672
Any good C or C++ libraries out there for dealing with large point clouds?
Basically, I'm looking for a library or SDK for handling large point clouds coming from LIDAR or scanners, typically running into many millions of points of X,Y,Z,Colour. What I'm after are as follows; Fast display, zooming, panning Point cloud registration Fast low level access to the data Regression of surfaces and solids (not as important as the others) While I don't mind paying for a reasonable commercial library, I'm not interested in a very expensive library (e.g. in excess of about $5k) or one with a per user run-time license cost. Open source would also be good. I found a few possibilities via google, but they all tend to be too expensive for my budget.
I second the call for R which I interface with C++ all the time (using e.g. the Rcpp and RInside packages). R prefers all data in memory, so you probably want to go with a 64bit OS and a decent amount of RAM for lots of data. The Task View on High-Performance Computing with R has some pointers on dealing with large data. Lastly, for quick visualization, the hexbin is excellent for visually summarizing large data sets. For the zooming etc aspect try the rgl package.
1,928,688
1,928,766
Custom UIs in C++ with Qt?
Coming from C#, I've decided to learn C++ with the Qt framework. I have one question though, what is the "correct" way to accomplish an UI like this one? This may be kind of subjective, but I'm sure that stacking image labels on top of each other isn't the right way. browser mockup http://img685.imageshack.us/img685/7643/mockup.png
I'd recommend creating a plain old standard UI first, then to apply a stylesheet to it to achieve the required look. That way, you can concentrate on the functionality that you want (a QToolBar with buttons and a QLineEdit) and just do all the styling afterwards (or first).
1,928,727
1,928,741
C++, is linking order standardized?
On my linux box, I have 2 libraries: libfoo1.a and libfoo2.a and they both contain an implementation of void foo(int) and my main program calls foo: int main() { foo(1); return 0; } I compiled the program two ways using g++ g++ main.cpp libfoo1.a libfoo2.a -o a1.out g++ main.cpp libfoo2.a libfoo1.a -o a2.out When I run the programs, a1 is clearly using the foo() implementation from libfoo1.a, while a2 clearly used libfoo2. That is, g++ linked whichever foo() that it saw first. My question (finally) is, is this "greedy" linking policy actually specified in the C++ standard? Or would a different compiler / platform behave differently in an implementation-defined way? PS: To put the question in practical context, I really like the way this g++ example works. In my real application, I have a legacy libfoo2 that implements many (many!) functions, but I want to provide new implementations for a handful of them in libfoo1. On one hand I could write a whole new interface in libfoo1, implement my handful, then delegate to libfoo2 for the remainder. But I would rather void writing all that delegation code, if I can rely linker to do it for me (even for non-g++ compilers like icc). PPS: To put it in real practical context, libfoo2 is the blas, and libfoo1 is a homebrew OpenMP implementation of a few of its routines. I'm not ready to shell out for MKL. ATLAS does not multithread the functions I want to call. It is very good at multithreading GEMM, but I need some of the quirkier routines from LAPACK to be fast too (zsptrf / zsptrs / zspr). It appears that the my cache-ignorant OpenMP implementation of these routines can do better than it's cache-tuned sequential implementation. Sorry for the length of post.
The standard doesn't say anything about linking order. I would say it's not good practice to rely on whatever order your compiler uses.
1,928,808
1,928,834
How to construct a container of MyClass, where MyClass constructor can throw?
I have something like: #include "MyImage.hpp" // MyImage wraps the Qt library image class namespace fs = boost::filesystem; class ImageCollection { public: ImageCollection(const char* path); private: const fs::path path_; deque<MyImage> instanceDeque_; } ImageCollection(const char* path) : path_(fs::is_directory(path) ? fs::complete(path) : fs::complete(path).parent_path()) /* Can I even do this? */ { /*** code in question ***/ fs::directory_iterator endIter; for(fs::directory_iterator dirIter(path_); dirIter != endIter; dirIter++) { instanceDeque_.push_back(MyImage(*dirIter)); } } The MyImage constructor throws a MyInvalidFileException when *dirIter is a fs::path to a non-image file. I'd like MyImage and ImageCollection to be immutable. Can I: try { instanceDeque_.push_back(MyImage(*dirIter)); } catch(const MyInvalidFileException& e) { // oops, tnx Nemanja T. // remember *dirIter in a list of non-Image files, to use later continue; } What happens when it throws? Is there a zombie MyImage or a zombie element left in the deque? Or is this actually the right way to do it? (i.e. the push_back() is aborted and no MyImage is created.) I currently have a messy workaround: // load up an empty MyImage, which I'd rather not do instanceDeque_.push_back(MyImage()); for(fs::directory_iterator dirIter(path_); dirIter != endIter; dirIter++) { MyImage& attemptImage = instanceDeque_.back(); bool success = attemptImage.loadPath(*dirIter); // "fill" the empty MyImage if (success) instanceDeque_.push_back(MyImage()); // prepare another empty MyImage } instanceDeque_.pop_back(); // discard the empty MyImage Where MyImage is initialized with a null QImage*, and loadPath() creates a QImage on the heap. This forces me to have null pointer checks everywhere. I figure there should be a way to have an instance of QImage if the file can be opened, and the construction to just fail if the file can't.
It depends on MyImage I guess. If there is an exception in the constructor of MyImage it should fail before you even reach the push_back method. This is because the constructor will be run before the push_back (which is logical, since it needs a value to pass the method). Thus if that step fails and exception is thrown, push_back will never be reached. Here are some pointers: C++ FAQ Lite: How can I handle a constructor that fails? C++ FAQ Lite: How should I handle resources if my constructors may throw exceptions?
1,929,037
1,929,049
using a class member to initialize a parent class
I have a basic_iostream derived class like this: class MyStream : public std::basic_iostream< char >, private boost::noncopyable { public: explicit MyStream( SomeUsefulData& data ) : buffer_( data ), std::basic_iostream< char >( &buffer_ ) { }; ~MyStream() { }; private: /// internal stream buffer MyStreamBuffer< char > buffer_; }; // class MyStream When I create an instance of it, though, I get a DataAbort exception. SomeUsefulData data; MyStream stream( data ); // <- Data Abort If, however I change MyStream to heap allocate the MyStreamBuffer, it works fine: class MyStream : public std::basic_iostream< char >, private boost::noncopyable { public: explicit MyStream( SomeUsefulData& data ) : std::basic_iostream< char >( new MyStreamBuffer< char >( data ) ) { }; ~MyStream() { delete rdbuf(); }; }; // class MyStream Is it wrong to use a class member to initialize a parent class? Thanks, PaulH
Direct base classes are always initialised first, no matter what order you put the initialisation statements in. If you turn on more compiler warnings, you should get a warning about this. Which means that yes, it is wrong to initialise a base class with a member, sorry!
1,929,094
1,929,559
reading from file certain lines at a time in c/c++
So i have a gui, designed using QT, c++. I have large amount of data in a text file that I would like to read in this fashion: load first 50 lines, when the user scrolls down load next 50 lines and so one. When the user scrolls up load previous 50 lines. Thank you.
The easiest solution would be to load the file into memory and manipulate it from there: std::vector<std::string> lines; std::string line; while(std::getline(file,line) { lines.push_back(line); } If the file is way to large. Then you need to build an index of the file that tells you exactly where each line starts. std::vector<std::streampos> index; index.push_back(file.tellg()); std::string line; while(std::getline(file,line) { index.push_back(file.tellg()); } file.setg(0); file.clear(); // Resets the EOF flag. Once you have your index. You can jump around the file and read any particular line. int jumpTo = 50; file.seekg(index[jumpTo]); // Jump to line 50. // // Read 50 lines. Do not read past the end // This will set the EOF flag and future reads will fail. for(int loop=0;loop < 50 && ((jumpTo + loop) < index.size());++loop) { std::string line; std::getline(file,line); }
1,929,112
1,929,730
design exercise preferably using mfc
i was told to design a paintbrush program in 2 variation , one that uses lots of space and little cpu and the other vice versa. the idea (as i was told- so not sure) is somehow to save the screen snapshots versus saving XOR maps (which i have no idea what it means) who represent the delta between the painting. can someone suggest a way or add links to related material ?
The obvious place to put the screen shots to use would be to implement an "undo" command. The simple, memory-hog method is to take a snapshot of the screen before each action. If the user hits "undo", you can restore the old screen. To save on memory space, you save only the difference between the two screens, by XORing them together. By itself, this doesn't actually save any space, but it sets all the unchanged pixels to 0. To save space, you'll then need to apply some sort of compression. Given that you can typically expect fairly large areas that are all zero, a run-length encoding will probably be quick and effective. For a run-length encoding, you'll typically turn a string of identical bytes into two bytes, the first holding the length of the run, and the second holding the value. For example, 75 zeros in a row would be encoded as 75 0. If you wanted to go a step further, instead of saving XORed bitmaps, you could look into using a metafile. A metafile records the actions taken at the level of Windows GDI calls, so (for example) if you drew a red 100x200 rectangle at 10, 100, it would record essentially that -- i.e. instead of the twenty thousand pixels, it would save an identifier saying what GDI function to execute, and the parameters to supply to that function. In a typical case, this might average around 15-20 bytes per "command" executed. At the same time, it does (often) involve more computation -- for example, if you draw a circle, re-running a metafile requires re-rastering the circle instead of just storing the bits it produced.
1,929,209
1,929,408
When overriding a virtual member function, why does the overriding function always become virtual?
When I write like this: class A { public: virtual void foo() = 0; } class B { public: void foo() {} } ...B::foo() becomes virtual as well. What is the rationale behind this? I would expect it to behave like the final keyword in Java. Add: I know that works like this and how a vtable works :) The question is, why C++ standard committee did not leave an opening to call B::foo() directly and avoid a vtable lookup.
The standard does leave an opening to call B::foo directly and avoid a table lookup: #include <iostream> class A { public: virtual void foo() = 0; }; class B : public A { public: void foo() { std::cout <<"B::foo\n"; } }; class C : public B { public: void foo() { std::cout <<"C::foo\n"; } }; int main() { C c; A *ap = &c; // virtual call to foo ap->foo(); // virtual call to foo static_cast<B*>(ap)->foo(); // non-virtual call to B::foo static_cast<B*>(ap)->B::foo(); } Output: C::foo C::foo B::foo So you can get the behaviour you say you expect as follows: class A { virtual void foo() = 0; // makes a virtual call to foo public: void bar() { foo(); } }; class B : public A { void foo() { std::cout <<"B::foo\n"; } // makes a non-virtual call to B::foo public: void bar() { B::foo(); } }; Now callers should use bar instead of foo. If they have a C*, then they can cast it to A*, in which case bar will call C::foo, or they can cast it to B*, in which case bar will call B::foo. C can override bar again if it wants, or else not bother, in which case calling bar() on a C* calls B::foo() as you'd expect. I don't know when anyone would want this behaviour, though. The whole point of virtual functions is to call the same function for a given object, no matter what base or derived class pointer you're using. C++ therefore assumes that if calls to a particular member function through a base class are virtual, then calls through derived classes should also be virtual.
1,929,380
1,929,421
Declaring the Unix flavour in C/C++
How do I declare in C/C++ that the code that is written is to be built in either HP-UX or Solaris or AIX?
I found that, a good way to figure this king of question, is, at least with gcc, to have this makefile: defs: g++ -E -dM - < /dev/null then, : $ make defs should output all the definitions you have available. So: $ make defs | grep -i AIX $ make defs | grep -i HP should give you the answer. Example for Linux: $ make defs | grep -i LINUX #define __linux 1 #define __linux__ 1 #define __gnu_linux__ 1 #define linux 1 Once you found the define you are looking for, you type at the beginning of your code: #if !(defined(HP_DEFINE) || defined(AIX_DEFINE) || defined(SOLARIS_DEFINE)) # error This file cannot be compiled for your plateform #endif
1,929,588
1,931,293
How to catch data-alignment faults on x86 (aka SIGBUS on Sparc)
Is it somehow possible to catch data-alignment faults even on i386? Maybe by setting a i386 specific machine register or something like that. On Solaris-Sparc I am receiving a SIGBUS in this case, but on i386 everything is fine. Environment: 32-bit application Ubuntu Karmic gcc/g++ v4.4.1 EDIT: Here is why I am asking this: our application crashes on Sol-Sparc with SIGBUS. For the purpose of debugging I would try to get a similar behavior on our i386 platform. our Sol-sparc machine is very slow, so compiling and debugging takes a lot of time there. And our i386 machine is unbelievable fast (8 cores, 32G memory). Even on i386 platforms there is a cost of performance on data-alignment faults. And therefore I would like to fix data-alignment faults wherever possible.
To expand on Vokuhila-Oliba's answer looking at the "SOF Mis-aligned pointers on x86." thread it seems that gcc can generate code with mis-aligned memory access. AFAIK you don't have any control over this. Enabling alignment checks on gcc compiled code would be a bad idea. You risk getting SIGBUS errors for good C code. ReEdited: Sorry about that
1,929,887
1,929,950
Is Pointer-to- " inner struct" member forbidden?
i have a nested struct and i'd like to have a pointer-to-member to one of the nested member: is it legal? struct InnerStruct { bool c; }; struct MyStruct { bool t; bool b; InnerStruct inner; }; this: MyStruct mystruct; //... bool MyStruct::* toto = &MyStruct::b; is ok but: bool MyStruct::* toto = &MyStruct::inner.c; is not. any idea? thanks Here are some details Yes it is &MyStruct::b and not mystruct::b; The code is from a custom RTTI/Property system. For each specified class we keep an array of "Property", including a Ptr-to-member It is used like this: //somewhere else in code... ( myBaseClassWithCustomRTTIPointer)->* toto = true;
Yes, it is forbidden. You are not the first to come up with this perfectly logical idea. In my opinion this is one of the obvious "bugs"/"omissions" in the specification of pointers-to-members in C++, but apparently the committee has no interest in developing the specification of pointers-to-members any further (as is the case with most of the "low-level" language features). Note that everything necessary to implement the feature in already there, in the language. A pointer to a-data-member-of-a-member is in no way different from a pointer to an immediate data member. The only thing that's missing is the syntax to initialize such a pointer. However, the committee is apparently not interested in introducing such a syntax. From the pure formal logic point of view, this should have been allowed in C++ struct Inner { int i; int j[10]; }; struct Outer { int i; int j[10]; Inner inner; }; Outer o; int Outer::*p; p = &Outer::i; // OK o.*p = 0; // sets `o.i` to 0 p = &Outer::inner.i; // ERROR, but should have been supported o.*p = 0; // sets `o.inner.i` to 0 p = &Outer::j[0]; // ERROR, but should have been supported o.*p = 0; // sets `o.j[0]` to 0 // This could have been used to implement something akin to "array type decay" // for member pointers p = &Outer::j[3]; // ERROR, but should have been supported o.*p = 0; // sets `o.j[3]` to 0 p = &Outer::inner.j[5]; // ERROR, but should have been supported o.*p = 0; // sets `o.inner.j[5]` to 0 A typical implementation of pointer-to-data-member is nothing more than just an byte-offset of the member from the beginning of the enclosing object. Since all members (immediate and members of members) are ultimately laid out sequentially in memory, members of members can also be identified by a specific offset value. This is what I mean when I say that the inner workings of this feature are already fully implemented, all that is needed is the initialization syntax. In C language this functionality is emulated by explicit offsets obtained through the standard offsetof macro. And in C I can obtain offsetof(Outer, inner.i) and offsetof(Outer, j[2]). Unfortunately, this capability is not reflected in C++ pointers-to-data-members.
1,930,017
1,930,023
Changeable return data type in C++
I'm writing a matrix class, and I want it to be able to store any different (numerical) data type - from boolean to long. In order to access the data I'm using the brackets operator. Is it possible to make that function return different data types depending on which data type is stored within the class. What's MORE is that I'm not entirely sure how I would STORE different data types within the class under the same variable name. It may well not be possible. The only way I can think to store the data as any type would be to store it as a void and store the type of data as an extra variable. however RETURNING as a void would cause problems, no? Because I would want to return as the data type I have stored in the function. Thanks.
Read up on templates.
1,930,081
1,930,163
C vs C++ code optimization for simple array creation and i/o
I've been trying to convince a friend of mine to avoid using dynamically allocated arrays and start moving over to the STL vectors. I sent him some sample code to show a couple things that could be done with STL and functors/generators: #include <iostream> #include <vector> #include <algorithm> #include <iterator> #define EVENTS 10000000 struct random_double { double operator() () { return (double)rand()/RAND_MAX; } }; int main(int argc, char **argv){ std::vector<double> vd (EVENTS); generate(vd.begin(), vd.end(), random_double()); copy(vd.begin(), vd.end(), std::ostream_iterator<double>(std::cout, "\n")); return 0; } His reply to this, although he feels it's more elegant, is that his own code is faster (by almost a factor of 2!) Here's the C code he replied with: #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <string.h> #define EVENTS 10000000 __inline double random_double() { return (double)rand()/RAND_MAX; } int main(int argc, char **argv){ unsigned int i; double *vd; vd = (double *) malloc(EVENTS*sizeof(double)); for(i=0;i<EVENTS;i++){ vd[i]=random_double(); } for(i=0;i<EVENTS;i++){ printf("%lf\n",vd[i]); } free(vd); return 0; } So I ran the simple timing test to see just what happens, and here's what I got: > time ./c++test > /dev/null real 0m14.665s user 0m14.577s sys 0m0.092s > time ./ctest > /dev/null real 0m8.070s user 0m8.001s sys 0m0.072s The compiler options, using g++ were: g++ -finline -funroll-loops. Nothing too special. Can anyone tell me why the C++/STL version is slower in this case? Where is the bottleneck, and will I ever be able to sell my friend on using STL containers?
Using printf: for (std::vector<double>::iterator i = vd.begin(); i != vd.end(); ++i) printf("%lf\n", *i); results are: koper@elisha ~/b $ time ./cpp > /dev/null real 0m4.985s user 0m4.930s sys 0m0.050s koper@elisha ~/b $ time ./c > /dev/null real 0m4.973s user 0m4.920s sys 0m0.050s Flags used: -O2 -funroll-loops -finline
1,930,343
1,930,377
How to know if the windowstation attached is interactive?
I am writing a program that can be loaded by another service (under our control), or by the logged-on user. The program needs to know if the window station is interactive in order to display dialogs. I know GetProcessWindowStation function, but this one returns a handle. Is there a way to find out?
The interactive window station is always winsta0. So you need to get the window station name to determine it. Here is some pseudo code: wchar_t buffer[256] = {0}; DWORD length = 0; GetUserObjectInformation(GetProcessWindowStation(), UOI_NAME, buffer, 256, &length); if (!lstrcmp(buffer, "winsta0")) { // Interactive! } From http://msdn.microsoft.com/en-us/library/ms687096(VS.85).aspx: The interactive window station, Winsta0, is the only window station that can display a user interface or receive user input
1,930,364
1,930,407
Install msvcr80d.dll
For reasons beyond my control, an app I am working on deploying needs to use the debug version of the Microsoft Visual C++ 2005 library. I tried to register the msvcr80d.dll with regsvr32.exe and it fails. Is there a work around to get the debug libraries to register?
this is the visual studio run time library debug version. besides being non optimized this dll contains additional code to detected various run time errors. you should not use that for distribution, in addition to being slower your application might display all sorts of ungainly debug message boxes. skip the shortcut and recompile a release version. This dll do not export DllRegisterServer and so cannot (and should not) be registered with regsvr32
1,930,399
1,930,536
shared_ptr, subscription, destructor
I'm using Boost/shared_ptr pointers throughout my application. When the last reference to an object is released, shared_ptr will delete the object for me. The objects in the application subscribes to events in a central location of the application, similar to the observer/subscriber pattern. In the object destructors, the object will unsubscribe itself from the list of subscriptions. The list of subscriptions is essentially just a list<weak_ptr<MyObject> >. What I want to do is something similar to this: Type::~Type() { Subscriptions::Instance()->Remove(shared_from_this()); } My problem here is that shared_from_this cannot be called in destructors so the above code will throw an exception. In my old implementation, the subscription list was just a list of pointers and then it worked. But I want to use weak_ptr references instead to reduce the risk of me screwing up memory by manual memory management. Since I rely on shared_ptr to do object deletion, there's no single place in my code where I can logically place a call to Unsubscribe. Any ideas on what to do in this situation?
You can destroy the objects via Subscription instance, then it'll automatically remove the pointers. You can forget about removing them from subscriptions -- the weak_ptr's wont be able to be locked anyway, then you can remove them. You can assign an unique ID to every object and then remove via the unique ID not the shared_ptr You can pass a normal pointer to Remove instead of a shared one -- it will serve as an "ID".
1,930,459
1,930,474
C++ delete - It deletes my objects but I can still access the data?
I have written a simple, working tetris game with each block as an instance of a class singleblock. class SingleBlock { public: SingleBlock(int, int); ~SingleBlock(); int x; int y; SingleBlock *next; }; class MultiBlock { public: MultiBlock(int, int); SingleBlock *c, *d, *e, *f; }; SingleBlock::SingleBlock(int a, int b) { x = a; y = b; } SingleBlock::~SingleBlock() { x = 222; } MultiBlock::MultiBlock(int a, int b) { c = new SingleBlock (a,b); d = c->next = new SingleBlock (a+10,b); e = d->next = new SingleBlock (a+20,b); f = e->next = new SingleBlock (a+30,b); } I have a function that scans for a complete line, and runs through the linked list of blocks deleting the relevant ones and reassigning the ->next pointers. SingleBlock *deleteBlock; SingleBlock *tempBlock; tempBlock = deleteBlock->next; delete deleteBlock; The game works, blocks are deleted correctly and everything functions as it is supposed to. However on inspection I can still access random bits of deleted data. If I printf each of the deleted singleblocks "x" values AFTER their deletion, some of them return random garbage (confirming the deletion) and some of them return 222, telling me even though the destructor was called the data wasn't actually deleted from the heap. Many identical trials show it is always the same specific blocks that are not deleted properly. The results: Existing Blocks: Block: 00E927A8 Block: 00E94290 Block: 00E942B0 Block: 00E942D0 Block: 00E942F0 Block: 00E94500 Block: 00E94520 Block: 00E94540 Block: 00E94560 Block: 00E945B0 Block: 00E945D0 Block: 00E945F0 Block: 00E94610 Block: 00E94660 Block: 00E94680 Block: 00E946A0 Deleting Blocks: Deleting ... 00E942B0, X = 15288000 Deleting ... 00E942D0, X = 15286960 Deleting ... 00E94520, X = 15286992 Deleting ... 00E94540, X = 15270296 Deleting ... 00E94560, X = 222 Deleting ... 00E945D0, X = 15270296 Deleting ... 00E945F0, X = 222 Deleting ... 00E94610, X = 222 Deleting ... 00E94660, X = 15270296 Deleting ... 00E94680, X = 222 Is being able to access data from beyond the grave expected? Sorry if this is a bit long winded.
Is being able to access data from beyond the grave expected? This is technically known as Undefined Behavior. Don't be surprised if it offers you a can of beer either.
1,930,610
1,930,870
Operator= in Boost::Python
If I have something like the following class class Foo { private: int _bar; public: Foo& operator=( const Foo& other ) { _bar = other._bar; return *this; } } Is there an easy way to export that functionality to python using boost::python? The documentation does not list and nice and easy .def( self = self ) I am not an expert with python so I do not even know if this is necessary to be honest. But I want this functionality in my python scripts, so I am posting the question just to make sure. Edit: here are the compiler errors when I do do .def( self = self ) .\src\Python.cpp(12) : error C2780: 'boost::python::class_<W> &boost::python::class_<W>::def(const char *,Fn,const A1 &,const A2 &,const A3 &)' : expects 5 arguments - 1 provided with [ W=Foo ] depends\common\include\boost/python/class.hpp(265) : see declaration of 'boost::python::class_<W>::def' with [ W=Foo ] .\src\Python.cpp(12) : error C2780: 'boost::python::class_<W> &boost::python::class_<W>::def(const char *,Fn,const A1 &,const A2 &)' : expects 4 arguments - 1 provided with [ W=Foo ] depends\common\include\boost/python/class.hpp(249) : see declaration of 'boost::python::class_<W>::def' with [ W=Foo ] .\src\Python.cpp(12) : error C2780: 'boost::python::class_<W> &boost::python::class_<W>::def(const char *,A1,const A2 &)' : expects 3 arguments - 1 provided with [ W=Foo ] depends\common\include\boost/python/class.hpp(242) : see declaration of 'boost::python::class_<W>::def' with [ W=Foo ] .\src\Python.cpp(12) : error C2780: 'boost::python::class_<W> &boost::python::class_<W>::def(const char *,F)' : expects 2 arguments - 1 provided with [ W=Foo ] depends\common\include\boost/python/class.hpp(233) : see declaration of 'boost::python::class_<W>::def' with [ W=Foo ] .\src\Python.cpp(12) : error C2784: 'boost::python::class_<W> &boost::python::class_<W>::def(const boost::python::def_visitor<Derived> &)' : could not deduce template argument for 'const boost::python::def_visitor<Derived> &' from 'boost::python::self_ns::self_t' with [ W=Foo ] depends\common\include\boost/python/class.hpp(223) : see declaration of 'boost::python::class_<W>::def' with [ W=Foo ]
I'm not an expert with Python, but in python the affectation with operator "=" has not the same meaning as in C++: a=b creates a new reference to the same internal object, so there is no point in exporting c++'s operator= into python interface. What you may do is creating a "clone" member function (implemented in terms of operator=) that will return a duplicate of the object. And import this function into Python. Alternatively, in Python, you can use a copy constructor: foo2 = Foo(foo1) (of course this constructor must be defined in the c++/python interface)
1,930,974
1,930,996
Newb C++ Class Problem
I am trying to get a grasp on pointers and their awesomeness as well as a better C++ understanding. I don't know why this wont compile. Please tell me what is wrong? I'm trying to initialize the pointer when an instance of the class is created. If I try with a normal int it works fine but when I tried to set it up with a pointer i get this in the console Running… Constructor called Program received signal: “EXC_BAD_ACCESS”. sharedlibrary apply-load-rules all Any assistance is appreciated greatly. Here is the code #include <iostream> using namespace std; class Agents { public: Agents(); ~Agents(); int getTenure(); void setTenure(int tenure); private: int * itsTenure; }; Agents::Agents() { cout << "Constructor called \n"; *itsTenure = 0; } Agents::~Agents() { cout << "Destructor called \n"; } int Agents::getTenure() { return *itsTenure; } void Agents::setTenure(int tenure) { *itsTenure = tenure; } int main() { Agents wilson; cout << "This employees been here " << wilson.getTenure() << " years.\n"; wilson.setTenure(5); cout << "My mistake they have been here " << wilson.getTenure() << " years. Yep the class worked with pointers.\n"; return 0; }
You don't ever create the int that the pointer points to, so the pointer is pointer to an area of memory that doesn't exist (or is used for something else). You can use new to get a block of memory from the heap, new returns the address of the memory location. itsTenure = new int; So now itsTenure holds the memory location you can dereference it to set its value. The changed constructor is as follows: Agents::Agents() { cout << "Constructor called \n"; itsTenure = new int; *itsTenure = 0; } But you must also remember to delete it using delete Agents::~Agents() { cout << "Destructor called \n"; delete itsTenure; }
1,931,126
1,931,171
Is it good practice to NULL a pointer after deleting it?
I'll start out by saying, use smart pointers and you'll never have to worry about this. What are the problems with the following code? Foo * p = new Foo; // (use p) delete p; p = NULL; This was sparked by an answer and comments to another question. One comment from Neil Butterworth generated a few upvotes: Setting pointers to NULL following delete is not universal good practice in C++. There are times when it is a good thing to do, and times when it is pointless and can hide errors. There are plenty of circumstances where it wouldn't help. But in my experience, it can't hurt. Somebody enlighten me.
Setting a pointer to 0 (which is "null" in standard C++, the NULL define from C is somewhat different) avoids crashes on double deletes. Consider the following: Foo* foo = 0; // Sets the pointer to 0 (C++ NULL) delete foo; // Won't do anything Whereas: Foo* foo = new Foo(); delete foo; // Deletes the object delete foo; // Undefined behavior In other words, if you don't set deleted pointers to 0, you will get into trouble if you're doing double deletes. An argument against setting pointers to 0 after delete would be that doing so just masks double delete bugs and leaves them unhandled. It's best to not have double delete bugs, obviously, but depending on ownership semantics and object lifecycles, this can be hard to achieve in practice. I prefer a masked double delete bug over UB. Finally, a sidenote regarding managing object allocation, I suggest you take a look at std::unique_ptr for strict/singular ownership, std::shared_ptr for shared ownership, or another smart pointer implementation, depending on your needs.
1,931,177
1,931,361
simplest way of recording 8 bit signed mono 16khz sound with alsa (in a way it's compatible with pulse)?
I'm totally lost, does anyone have a very simple example of how to record a sound using ALSA with c++? the only thing i need is the raw samples as signed bytes for feeding them to another part of my program. All the examples i found googling seem to have issues with PulseAudio or don't cover what i need.
Listing 4 in this article shows how to use the ALSA library API to capture audio.
1,931,218
1,931,231
C++ allocating dynamic memory in a function - newbie question
I'm investigating a memory leak and from what I see, the problem looks like this: int main(){ char *cp = 0; func(cp); //code delete[] cp; } void func(char *cp){ cp = new char[100]; } At the //code comment, I expected cp to point to the allocated memory, but it still is a null pointer meaning I never delete the memory. What am I doing wroing?
void func(char *cp){ cp = new char[100]; } In this function, char *cp is a "pointer being passed by copy" what means that they are pointing to the same memory address but they are not the same pointer. When you change the pointer inside, making it to point to somewhere else, the original pointer that has been passed will keep pointing to 0.
1,931,519
1,936,349
What are the best strategies and examples for teaching C++ memory management to early college students?
So I'm teaching a 2nd semester freshman level C++ course at a university in an upcoming semester. The students have used arrays (though only statically allocated) and have some notion of references and pointers (but probably not much). In general, they have not done a whole lot of dealing with dynamic memory allocation and management. I'm trying to sort of harness the global intelligence of the Stack Overflow community to see, in your collective experience, what have been the most effective ways to teach things like pointers and memory management to young computer science students? There are a lot of existing interesting StackOverflow posts on related topics: When teaching C, is it better to teach arrays before or after pointers? What are the barriers to understanding pointers and what can be done to overcome them? What is the real difference between Pointers and References? should we teach pointers in a "fundamentals of programming" course? What are the important notions in C that you did not learn from your teachers I certainly have my own set of opinions on how and what I teach, but I'm really interested in how my methodology differs from yours. Some sub-questions to consider (you're certainly not limited to these): What order would you teach things in and how would you relate the topics? "Ordinary" stack variables, followed by references, followed by pointers? Where do arrays fit in? When do you introduce the "new" keyword? etc. What visual aids have you seen used that best express these concepts? e.g. Drawing boxes for memory locations with values inside and variables/pointers as names with arrows pointing to the boxes? Are there any particular websites or textbooks you've read that just have outstanding descriptions? Are there particular code examples (e.g. a "swap" function) that tend to get the information across better than others? Teach on! Edit In an attempt to differentiate this from some of the links I've posted: Most of the previous SO links I've posted focus themselves very directly on pointers. Though pointers are an integral part of understanding memory behavior, I'm interested in the more overarching themes of how students understand how memory works in general. How do we best illustrate the differences between normal, pointer, and reference declaration? How do we emphasize the differences between global, stack, and heap variables? I think even getting into pushing return addresses onto the call stack is fair game too. What do you think the most important aspects of memory management are, how do you tie them all together, and how do you get this across in a coherent fashion?
Since I've always been a logical person I mostly would like to hear why you need dynamic allocation, not how it works and how the syntax is in a particular language. Start with static allocation, move on to cases when you hit the limitations of it, introduce dynamic allocations. Try to explain the different runtime scopes (compile time, runtime and the border cases). Explain which allocation techniques to use when. For heap allocation you could use shared memory situations and show that it is necessary to have a referencing mechanism, and introduce pointers through that. Show that you cannot determine the lifetime of the memory area easily with shared owner semantics and show different solutions (reference counting, manual deallocation etc) and describe why you need a tradeoff and not just one solution. Use other examples than only memory allocation (e.g RAII) to show that the techniques you show are not limited to memory but to any type of resources. I think that the key is to build the knowledge from the ground up, and not treat people like idiots (Blinky), but to keep in mind that many people have limited experience in the field, and need concrete examples to grasp why all the features are in place. There are many factors in play, and clearly defining the constraints so the students understand the problem formulation is probably the most important aspect of teaching this type of things. An example is worth a thousand words, and giving students concrete examples where the things they know so far doesn't cut it enables them to reason about the problem and eventually take the next step.
1,931,656
1,931,677
Does msvcrt.dll use a linear congruential generator for its rand() function?
I am trying to predict the output of a program that uses msvcrt's rand() function for generating the face of three dice. I believe the code is something like: dice[0] = rand() % 6 + 1; dice[1] = rand() % 6 + 1; dice[2] = rand() % 6 + 1;, and I was wondering if I could use a prediction program for linear congruential generators to predict the next numbers in the sequence.
See for yourself: C:\Program Files\Microsoft Visual Studio 8\VC\crt\src\rand.c (Or use %VCINSTALLDIR%\crt\src\rand.c if you're running from a VC command prompt.) (Assuming you have at least the standard version of VC. It's two lines. I'd post it, but not sure whether the license allows it.)
1,931,692
1,931,710
Any disadvantage if only using cpp files without separate header files?
I have found some threads that explain why C++ separates .cpp and .h files (e.g. here). I'd be interested to know if it causes any problem if I don't separate them. I don't want to share the object files, so what's the benefit of the separation on a small project? If it just slows down the compilation time, it's not a big deal in my opinion. I want to re-implement a Java program in C++, so to me it seems much easier to keep a class in one file only. Example: // Hello.cpp #ifndef HELLO_20091218 #define HELLO_20091218 #include <iostream> #include "Utils.cpp" class Hello { public: void start() { std::cout << Utils::nrand(100) << "\n"; // Utils and all other classes are written in a similar way } }; #endif There is a thing that troubles me. "Defining a member function inside the class asks the implementation to expand calls to it inline." So if I do like this, everything is marked inline implicitly. Will it cause a larger executable or any other disadvantages?
In C and C++ the smallest unit of compilation is the file. If you just don't use header files and include everything in your "main" file, everytime you change something your whole program would have to be recompilled. For larger applications this can be a very good argument for separation of header and implementation. Also if another part of your application would live in another binary executable and you wan't to reuse classes you are safe with header files while you will get alot of overhead without them. If you don't care about those things (You'll regret that.) there is no need in separate header files for you. About the inlining: The compiler will inline a lot of functions (sometimes even whole classes, so to speak) anyway, even if you don't ask it to do that. Inlining is generally a benefit for performance. There are corner cases (large size of the executable can resolut in slower execution) but those are fairly unusual.
1,932,174
1,932,188
How do i get visual studio 2008 to create a class for my MFC dialog resource?
I used to use VC 6 a while back and there was a simple to use "wizard" that would create a class out of a dialog created in the GUI editor. I am using 2008 professional and there seems to be no way to generate this. I can try to make it based on a template of previous projects, but it seems to me that is missing. Where did they bury that functionality?
You might want to take a look at this. :)
1,932,263
1,932,339
inline asm buffer loop
Ok here's my problem. I want to loop through a simple char buffer using inline asm and VC++; My agenda is to create a loop that reads information from memory as fast as physically possible heres my code char buffer[howmany]; memset(buffer,33,howmany); char arr = 0; __asm { MOV eax,seg buffer ;operand size conflict MOV eds,eax MOV ecx,[howmany] MOV ebx,ip MOV arr, ES::buffer[ecx] ;operand size conflict ;inline assembler syntax error in 'third operand' ;found 'bad token' LOOP ebx ;inline assembler syntax error in 'opcode'; found 'bad token' ; 'LOOP' : identifier is reserved word } I'm pretty new with assembly, but this seems right, but it doesn't work? I'm not sure why. Thanks in advance. Final Solution __asm { LEA esi, buffer MOV ecx,howmany buf_loop: mov eax, [esi] inc esi dec ecx jnz buf_loop }
First, there is no EDS, only DS. Even in 32-bit mode, the segment registers remain 16 bits. Second, unless you're working on an ancient system like a DOS extender, or something really unusual (a lot different from a typical desktop/server OS like Windows, Linux, OS/X, BSD, etc.) you shouldn't modify any segment registers in any case. Most current systems use a "flat" memory model, where the OS sets up all1 the segment registers with a base of 0 and a limit of the top of memory, so you never have any reason to modify any of them at all. Unfortunately, while it's easy to say your code is wrong, it's a bit harder to say what would be right -- you haven't said enough about what you want to do. Right now, it looks like you're copying from a buffer, but each time through the loop you're overwriting the value you wrote in the last iteration, so you might as well just copy the last word and be done. For looping through the buffer to accomplish much, you'd want to copy it to a destination buffer of the same (or larger) size: mov ecx, howmany mov esi, offset FLAT:source mov edi, offset FLAT:dest rep movsd As others have already pointed out, the operand for a loop instruction is a label, not a register. What they don't seem to have pointed out is that with modern CPUs (anything newer than the original Pentium) you usually want to avoid using the LOOP instruction at all. Just for the sake of argument, however, a loop to do the move like above would look like: mov ecx, howmany mov esi, offset FLAT:source mov edi, offset FLAT:dest move_loop: lodsd stosd loop move_loop For a modern CPU, it's usually better to use more, but simpler, instructions. ; same setup as above move_loop: mov eax, [esi] mov [edi], eax inc esi inc edi dec ecx jnz move_loop The other side of things is that in this case, it's unlikely to matter -- unless it all fits in cache, a block move like this will almost always be limited by the memory bandwidth -- moves don't get much faster, but to get the last little bit of improvement, you want to use SSE instructions/registers. Edit: One last detail. VC++ (among others) won't let you define a label inside an _asm block, so if you need a label, you do something like: _asm { mov ecx, howmany mov esi, offset FLAT:source mov edi, offset FLAT:dest } move_loop: _asm { lodsd stosd loop move_loop } 1Well, not all -- FS and possibly GS won't be this way, but CS, DS, ES and SS will be. You don't want to change any of them anyway (in fact, attempting to do so will normally just get your program shut down).
1,932,311
1,932,371
When to use the inline function and when not to use it?
I know that inline is a hint or request to the compiler and is used to avoid function call overheads. So, on what basis one can determine whether a function is a candidate for inlining or not? In which case one should avoid inlining?
Avoiding the cost of a function call is only half the story. do: use inline instead of #define very small functions are good candidates for inline: faster code and smaller executables (more chances to stay in the code cache) the function is small and called very often don't: large functions: leads to larger executables, which significantly impairs performance regardless of the faster execution that results from the calling overhead inline functions that are I/O bound the function is seldom used constructors and destructors: even when empty, the compiler generates code for them breaking binary compatibility when developing libraries: inline an existing function change an inline function or make an inline function non-inline: prior version of the library call the old implementation when developing a library, in order to make a class extensible in the future you should: add non-inline virtual destructor even if the body is empty make all constructors non-inline write non-inline implementations of the copy constructor and assignment operator unless the class cannot be copied by value Remember that the inline keyword is a hint to the compiler: the compiler may decide not to inline a function and it can decide to inline functions that were not marked inline in the first place. I generally avoid marking function inline (apart maybe when writing very very small functions). About performance, the wise approach is (as always) to profile the application, then eventually inline a set of functions representing a bottleneck. References: To Inline or Not To Inline [9] Inline functions Policies/Binary Compatibility Issues With C++ GotW #33: Inline Inline Redux Effective C++ - Item 33: Use inlining judiciously EDIT: Bjarne Stroustrup, The C++ Programming Language: A function can be defined to be inline. For example: inline int fac(int n) { return (n < 2) ? 1 : n * fac(n-1); } The inline specifier is a hint to the compiler that it should attempt to generate code for a call of fac() inline rather than laying down the code for the function once and then calling through the usual function call mechanism. A clever compiler can generate the constant 720 for a call fac(6). The possibility of mutually recursive inline functions, inline functions that recurse or not depending on input, etc., makes it impossible to guarantee that every call of an inline function is actually inlined. The degree of cleverness of a compiler cannot be legislated, so one compiler might generate 720, another 6 * fac(5), and yet another an un-inlined call fac(6). To make inlining possible in the absence of unusually clever compilation and linking facilities, the definition–and not just the declaration–of an inline function must be in scope (§9.2). An inline especifier does not affect the semantics of a function. In particular, an inline function still has a unique address and so has static variables (§7.1.2) of an inline function. EDIT2: ISO-IEC 14882-1998, 7.1.2 Function specifiers A function declaration (8.3.5, 9.3, 11.4) with an inline specifier declares an inline function. The inline specifier indicates to the implementation that inline substitution of the function body at the point of call is to be preferred to the usual function call mechanism. An implementation is not required to perform this inline substitution at the point of call; however, even if this inline substitution is omitted, the other rules for inline functions defined by 7.1.2 shall still be respected.
1,932,455
1,932,769
Ultra-light gzip compression implementation?
I'm searching for an ultra-light gzip compression/decompression library in C++ (something definitively lighter than zlib) on a libral (BSD, MIT, PD) license. Googling revealed many libraries, but either they are bloated (like GZ compression in Crypto++) or on a more restrictive license. It's hard to believe for me, that there's no lightweight free gz implementation... Preferably C++ (I need to have it in the form of a stream) but C would be ok.
Statically linked zlib is probably the lightest you can get, it also has a rather nice and generously permissive license. If it really isn't light enough, even considering what the linker will strip out, then chopping it down to size yourself might be a viable option.
1,932,654
1,932,666
Constructors accepting string reference. Bad idea?
It's considered a bad idea/bad design, have a class with a constructor accepting a reference, like the following? class Compiler { public: Compiler( const std::string& fileName ); ~Compiler(); //etc private: const std::string& m_CurrentFileName; }; or should I use values? I actually do care about performance.
If you used a value parameter in this case, you would have a reference in the class to a temporary, which would become invalid at some point in the future. The bad idea here is probably storing a reference as a member in the class. It is almost always simpler and more correct to store a value. And in that case, passing the constructor a const reference is the right thing to do. And as for performance, you should only care about this where it matters, which you can only find out by profiling your code. You should always write your code firstly for correctness, secondly for clarity and lastly for performance.
1,932,700
1,932,723
Copy constructor not called, but compiler complains that there's no
Given the following code: #include <boost/noncopyable.hpp> enum Error { ERR_OK=0 }; struct Filter : private boost::noncopyable { Filter() {} virtual ~Filter() {} virtual int filter(int* data) const = 0; }; struct SpecialFilter : public Filter, private boost::noncopyable { inline SpecialFilter(unsigned int min, unsigned int max) : min(min), max(max) {} virtual ~SpecialFilter() {} virtual int filter(int* data) const { // ... return ERR_OK; } unsigned int min; unsigned int max; }; struct AClass { AClass() {} AClass(const AClass& other) {} ~AClass() {} int specialFilter(int channel, int minThreshold, int maxThreshold) { // ... return filter(channel, SpecialFilter(123, 321)); } int filter(int channel, const Filter& filter) { // ... return ERR_OK; } }; My compiler (GCC 4.2) complains: - warning: direct base ‘boost::noncopyable_::noncopyable’ inaccessible in ‘SpecialFilter’ due to ambiguity - noncopyable.hpp: In copy constructor ‘Filter::Filter(const Filter&)’: - noncopyable.hpp:27: error: ‘boost::noncopyable_::noncopyable::noncopyable(const boost::noncopyable_::noncopyable&)’ is private - synthezised method first required here: [return filter(channel, SpecialFilter(123, 321));] But I don't call the copy constructor!
You never call copy constructor. The copy constructor is always called for you implicitly by the compiler. So you need to learn to recognize situations when it might be called. When you attach a const reference to a temporary object ... return filter(channel, SpecialFilter(123, 321)); ... the compiler has the right to perform a copy of the temporary object and require an accessible copy constructor (even if it won't be actually called). This is what is causing the problem in your case. In other words, when you make some type non-copyable, you also give up the possibility to attach const references to temporary objects of that type.
1,933,064
1,933,109
How to correctly initialize an object. [C++]
I mentioned in one of my earlier questions that I'm reading book "C++ Coding Standards" By Herb Sutter and Andrei Alexandrescu. In one of the chapters they are saying something like this: Always perform unmanaged resource acquisition, such as a new expression whose result is not immediately passed to a smart pointer constructor, in the constructor body and not in initializer lists. Does that mean that I should use construction of this form (providing that data_3_ has to be initialized with new): SomeClass(const T& value, const U& value2, const R& value3) : data_(value), data_2_(value2) { data_3_ = new value3; } instead of: SomeClass(const T& value, const U& value2, const R& value3) : data_(value), data_2_(value2), data_3_(new value3) // here data_3_ is initialized in ctor initialization list // as far as I understand that incorrect way according to authors { } Thanks in advance. P.S. And if that's what they mean why are they using term unmanaged resource acquisition? I always thought that this resources are "manually managed"? P.S 2. I'm sorry in advance if there are any formatting problems in this post - I have to admit - I absolutely detest the way of formatting on this forum.
That's because the constructor of SomeClass may throw an exception. In the situation you describe (ie not using a smart pointer), you have to free the resource in the destructor AND if the constructor of SomeClass throws an exceptions, with a try-catch block: SomeClass(const T& value, const U& value2, const R& value3):data_(value),data_2_(value2) : data_3_(NULL) { try { data_3_ = new value3; // more code here that may throw an exception } catch(...) { delete data_3_; throw; } } .. Which you can't do if an exception is thrown in the initialisation list. See this for further explanations.
1,933,113
1,933,140
C++ Windows - How to get process path from its PID
How can I retrieve a process's fully-qualified path from its PID using C++ on Windows?
Call OpenProcess to get a handle to the process associated with your PID. Once you have a handle to the process, call GetModuleFileNameEx to get its fully-qualified path. Don't forget to call CloseHandle when you're finished using the process handle. Here's a sample program that performs the required calls (replace 1234 with your PID): #include <windows.h> #include <psapi.h> // For access to GetModuleFileNameEx #include <tchar.h> #include <iostream> using namespace std; #ifdef _UNICODE #define tcout wcout #define tcerr wcerr #else #define tcout cout #define tcerr cerr #endif int _tmain(int argc, TCHAR * argv[]) { HANDLE processHandle = NULL; TCHAR filename[MAX_PATH]; processHandle = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, 1234); if (processHandle != NULL) { if (GetModuleFileNameEx(processHandle, NULL, filename, MAX_PATH) == 0) { tcerr << "Failed to get module filename." << endl; } else { tcout << "Module filename is: " << filename << endl; } CloseHandle(processHandle); } else { tcerr << "Failed to open process." << endl; } return 0; }
1,933,289
1,933,460
ESP Error when I call an API function?
platform : win32 , language : c++ I get this error when I call an imported function I declared: Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention. And this is the code I used: int LoadSongFromFile(int module); typedef int (CALLBACK* loadSongT)(LPCTSTR); //... HINSTANCE dllHandle = NULL; loadSongT loadSongPtr = NULL; dllHandle = LoadLibrary(L"miniFMOD.dll"); loadSongPtr = (loadSongT)GetProcAddress(dllHandle,"SongLoadFromFile"); int songHandle = loadSongPtr(L"C:\b.xm"); The function I'm trying to call is SongLoadFromFile which requires one argument (in C# it is string so I assume its LPCTSTR in C++) and returns an int value. Can somebody check what have I done wrong? P.S. songHandle gets a weird negative value of -858993460 This is how I can call that function from C# : [DllImport("MiniFMOD.dll")] public static extern int SongLoadFromFile(string name); P.S. 2 : Using *typedef int (__cdecl loadSongT)(char);* doesn't return an error but songHandle comes up as 0. miniFMOD.dll is an unmanaged library
I think the other people are misunderstanding the question. It seems to me that minifmod.dll is a native library that exports a function named SongLoadFromFile. The existing code that calls this is managed code (C#) that uses DllImport to call the function in the native DLL. From what little information I could gather by a few Google searches, it looks as though it should be declared as follows: typedef int (__cdecl * SongLoadFromFileT)(const char*); Importantly, it is __cdecl calling convention and it takes an ANSI string instead of a Unicode string. As an aside, I find it strange that I can't find ANYTHING on minifmod.dll other than a few forum posts on a Russian website and some SO questions from this guy. The only "legitimate" information I can find on minifmod is a small static library with similar functionality. I wonder if minifmod.dll is some kind of commercialized version of the static library; at least that would explain why there is not much public documentation about it. Ah, I found it; it is a Delph port of minifmod (http://www.cobans.net/minifmod.php).
1,933,406
1,944,153
date and time picker problem, can't reset date or time
I'm using a usoft date time picker control in a dialog box. I started by setting the format to "HH':'mm' 'ddddMMMdd','yyyy" and the current local date & time using DTM-SETSYSTEMTIME. If the user changes any field in the control, the program can not reset the date and time in the control using DTM-SETSYSTEMTIME although SendMessage returns a 1. As far as I can tell, the dialog box returns false (zero) to any notifications it receives concerning the control. The problem as described above is how I first became aware of it but it's actually much simpler. I did two DTM-SETSYSTEMTIME calls in a row and only the first one took affect. The second in the following example does not get put into effect even though the status is returned is 1. hwnd = GetDlgItem (hDlg, IDC_SUN_STAT_DATE_TIME); Status = SendMessage (hwnd, DTM_SETFORMAT,0,(LPARAM)"HH':'mm' 'ddddMMMdd','yyyy"); Status = SendMessage (hwnd, DTM_SETSYSTEMTIME,GDT_VALID, (LPARAM)&systimeTime); systimeTime.wHour += 2; Status = SendMessage (hwnd, DTM_SETSYSTEMTIME,GDT_VALID, (LPARAM)&systimeTime); It appears that only the first DTM-SETSYSTEMTIME is put into effect, following ones are ignored. What do I have to do to change/reset the date/time in the control? Or (more likely) what am I doing wrong?
I have cut and pasted your code into my own program in Visual C++ 6.0, and it works perfectly for me. If I comment out the second DTM_SETSYSTEMTIME, I get a time that is two hours earlier. There is something in the code you're not showing us. Edit: Since you've selected this answer, I might as well make it accurate. I've verified your comments with my own program. You're having a problem with the interactions of unexpected behaviors of the date/time picker: The SYSTEMTIME structure requires a full 4-digit year. The date/time picker does not indicate an error if you use DTM_SETSYSTEMTIME with an invalid SYSTEMTIME. Once you've set an invalid SYSTEMTIME, the date/time picker stops responding to further DTM_SETSYSTEMTIME messages. Furthermore it still returns as if it had processed the message properly.
1,934,052
1,934,095
Using type of function pointer as template argument
I'm trying to write a template which gets the type of a functionpointer as templateargument and the corresponding functionpointer as a function argument, so as a simplyfied example I'm doing this right now: int myfunc(int a) { return a; } template<typename T, typename Func> struct Test { typedef typeof(myfunc) Fun; static T MyFunc(T val, Func f) { return f(val); } }; int main(void) { std::cout<<Test<int, typeof(myfunc)>::MyFunc(5, myfunc)<<std::endl; } However this code instantly crashes. If I change the type of f to Fun it works perfectly. So what am I doing wrong and how can I get this to work? I'm using mingw under windows vista if that behaviour in case that behaviour is compiler dependent.
You don't really need the Test class for this scenario, and Why use the typeof function here? template< typename T, typename fT > T TestMyFunc( T t, fT f ) { return f(t); }; will do, and no fiddling with function pointer types: std::cout << TestMyFunc(5,myfunc) << std::endl; The template arguments are deduced automatically for functions!
1,934,071
1,934,253
sprintf(buf, "%.20g", x) // how large should buf be?
I am converting double values to string like this: std::string conv(double x) { char buf[30]; sprintf(buf, "%.20g", x); return buf; } I have hardcoded the buffer size to 30, but am not sure if this is large enough for all cases. How can I find out the maximum buffer size I need? Does the precision get higher (and therefore buffer needs to increase) when switching from 32bit to 64? PS: I cannot use ostringstream or boost::lexical_cast for performance reason (see this)
I have hardcoded the buffer size to 30, but am not sure if this is large enough for all cases. It is. %.20g specifies 20 digits in the mantissa. add 1 for decimal point. 1 for (possible) sign, 5 for "e+308" or "e-308", the worse case exponent. and 1 for terminating null. 20 + 1 + 1 + 5 + 1 = 28. Does the precision get higher (and therefore buffer needs to increase) when switching from 32bit to 64? No. A double is the same size in both architectures. If you declare your variables as long double, then you possibly have 1 more digit in the exponent "e+4092", which still fits in a 30 character buffer. But only on X86, and only on older processors. The long double is an obsolete 80 bit form of floating point value that was the native format of the 486 FPU. That FPU architecture didn't scale well and as since been discarded in favor of SSE style instructions where the largest possible floating point value is a 64 bit double. Which is a long way of saying a buffer of 30 characters will always be sufficient as long as you keep limiting the mantissa in your printout to 20 digits.
1,934,238
1,935,547
Problem with luabind::object dereferencing (simplified)
Using C++, lua5.1, luabind 0.7 Lua code: -- allocates near 8Mb of memory function fff() local t = {} for i = 1, 300000 do table.insert(t, i) end return t end C++ code: { luaL_dostring(lua_state, "return fff()"); luabind::object obj(luabind::from_stack(ls, -1)); } lua_gc(l_, LUA_GCCOLLECT, 0); // collect garbage Result: Lua still have a 8Mb allocated memory. Garbage collection ignores that table object. It has references anywhere? But where? That table deallocates only on program exit (when "lua_close" function called). How to solve this problem? Thank you.
If the code you use is exactly as posted, I'd say there's still a reference in the Lua stack. Try to insert a lua_pop(l, 1) between the luabind::object creation and the lua_gc call. On a side note, the current stable release of luabind is 0.8.1, there's 0.9-rc also; you might get more answers if you were using some current version (both here and from the luabind-users group)
1,934,282
1,934,311
C++ namespaces trobles
//portl.cpp namespace FAWN { namespace Sys{ class PortListner { .... Connecter::ConPtr _cur_con; - the main problem is here ... //con.cpp namespace FAWN { namespace Sys { class Connecter { ..... public: typedef boost::shared_ptr<Connecter> ConPtr; ... Moreover, portl.cpp file is included into some other "main" sourse file. And this "other-main" file includes con.cpp too. So if I include con.cpp to portl.cpp - I define Connecter twice (in portl and in main). If I do not include it, compilator doesn't know what Connecter::ConPtr (or FAWN::sys::Connecter::ConPtr) means and try to use it as defenition of method.
Put the class Connecter (which you should probably rename to Connector) into a header file (.h instead of .cpp) and add include guards into the file. That is, at the beginning of your con.h file, add lines #ifndef CON_H_INCLUDED #define CON_H_INCLUDED and at the very end, add the line #endif This way, even if you #include con.h twice, the second time it will not get read because the symbol CON_H_INCLUDED has been defined on the first time so the #ifndef-#endif pair hides the content. This is the common way in C++: put class declarations in .h files that get #included in .cpp files that then actually define the functions.
1,934,301
1,934,328
one question about initialization list in C++
I was told there are multiple situations in which initialization list must be used to for initialization. There are three cases 1) const member 2) reference 3) members without default constructors Is that right? Anyone would like elaborate this? Is there any other case I missed? Thanks!
...or POD class types or arrays of POD class types that directly or indirectly themselves contain a const-qualified member. But yes, yours are the main cases. For your (3), this only applies if there are user-declared constructors other than a default constuctor. If there are no user-declared constructors at all then the member can be default initialized if it isn't mentioned in the initializer list.
1,934,367
1,934,456
Indirectly calling non-const function on a const object
Given the following code: class foo; foo* instance = NULL; class foo { public: explicit foo(int j) : i(j) { instance = this; } void inc() { ++i; } private: int i; }; Is the following using defined behavior? const foo f(0); int main() { instance->inc(); } I'm asking because I'm using a class registry, and as I don't directly modify f it would be nice to make it const, but then later on f is modified indirectly by the registry. EDIT: By defined behavior I mean: Is the object placed into some special memory location which can only be written to once? Read-only memory is out of the question, at least until constexpr of C++1x. Constant primitive types for instance, are (often) placed into read-only memory, and doing a const_cast on it may result in undefined behavior, for instance: int main() { const int i = 42; const_cast<int&>(i) = 0; // UB }
Yes, it is undefined behavior, as per 7.1.5.1/4: Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior. Note that object's lifetime begins when the constructor call has completed (3.8/1).
1,934,602
1,934,648
One more time: LNK2005 (now ok) and LNK2019 (ok)
I know that all forums are full of such question, but I've tried few hooks, and they doesn't work (or I do them bad). So, I've got: main.cpp <- fawn.h <- connector.cpp (defenition) <- conncetor.h (declaration) <- portl.cpp (def) <- portl.h (dcl) <- connector.h with include guard (thanks to Igor Zevaka and jk), everything compiles, but doesn't link, saying "already defined in main.obj" about all funcs., no metter are they static or not. I've tryed already pulling the conncetor.h contents to connector.cpp, same way with portl.cpp (there was #include "connector.h" in it). Thanks beforehand.
Does fawn.h include connector.cpp? (or do I read it wrong?) If so this is your error. Now connector.cpp (itself) has a function bla() and main.cpp has same function because it includes (read: copy-pasted in) connector.cpp. And you are trying to link them together. EDIT: For the last error make sure FAWN::Sys::Connecter::getSocket(void) is implemented somewhere (and that cpp file it is in is linked in). Looks like it is just missing.
1,934,762
1,934,770
Odd behavior when passing copy via '*this'
Recently I implemented a 'Paused' screen in my game. Since I wanted it to be a separate game state, I needed to somehow save the data from when the player paused the game to when they re-enter. However, when states are switched the pointer to the previous state is deleted. Thus, I decided for the Paused constructor to take a copy of the Level ( a class ), so that it could hold it until the user decided to resume. Then it would set the next state using that Level that was copied. The code to set the next state to paused looks like this... p_Game->SetNextState( new Paused( *this )); Unfortunately, when I enter the command to pause, the program crashes. I debugged it until I found that the problem seems to have something to do with a pointer to the boss that the Level class holds as a member variable. The way the game loop operates, it first handles events, then runs logic, then renders, and if a state has been set, it updates to the new one. The program crashes whenever an operation is done on the Boss pointer, which occurs during the run logic and rendering portion of Level, but before the game state is switched to paused. Note, this Boss pointer is allocated upon Level construction, and deallocated upon destruction. Could passing a copy of the current Level somehow mess with a pointer being held in a member variable?
Did you define an actual copy constructor that deep-copies the Level object, creating a new Boss object, et cetera? Or did you just use the one automatically provided by the compiler, which is a shallow copy? If the latter, that's where you're running into issues: because it's a shallow copy, the pointer for the Boss object in the new level is pointing to the same Boss object as in the level you're copying... but that Boss object is getting deallocated when your original level object (not the copy, but the one you made a copy of) destructs. Even if you wrote your own constructor, you may still need to make sure that you're doing a deep copy instead of a shallow copy. More on copy constructors: link
1,934,898
1,935,084
Python, Threads, the GIL, and C++
Is there some way to make boost::python control the Python GIL for every interaction with python? I am writing a project with boost::python. I am trying to write a C++ wrapper for an external library, and control the C++ library with python scripts. I cannot change the external library, only my wrapper program. (I am writing a functional testing application for said external library) The external library is written in C and uses function pointers and callbacks to do a lot of heavy lifting. Its a messaging system, so when a message comes in, a callback function gets called, for example. I implemented an observer pattern in my library so that multiple objects could listen to one callback. I have all the major players exported properly and I can control things very well up to a certain point. The external library creates threads to handle messages, send messages, processing, etc. Some of these callbacks might be called from different processes, and I recently found out that python is not thread safe. These observers can be defined in python, so I need to be able to call into python and python needs to call into my program at any point. I setup the object and observer like so class TestObserver( MyLib.ConnectionObserver ): def receivedMsg( self, msg ): print("Received a message!") ob = TestObserver() cnx = MyLib.Conection() cnx.attachObserver( ob ) Then I create a source to send to the connection and the receivedMsg function is called. So a regular source.send('msg') will go into my C++ app, go to the C library, which will send the message, the connection will get it, then call the callback, which goes back into my C++ library and the connection tries to notify all observers, which at this point is the python class here, so it calls that method. And of course the callback is called from the connection thread, not the main application thread. Yesterday everything was crashing, I could not send 1 message. Then after digging around in the Cplusplus-sig archives I learned about the GIL and a couple of nifty functions to lock things up. So my C++ python wrapper for my observer class looks like this now struct IConnectionObserver_wrapper : Observers::IConnectionObserver, wrapper<Observers::IConnectionObserver> { void receivedMsg( const Message* msg ) { PyGILState_STATE gstate = PyGILState_Ensure(); if( override receivedMsg_func = this->get_override( "receivedMsg" ) ) receivedMsg_func( msg ); Observers::IConnectionObserver::receivedMsg( msg ); PyGILState_Release( gstate ); } } And that WORKS, however, when I try to send over 250 messages like so for i in range(250) source.send('msg") it crashes again. With the same message and symptoms that it has before, PyThreadState_Get: no current thread so I am thinking that this time I have a problem calling into my C++ app, rather then calling into python. My question is, is there some way to make boost::python handle the GIL itself for every interaction with python? I can not find anything in the code, and its really hard trying to find where the source.send call enters boost_python :(
I found a really obscure post on the mailing list that said to use PyEval_InitThreads(); in BOOST_PYTHON_MODULE and that actually seemed to stop the crashes. Its still a crap shoot whether it the program reports all the messages it got or not. If i send 2000, most of the time it says it got 2000, but sometimes it reports significantly less. I suspect this might be due to the threads accessing my counter at the same time, so I am answering this question because that is a different problem. To fix just do BOOST_PYTHON_MODULE(MyLib) { PyEval_InitThreads(); class_ stuff
1,934,961
1,934,976
Why does copy constructor call other class' default constructor?
I was wondering why an error like this would occur. no matching function for call to 'Foo::Foo()' in code for a copy constructor? Assume Foo is just an object with normal fields ( no dynamically allocated memory, etc. ), and the only constructor it has defined is a constructor that takes one argument. I didn't even know the constructor needed to be considered though. If the code says something like bar = thing.bar; // and bar is of Foo type, with the specifications described above, shouldn't it just generate a shallow copy and be done with it? Why does a default constructor need to be invoked?
If you don't define a constructor, the compiler will generate a default constructor, however if you do define a constructor (Like a copy constructor) the compiler won't generate the default constructor, so you need to define that constructor too.
1,935,138
1,935,167
What is the difference between POSIX sockets and BSD sockets?
Could someone please explain the differences between POSIX sockets and BSD sockets?
As reported in http://www.openss7.org/papers/strsock/sockimp.pdf: Berkeley Sockets. Sockets uses the BSD interface that was developed by BBN for the TCP/IP protocol suite under DARPA contract on 4.1aBSD and released in 4.2BSD. BSD Sockets provides a set of primary API functions that are typically implemented as system calls. The BSD Sockets interface is non-standard, operated differently from the POSIX interface in subtle ways, and is now deprecated in favour of the POSIX/SUS standard Sockets interface. POSIX Sockets. Sockets were standardized by X/Open, later the OpenGroup, and IEEE in the POSIX standardization process. They appear in XNS 5.2 [XNS99], SUSv1 [SUS95], SUSv2 [SUS98] and SUSv3 [SUS03]. POSIX/SUS Sockets is now the common application environment for accessing networking, deprecating the XTI for TCP/IP networking applications.
1,935,139
1,935,670
Using std::map<K,V> where V has no usable default constructor
I have a symbol table implemented as a std::map. For the value, there is no way to legitimately construct an instance of the value type via a default constructor. However if I don't provide a default constructor, I get a compiler error and if I make the constructor assert, my program compile just fine but crashes inside of map<K,V>::operator [] if I try to use it to add a new member. Is there a way I can get C++ to disallow map[k] as an l-value at compile time (while allowing it as an r-value)? BTW: I know I can insert into the map using Map.insert(map<K,V>::value_type(k,v)). Edit: several people have proposed solution that amount to altering the type of the value so that the map can construct one without calling the default constructor. This has exactly the opposite result of what I want because it hides the error until later. If I were willing to have that, I could simply remove the assert from the constructor. What I Want is to make the error happen even sooner; at compile time. However, it seems that there is no way to distinguish between r-value and l-value uses of operator[] so it seems what I want can't be done so I'll just have to dispense with using it all together.
You can't make the compiler differentiate between the two uses of operator[], because they are the same thing. Operator[] returns a reference, so the assignment version is just assigning to that reference. Personally, I never use operator[] for maps for anything but quick and dirty demo code. Use insert() and find() instead. Note that the make_pair() function makes insert easier to use: m.insert( make_pair( k, v ) ); In C++11, you can also do m.emplace( k, v ); m.emplace( piecewise_construct, make_tuple(k), make_tuple(the_constructor_arg_of_v) ); even if the copy/move constructor is not supplied.
1,935,266
1,937,882
Boost Libraries Support for MS VC++ 10.0
Friends I have been using Microsoft Visual C++ 2010 Express edition and also downloaded the Boost Libraries for Windows and I would want to have Boost linked with VC++ so that I can run programs that involves Boost libraries in VC++. Please provide some inputs on Boost with VC++ Thank you
Now that you have download and extract the whole library to a folder, c:\boost. open the visual studio 2010 commandline window from the Start Menu, so that all VS2010 environments are pre-set for you. navigate to c:\boost Run bjam.exe, and wait. Alternatively, you can save the following 3 lines into a a file build.bat(as I do) bjam.exe link=static runtime-link=static threading=multi --layout=versioned stage bjam.exe link=static runtime-link=shared threading=multi --layout=versioned stage bjam.exe link=shared runtime-link=shared threading=multi --layout=versioned stage and run build.bat, after the build, all libs are in .\stage
1,935,274
1,935,303
count number of files with a given extension in a directory - C++?
Is it possible in c++ to count the number of files with a given extension in a directory? I'm writing a program where it would be nice to do something like this (pseudo-code): if (file_extension == ".foo") num_files++; for (int i = 0; i < num_files; i++) // do something Obviously, this program is much more complex, but this should give you the general idea of what I'm trying to do. If this is not possible, just tell me. Thanks!
There is nothing in the C or C++ standards themselves about directory handling but just about any OS worth its salt will have such a beast, one example being the findfirst/findnext functions or readdir. The way you would do it is a simple loop over those functions, checking the end of the strings returned for the extension you want. Something like: char *fspec = findfirst("/tmp"); while (fspec != NULL) { int len = strlen (fspec); if (len >= 4) { if (strcmp (".foo", fspec + len - 4) == 0) { printf ("%s\n", fspec); } } fspec = findnext(); } As stated, the actual functions you will use for traversing the directory are OS-specific. For UNIX, it would almost certainly be the use of opendir, readdir and closedir. This code is a good starting point for that: #include <dirent.h> int len; struct dirent *pDirent; DIR *pDir; pDir = opendir("/tmp"); if (pDir != NULL) { while ((pDirent = readdir(pDir)) != NULL) { len = strlen (pDirent->d_name); if (len >= 4) { if (strcmp (".foo", &(pDirent->d_name[len - 4])) == 0) { printf ("%s\n", pDirent->d_name); } } } closedir (pDir); }
1,935,331
1,935,334
How can I check that I didn't break anything when refactoring?
I'm about to embark on a bout of refactoring of some functions in my code. I have a nice amount of unit tests that will ensure I didn't break anything, but I'm not sure about the coverage they give me. Are there any tools that can analyze the code and see that the functionality remains the same? I plan to refactor some rather isolated code, so I don't need to check the entire program, just the areas that I'm working on. For context, the code I'm working on is in C/C++, and I work in Linux with GCC and VIM.
gcov will give you coverage information for your unit tests. It's difficult to answer your question in an accurate manner without knowing more about the refactorings you plan to perform. An advice one might give is to proceed with small iterations instead of refactoring lots and lots of parts of your code base and then realize everything breaks. Reference: The GNU Coverage Tool - A Brief Tutorial
1,935,371
1,935,417
I get an exception if I leave the program running for a while
Platform : Win32 Language : C++ I get an error if I leave the program running for a while (~10 min). Unhandled exception at 0x10003fe2 in ImportTest.exe: 0xC0000005: Access violation reading location 0x003b1000. I think it could be a memory leak but I don't know how to find that out. Im also unable to 'free()' memory because it always causes (maybe i shouldn't be using free() on variables) : Unhandled exception at 0x76e81f70 in ImportTest.exe: 0xC0000005: Access violation reading location 0x0fffffff. at that stage the program isn't doing anything and it is just waiting for user input dllHandle = LoadLibrary(L"miniFMOD.dll"); playSongPtr = (playSongT)GetProcAddress(dllHandle,"SongPlay"); loadSongPtr = (loadSongT)GetProcAddress(dllHandle,"SongLoadFromFile"); int songHandle = loadSongPtr("FILE_PATH"); // ... {just output , couldn't cause errors} playSongPtr(songHandle); getch(); // that is where it causes an error if i leave it running for a while Edit 2: playSongPtr(); causes the problem. but i don't know how to fix it
I think it's pretty clear that your program has a bug. If you don't know where to start looking, a useful technique is "divide and conquer". Start with your program in a state where you can cause the exception to happen. Eliminate half your code, and try again. If the exception still happens, then you've got half as much code to look through. If the exception doesn't happen, then it might have been related to the code you just removed. Repeat the above until you isolate the problem. Update: You say "at that stage the program isn't doing anything" but clearly it is doing something (otherwise it wouldn't crash). Is your program a console mode program? If so, what function are you using to wait for user input? If not, then is it a GUI mode program? Have you opened a dialog box and are waiting for something to happen? Have you got any Windows timers running? Any threads? Update 2: In light of the small snippet of code you posted, I'm pretty sure that if you try to remove the call to the playSongPtr(songHandle) function, then your problem is likely to go away. You will have to investigate what the requirements are for "miniFMOD.dll". For example, that DLL might assume that it's running in a GUI environment instead of a console program, and may do things that don't necessarily work in console mode. Also, in order to do anything in the background (including playing a song), that DLL probably needs to create a thread to periodically load the next bit of the song and queue it in the play buffer. You can check the number of threads being created by your program in Task Manager (or better, Process Explorer). If it's more than one, then there are other things going on that you aren't directly controlling.
1,935,447
1,935,467
do sem_wating threads cause more switching
I have several threads which act as backup for the main one spending most of their life blocked by sem_wait(). Is it OK to keep them or is it better to spawn new threads only when they need to do actual work? Does kernel switch to threads waiting on sem_wait() and "waste" CPU cycles? Thanks.
No, blocked threads are never switched in for any common thread library and operating system (it would be an extremely badly designed one where they were). But they will still use memory, of course.
1,935,455
1,936,318
getopt for Visual Studio CRT?
Is there an equivalent to getopt() in the visual studio CRT? Or do I need to get it and compile it with my project? Edit clarification getopt is a utility function in the unix/linux C Run Time library for common command line parsing chores i.e. parsing arguments of the form -a -b -f someArg etc'
You can use the getopt implementation from the GNU C library. It's licensed under the LGPL, which should be compatible with most software projects. See the file posix/getopt.c in the source distribution.
1,935,777
1,935,832
C++ design: How to cache most recent used
We have a C++ application for which we try to improve performance. We identified that data retrieval takes a lot of time, and want to cache data. We can't store all data in memory as it is huge. We want to store up to 1000 items in memory. This items can be indexed by a long key. However, when the cache size goes over 1000, we want to remove the item that was not accessed for the longest time, as we assume some sort of "locality of reference", that is we assume that items in the cache that was recently accessed will probably be accessed again. Can you suggest a way to implement it? My initial implementation was to have a map<long, CacheEntry> to store the cache, and add an accessStamp member to CacheEntry which will be set to an increasing counter whenever an entry is created or accessed. When the cache is full and a new entry is needed, the code will scan the entire cache map and find the entry with the lowest accessStamp, and remove it. The problem with this is that once the cache is full, every insertion requires a full scan of the cache. Another idea was to hold a list of CacheEntries in addition to the cache map, and on each access move the accessed entry to the top of the list, but the problem was how to quickly find that entry in the list. Can you suggest a better approach? Thankssplintor
Have your map<long,CacheEntry> but instead of having an access timestamp in CacheEntry, put in two links to other CacheEntry objects to make the entries form a doubly-linked list. Whenever an entry is accessed, move it to the head of the list (this is a constant-time operation). This way you will both find the cache entry easily, since it's accessed from the map, and are able to remove the least-recently used entry, since it's at the end of the list (my preference is to make doubly-linked lists circular, so a pointer to the head suffices to get fast access to the tail as well). Also remember to put in the key that you used in the map into the CacheEntry so that you can delete the entry from the map when it gets evicted from the cache.
1,935,953
1,936,049
Error linking with gcc
I've try to compile this code: #include <iostream> #include <cstdlib> using namespace std; #define ARRAY_TAM 2 typedef int (*operacion)(int, int); typedef const char* (*Pfchar)(); int suma(int, int); int resta(int, int); const char* descrSuma(); const char* descrResta(); const char* simbSuma(); const char* simbResta(); class OP { private: public: operacion op; Pfchar descr; Pfchar simb; }; int main (int argv, char *argc[]) { OP ArrayOP[ARRAY_TAM]; ArrayOP[0].op = suma; ArrayOP[0].descr = descrSuma; ArrayOP[1].op = resta; ArrayOP[1].descr = descrResta; int op1, op2; unsigned int i; char opcion; bool fin = false; while (fin != true) { cout << "CALCULADORA" << "\n"; cout << "===========" << "\n"; for (i = 0; (i < ARRAY_TAM); i++) { cout << i+1; cout << ".- "; cout << ArrayOP[i].descr() << "\n"; } cout << i+1 << ".- " << "Salir" << endl; cout << "Opcion: "; cin >> opcion; opcion = atoi(&opcion); opcion--; cout << (int)opcion << endl; if ((opcion >= 0) && (opcion < ARRAY_TAM)) { cout << "Operando 1: "; cin >> op1; cout << "Operando 2: "; cin >> op2; cout << "Resultado: op1 " << ArrayOP[opcion].simb() << " op2 = " << ArrayOP[opcion].op(op1, op2); } else if (opcion == ARRAY_TAM) { fin = true; } } return 0; } int suma (int op1, int op2) {return op1 + op2;} int resta (int op1, int op2) {return op1 - op2;} const char* descrSuma() {return "Suma";} const char* descrResta() {return "Resta";} const char* simbSuma() {return "+";} const char* simbResta() {return "-";} An it works, but I have a lot of problems linking with gcc with debbugging symbols and it doesn't link :-( Need Help! Large linker error: facon@facon-laptop:~/Windows - Mis documentos/Prog/C/Ejercicios/pedirentero$ g++ -o main main.o main.o: In function `_start': /build/buildd/eglibc-2.10.1/csu/../sysdeps/i386/elf/start.S:65: multiple definition of `_start' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crt1.o:/build/buildd/eglibc-2.10.1/csu/../sysdeps/i386/elf/start.S:65: first defined here main.o:(.rodata+0x0): multiple definition of `_fp_hw' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crt1.o:(.rodata+0x0): first defined here main.o: In function _fini': (.fini+0x0): multiple definition of_fini' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crti.o:(.fini+0x0): first defined here main.o:(.rodata+0x4): multiple definition of `_IO_stdin_used' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crt1.o:(.rodata.cst4+0x0): first defined here main.o: In function __data_start': (.data+0x0): multiple definition of__data_start' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crt1.o:(.data+0x0): first defined here main.o: In function __data_start': (.data+0x4): multiple definition of__dso_handle' /usr/lib/gcc/i486-linux-gnu/4.4.1/crtbegin.o:(.data+0x0): first defined here main.o: In function _init': (.init+0x0): multiple definition of_init' /usr/lib/gcc/i486-linux-gnu/4.4.1/../../../../lib/crti.o:(.init+0x0): first defined here /usr/lib/gcc/i486-linux-gnu/4.4.1/crtend.o:(.dtors+0x0): multiple definition of `DTOR_END' main.o:(.dtors+0x4): first defined here /usr/bin/ld: warning: Cannot create .eh_frame_hdr section, --eh-frame-hdr ignored. /usr/bin/ld: error in main.o(.eh_frame); no .eh_frame_hdr table will be created. collect2: ld returned 1 exit status PD: Edited.
You write "... it works", but then you write "... problems with linking". I am little bit confused with this question, because: If there are problems with linking then it doesn't work ... But if it works, then you don't have problems with linking... So I guess that you mean: "it compiles, but there are linking errors" ? If that's the case, then you could try g++ -g main.cpp -o main instead of gcc -g main.cpp -o main EDIT: ... and do not mention main.o on the command line =;) EDIT: if that all doesn't help - maybe there is something wrong with your g++/gcc installation? on ubuntu please try sudo aptitude install build-essential
1,935,964
1,965,935
basic playback with programmatically created windows media player
I was trying to "just quickly integrate" the Windows Media Player via COM to play single files from the local file system or http sources - but due to the sparse documentation and online resources to its usage when not embedding into some kind of an Ole container, i couldn't get that supposedly trivial use-case to work. Initialization etc. works fine, but actually playing some file always fails. Example code, starting with initialization (error handling stripped, basically translated from the C# example at MSDN, executed on the main thread): CComPtr<IWMPPlayer> player; player.CoCreateInstance(__uuidof(WindowsMediaPlayer), 0, CLSCTX_INPROC_SERVER); CComQIPtr<IWMPCore3> core(player); CComPtr<IWMPControls> controls; core->get_controls(&controls); CComPtr<IWMPPlaylist> playlist; core->get_currentPlaylist(&playlist); CComBSTR path("c:\\bar.mp3"); // alternatively http://foo/bar.mp3 The first approach to play something gives "command not available": core->put_url(path); // ... waiting after that for WMP to load doesn't make a difference controls->play(); // returns 0x000D1105 - NS_S_WMPCORE_COMMAND_NOT_AVAILABLE The second approach only produces S_OKs, but nothing is actually played: CComPtr<IWMPMedia> media; core->newMedia(path, &media); playlist->appendItem(media); controls->playItem(media); // returns S_OK, but doesn't play Another thing i noted is that core->get_playState() always returns wmposMediaOpening, no matter how long i wait. I've stumbled upon one thread that suggests multi-threading might not work properly with WMP and this code runs in a multi-threaded apartment. Might that be the problem? If not, what else could be preventing WMP from playing the files? Notable background: The WMP instance is created in a DLL with a browser as the host-process. Update: Trying plain DirectShow, which WMP should be using itself, exhibits a more specific problem - see the question for that.
After further investigation, it turned out that this was actually caused by a VS2005 workaround for VS2008s AtlSetPerUserRegistration() which was always active - but should have been only for the contained COM servers registration/unregistration. The workaround overrides HKEY_LOCAL_MACHINE with HKEY_CURRENT_USER, which obviously results in quite some components failing if they are created in-process.
1,936,001
1,936,007
running external .exe on button click c++. How to?
I am creating a simple GUI in C++ which have few buttons in it. I want to launch some external .exe files when i click on these buttons. What's the code to achieve this?
In its simplest form: system("c:\\path\\to\\binary.exe");. If you need more control, use something like CreateProcess().
1,936,013
1,936,057
How can I create a std::vector with 64 bit indexes?
I want to create a big std::vector so operator[] should receive long long rather than unsigned int, I tried writing my own allocator: template <typename T> struct allocator64 : std::allocator<T> { typedef long long difference_type; typedef unsigned long long size_type; }; But when I try the following: long long n = 5; std::vector<int, allocator64<int> > vec(n); vec[n-1] = 2; I get the following warning for the second and third line: warning C4244: 'argument' : conversion from '__int64' to 'unsigned int', possible loss of data What am I missing? I thought the type for operator[] and for the size constructor should come from allocator::size_type. I'm using VS9 (2008).
Maybe the STXXL library can help: STXXL provides an STL replacement using an abstraction layer to storage devices to allow for the optimal layout of data structures. This allows for multi-terabyte datasets to be held and manipulated in standard C++ data structures, whilst abstracting the complexity of managing this behaviour efficiently. STXXL utilises multi-disk I/O to speed up I/O bound calculations. STXXL has been developed at the University of Karlsruhe.
1,936,266
1,936,280
Problem with boost memory mapped files: they go to disk instead of RAM
I am trying to understand how Boost memory mapped files work. The following code works, it does what it is supposed to do, but the problem is that the file it generates is stored on disk (in the same directory of the executable) instead of memory. Maybe there is a flag to set somewhere, but I could not find it... Thanks in advance for any info! #include <iostream> #include <string> #include <cstring> #include <boost/iostreams/device/mapped_file.hpp> using std::cout; using std::endl; int main(int argc, char** argv) { const int blockSize = 64; bool writer = false; if(argc > 1) { if(!strcmp(argv[1], "w")) writer = true; } boost::iostreams::mapped_file_params params; params.path = "map.dat"; // params.length = 1024; // default: all the file params.new_file_size = blockSize; if(writer) { cout << "Writer" << endl; params.mode = std::ios_base::out; } else { cout << "Reader" << endl; params.mode = std::ios_base::in; } boost::iostreams::mapped_file mf; mf.open(params); if(writer) { char *block = mf.data(); strcpy(block, "Test data block...\0"); cout << "Written: " << block << endl; } else { cout << "Reading: " << mf.const_data() << endl; } mf.close(); return 0; } /* Compiler options: -Wall -I$(PATH_BOOST_INCLUDE) -ggdb Linker options: -L$(PATH_BOOST_LIBS) -lboost_iostreams-mt -lboost_system-mt -lboost_filesystem-mt -DBOOST_FILESYSTEM_NO_DEPRECATED */ Compiler used: gcc 4.2.1 Boost 1.41.0 OS: MacOS X 10.6.2
Memory mapping maps disk files into memory. There has to be a file on disk for this to happen! Edit: From your comments, it sounds like you want to use shared memory - see http://www.boost.org/doc/libs/1_41_0/doc/html/interprocess/quick_guide.html
1,936,382
1,936,434
What is a good way to add MFC gui to a Win32 C++ command line application?
We have a command line application that could benefit from a GUI. We want to add some plotting functionality and have identified a plotting library that uses MFC. Initially we developed a separate app, but we'd rather have the GUI in the same process space. I was thinking of possibly a GUI in an MFC DLL that could be hosted in the production app AND in a testing app. The questions are: What are the steps necessary to add an MFC GUI to a win32 command line app Is it possible to make a GUI in an MFC DLL and how can it be done? (so that different apps can reuse the same GUI) EDIT I should add that this is an unmanaged app (and needs to stay that way - it needs to be highly performant, makes extensive use of templates, boost, custom allocators, internally developed thread serialization, etc) RESULTS: Nick D's answer worked great - especially the follow-up link in his comment with the details about a regular MFC DLL. Note that we will be using Qt for the next iteration. Modifying our build environment and getting used to a a new framework was just too much this time around.
You can call/reuse GUI code in a dll. (I even use Delphi forms in my C++ projects) A very simple dll example: // The DLL exports foo() function void foo() { AFX_MANAGE_STATE( AfxGetStaticModuleState() ); CDlgFoo dlg; dlg.DoModal(); } In the console program you'll have code like this: h = ::LoadLibrary( "my.dll" ); ::DisableThreadLibraryCalls( h ); pfoo = (foo_type*)::GetProcAddress( h, (const char*)1 ); if ( pfoo ) pfoo();
1,936,399
1,936,410
C++ [] array operator with multiple arguments?
Can I define in C++ an array operator that takes multiple arguments? I tried it like this: const T& operator[](const int i, const int j, const int k) const{ return m_cells[k*m_resSqr+j*m_res+i]; } T& operator[](const int i, const int j, const int k){ return m_cells[k*m_resSqr+j*m_res+i]; } But I'm getting this error: error C2804 binary operator '[' has too many parameters
Prior to C++23, you could not overload operator[] to accept multiple arguments. As a workaround, you instead can overload operator(). (See How do I create a subscript operator for a Matrix class? from the C++ FAQ.) From C++23, as mentioned in a (deleted) answer by cigien, multiple subscript arguments can be passed to operator[] directly. See this demo from the cppreference page.
1,936,452
1,936,461
c++ () operator problem
I've got another problem when trying to overload the () operator for array access: const OctTreeNode*& operator()(const int i, const int j, const int k) const{ return m_cells[k*m_resSqr+j*m_res+i]; } OctTreeNode*& operator()(const int i, const int j, const int k){ return m_cells[k*m_resSqr+j*m_res+i]; } vector<OctTreeNode*> m_cells; I get a C2440 'return': cannot convert from 'OctTreeNode *const' to 'const OctTreeNode *&' what's the deal? i'm declaring it exactly as in another class. the only difference is that the other class is generic, and there i'm using T& instead of OctreeNode*&
The first operator should return const const OctTreeNode * const & operator()(const int i, const int j, const int k) const{ return m_cells[k*m_resSqr+j*m_res+i]; } ... or the const before the *, I never seem to remember -_- First const tells us that we can't modify OctTreeNode, second one tells us that we can't modify the pointer to it (set it to NULL for example) while the third one tells us that the method doesn't change the object. To be honest I'm unsure wether the first one is needed, as the only thing that we need to grant const correctness to the method, is to grant that nobody will change references to those pointers.
1,936,542
1,936,552
Tips for embedding a longer text in source code, as in languages like Perl?
Possible Duplicate: Something like print END << END; in C++? In a shell script or in a perl program the so called "HERE" documents are commonly used for longer text, e.g. Perl: my $t=<<'...'; usage: program [options] arg1 arg2 options: -opt1 description for opt1 -opt2 description for opt2 ... print $t; This style is very well readable, e.g. no need to escape quotes or to explicitly insert \n. I am wondering if there is a comparable elegant approach to embed a longer text inside a C/C++ program? #include <iostream>; int main(void) { std::string t; // t = ... the same long text as in the perl example in a HERE document fashion ... std::cout << t; return 0; } EDIT: Simplification: there is no variable interpolation needed.
Unfortunately there's no elegant solution. I keep using: std::string lorem = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, " "sed do eiusmod tempor incididunt ut labore et dolore magna " "aliqua. Ut enim ad minim veniam, quis nostrud exercitation " "..."; C/C++ sticks the strings together, unfortunately there's no way to enter a linebreak implicitly except using \n. Besides, this is a duplicate of this SO question.
1,936,592
1,936,601
How to support linux for my C# project
I have a project that is an open source application for a specific type of scientific calculation that uses c++ for the backend, and C# for the front end. I'm not doing anything windows specific in the c++ portion, so I'm hoping for a relatively small learning curve there. I have a few specific questions, and I would appreciate any advice in general about this type of transition. Please keep in mind that I know absolutely nothing about Linux, but I am willing to learn. Is there an IDE that is similar to Visual Studio? Ideally, I would like to set it up in a similar fashion to what I have now, with 2 C# solutions and a couple of c++ dlls. I really don't want to use a text editor alone and link with a command line Is there some tool to give me an idea about problems I might have in the transition? Is there anyway to translate my Visual Studio options to gcc options? I know that I don't need to support Linux technically, as almost everyone in my field uses Windows, or has easy access to a Windows box, but I thought this might be interesting from a technical standpoint.
There is a IDE you can use for C# on linux - it is Mono Develop. The current version will open visual studio project and solution files, so zero knowledge is needed to migrate to it. It uses the Mono project, which is an implementation of C# for linux. They have created a migration tool (MoMa) so you can test your C# code and see if it will work on linux - it will provide you with hints and explanations of what isn't portable and why. I know this isn't the c++ route you are asking about, but it is probably going to be the easiest and quickest way to make your application platform independent.
1,936,694
1,936,746
Segfault in atoi(str)
I'm new to the C/C++ game so I assume I'm making a rookie mistake: int main(){ char* clen; clen = getenv("CONTENT_LENGTH"); if (clen==NULL){ cout << "No such ENV var: CONTENT_LENGTH"<<endl; exit(0); } int cl = 0; cl = atoi(clen); if (cl < 1){ return inputPage(); } // if there is no content, we assume that this is a fresh request, // so we showed the input page, otherwise, we'll return dispatch to //the processing code. postTest(clen); } This is supposed to be a CGI script. As far as I can tell with GDB, print statements, etc. this code segfaults on the line "cl = atoi(clen);" I have no idea why this is. K&R suggests that this is correct. I basically copied this line from a half dozen other online tutorials. And it seemed to be working last night! I'm totally stumped.
I don't believe that it really crashes on atoi() Could you please try out this code? #include <iostream> #include <stdlib.h> #ifndef NULL #define NULL 0 #endif using namespace std; int main(){ char* clen; clen = getenv("CONTENT_LENGTH"); if (clen==NULL){ cout << "No such ENV var: CONTENT_LENGTH"<<endl; exit(0); } int cl = 0; cl = atoi(clen); if (cl < 1){ std::cout << "return inputPage();" << std::endl; return 0; } std::cout << "postTest();" << std::endl; } compile it e.g. to "app" and run it with some variations of CONTENT_LENGTH, e.g. ./app CONTENT_LENGTH=4 ./app CONTENT_LENGTH=-4 ./app CONTENT_LENGTH=a ./app
1,936,913
1,936,933
Storing an integer into a char* in C++
I'm writing some code that returns an integer, which then needs to be outputted using printw from the ncurses library. However, since printw only takes char*, I can't figure out how to output it. Essentially, is there a way to store a integer into a char array, or output an integer using printw?
printw() accepts const char * as a format specifier. What you want is printw("%d",yournumber);
1,936,942
1,936,959
Writing a deep copy - copying pointer value
In writing a copy constructor for a class that holds a pointer to dynamically allocated memory, I have a question. How can I specify that I want the value of the pointer of the copied from object to be copied to the pointer of the copied to object. Obviously something like this doesn't work... *foo = *bar.foo; because, the bar object is being deleted (the purpose of copying the object in the first place), and this just has the copied to object's foo point to the same place. What is the solution here? How can I take the value of the dynamically allocated memory, and copy it to a different address?
You allocate new object class Foo { Foo(const Foo& other) { // deep copy p = new int(*other.p); // shallow copy (they both point to same object) p = other.p; } private: int* p; };
1,937,135
2,044,860
exposing std::vector<double> with boost.python
I have written some C++ code that generates a std::vector. I also have a python script that manipulates some data that, for now, I am declaring like this (below). import numpy x = numpy.random.randn(1000) y = numpy.random.randn(1000) I can run the script fine. From my C++ code: using namespace boost::python; try{ Py_Initialize(); object main = import("__main__"); object global(main.attr("__dict__")); object result = exec_file("scatterPlot.py", global, global); Py_Finalize(); } catch(error_already_set){ PyErr_Print(); } return; I have no idea how to get my C++ data to python. I've around quite a bit, but there doesn't seem to be anything definitive. I have in my C++ BOOST_PYTHON_MODULE(vector_indexing_suite_ext){ boost::python::class_<std::vector<double> >("PyVec") .def(boost::python::vector_indexing_suite<std::vector<double> >()); } This seems to work, but as I understand, it only provides a class "PyVec" for my python script but not the data I need. Am I wrong? I've also seen some other people use boost::shared_ptr in a python mailing list. I also found this example but found it confusing. I can think of a few approaches Pass something to the boost::python::exec_file method Using the boost_indexing_suite_ext Uinsg boost::shared_ptr Which approach is easiest to get going? No approach seems clear to me. Here are some more links I've looked at: from the boost website from the python website another mailing list thread UPDATE: This works for passing an int to my python code like below int main(){ int five_squared=0; int a =3; try { Py_Initialize(); object main_module = import("__main__"); object main_namespace = main_module.attr("__dict__"); main_namespace["var"]=a; object ignored = exec("result = 5 ** var", main_namespace); five_squared = extract<int>(main_namespace["result"]); } catch( error_already_set ) { PyErr_Print(); } std::cout << five_squared << std::endl; return 0; } But I want to pass a vector, when I try to do that in a similar fashion as above I get this error TypeError: No to_python (by-value) converter found for C++ type: std::vector > So, obviously I need to tell python how to deal with std::vector. I think this code could help with that. BOOST_PYTHON_MODULE(vector_indexing_suite_ext){ boost::python::class_<std::vector<double> >("PyVec") .def(boost::python::vector_indexing_suite<std::vector<double> >()); } But since std::vector is pretty common, there must be a defined way to do this... right?
The following code works for me (Python 2.6, Boost 1.39). This is almost the same as your code, except without the BOOST_PYTHON_MODULE line itself (but with the class_ definition for the vector). BOOST_PYTHON_MODULE only needs to be used when creating extension modules. #include <iostream> #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> using namespace boost::python; using namespace std; int main() { vector<double> vec; vec.push_back(1.2); vec.push_back(3.4); try { Py_Initialize(); boost::python::class_<std::vector<double> >("PyVec") .def(boost::python::vector_indexing_suite<std::vector<double> >()); object main_module = import("__main__"); object globals = main_module.attr("__dict__"); globals["var"]=vec; object ignored = exec("result = sum(var)", globals, globals); double result = extract<double>(globals["result"]); std::cout << result << std::endl; } catch( error_already_set ) { PyErr_Print(); } return 0; }
1,937,163
1,937,178
Drawing in a Win32 Console on C++?
What is the best way to draw things in the Console Window on the Win 32 platform using C++? I know that you can draw simple art using symbols but is there a way of doing something more complex like circles or even bitmaps?
No you can't just do that because Win32 console doesn't support those methods. You can however use GDI to draw on the console window. This is a great example of drawing a bitmap on a console by creating a child window on it: http://www.daniweb.com/code/snippet216431.html And this tells you how to draw lines and circles: http://www.daniweb.com/code/snippet216430.html This isn't really drawing in the console though. This is sort of drawing "over" the console but it still does the trick pretty well.
1,937,176
1,937,222
Maintaining a valid position using seekg in ifstreams
I am trying to make my file parsing more robust. Using an ifstream, how can I ensure seekg keeps me in a valid position within the file? This does not work: while(m_File.good() && m_File.peek() != EOF) { ...a seekg operation moves file position past end of file... } I assume the current iterator has been pushed way past the end iterator, so the peek() is never true.
No, there is no way of doing this, short of finding the offset of the end of file and making sure you don't seek beyond it, which causes undefined behaviour - you can of course increase the size of the file by writing.
1,937,181
1,937,207
How to return 2 dimension array in C++
I have a segmentationfault at the line : cout << b[0][0]; Could someone tell me what should I do to fix my code? #include <iostream> using namespace std; int** gettab(int tab[][2]){ return (int**)tab; } int main() { int a[4][2] = {{0, 0}, {1, 0}, {2, 0}, {2, 1}}; int ** b = gettab(a); cout << b[0][0]; return 0; }
A 2-dimensional array is not the same thing as an array of pointers, which is how int** is interpreted. Change the return type of gettab. int* gettab(int tab[][2]){ return &tab[0][0]; } int main() { int a[4][2] = {{0, 0}, {1, 0}, {2, 0}, {2, 1}}; int* b = gettab(a); cout << b[0]; // b[row_index * num_cols + col_index] cout << b[1 * 2 + 0]; // the 1 from {1, 0} } Or: int (*gettab(int tab[][2]))[2] { return tab; } // or: template<class T> struct identity { typedef T type; }; identity<int(*)[2]>::type gettab(int tab[][2]) { return tab; } int main() { int a[4][2] = {{0, 0}, {1, 0}, {2, 0}, {2, 1}}; int (*b)[2] = gettab(a); cout << b[0][0]; }
1,937,291
1,937,321
Advantage of winelib?
Are there any advantages to compiling my Windows application with winelib for Linux users? Why not just give them the .exe and let them run it with Wine? Seems just like extra work for no gain.
You might want to read on Advantages and Disadvantages of using Winelib.
1,937,294
1,937,869
SEHException thrown in a non-.NET application
I am writing an MFC application that doesn't use .NET (CLR support is set to No Common Language Runtime support in the project settings). However, I get an SEHException thrown when I quit the application in Release build. Debug build gives me an assertion error, but the error window disappears in about half a second after it pops up (something I haven't encountered before either) so I don't get a chance to look at it. So the main question is: how can an application that doesn't have any managed code throw an Interop.SEHException?
An application without managed code can throw a SEHException because structured exception handling (SEH) is part of Win32, and predates the CLR. Here's a link from January 1997 giving a crash course (hah!) on Win32 SEH.
1,937,345
1,937,350
Gdiplus in C++ managed or unmanaged?
is this file with namespace Gdiplus in c++ managed or unmanaged code?
Unmanaged. The managed wrapper is the System::Drawing namespace.
1,937,349
1,937,374
Simple C++ File stream
I want to read then store the content of a file in an array, but this isn't working: #include <iostream> #include <fstream> #include <string> using namespace std; int main () { string content,line,fname; cout<<"Execute: "; cin>>fname; cin.ignore(); cout<<endl; //Doesn't work: ifstream myfile(fname); if(!myfile.is_open()){ cout<<"Unable to open file"<<endl; }else{ while(!myfile.eof()){ getline(myfile,line); //I don't know how to insert the line in the string } myfile.close(); } cin.get(); return 0; }
2 things. When creating your ifstream, you must pass a char*, but you're passing a string. To fix this, write : ifstream myfile(fname.c_str()); Also, to add the line to the content, call the "append" method : content.append(line); It works for me :) If you actually want to store each line seperatly, store every line into a string vector, like Skurmedel said.
1,937,392
1,937,436
C++ Destructor Behavior
I had a question about C++ destructor behavior, more out of curiosity than anything else. I have the following classes: Base.h class BaseB; class BaseA { public: virtual int MethodA(BaseB *param1) = 0; }; class BaseB { }; Imp.h #include "Base.h" #include <string> class BImp; class AImp : public BaseA { public: AImp(); virtual ~AImp(); private: AImp(const AImp&); AImp& operator= (const AImp&); public: int MethodA(BaseB *param1) { return MethodA(reinterpret_cast<BImp *>(param1)); } private: int MethodA(BImp *param1); }; class BImp : public BaseB { public: BImp(std::string data1, std::string data2) : m_data1(data1), m_data2(data2) { } ~BImp(); std::string m_data1; std::string m_data2; private: BImp(); BImp(const BImp&); BImp& operator= (const BImp&); }; Now, the issue is that with this code, everything works flawlessly. However, when I make the destructor for BImp virtual, on the call to AImp::MethodA, the class BImp seems to have its data (m_data1 and m_data2) uninitialized. I've checked and made sure the contained data is correct at construction time, so I was wondering what the reason behind this could be... Cheers! Edit: param1 was actually a reference to B in MethodA. Looks like I over-sanitized my real code a bit too much! Edit2: Re-arranged the code a bit to show the two different files. Tested that this code compiles, a well. Sorry about that!
If you are casting between related types as you do in this case, you should use static_cast or dynamic_cast, rather than reinterpret_cast, because the compiler may adjust the object pointer value while casting it to a more derived type. The result of reinterpret_cast is undefined in this case, because it just takes the pointer value and pretends it's another object without any regard for object layout.
1,937,408
1,937,416
ifstream, bytes read?
How do you get how many bytes were read with the ifstream::read function? Tell is saying the file is 10 bytes and windows says it is 10 bytes too but there are only 8 bytes in the file so when I read it, it is only reading the 8 bytes so I end up with too large of a buffer.
You can find out by calling gcount() on a stream immediately after you read. ifs.read(buf, sizeof buf); std::streamsize bytes = ifs.gcount();
1,937,525
1,937,538
error C2248: 'Gdiplus::Bitmap::Bitmap' : cannot access private member declared in class 'Gdiplus::Bitmap'
i am getting this error and i dont know why or understand the reason: vector<double> fourier_descriptor(Gdiplus::Bitmap myBitmap) { vector<double> res; Contour c; vector<Pixel> frame;// = c.GetContour(p); frame = c.GetContour(myBitmap); return res; } the error is in this line frame = c.GetContour(myBitmap);
I can't find a reference for the GetContour method, but that looks like you're trying to pass a Bitmap by value, which (if I remember my C++ correctly) will invoke the copy constructor -- and Bitmap doesn't have a public copy constructor. If you own Contour, rewrite that function to take a Bitmap* or Bitmap& instead (i.e. pass a pointer or reference), thereby avoiding the copy constructor.
1,937,558
1,937,563
Private members: Static const vs. just const
I'm trying to decide what the best option would be for when an object has some traits that won't change, and are needed throughout its functions. Static const members Const members It seems to me like the real reason for a static member is to have a variable that can be changed, and thus affect all other objects of the same class. However, I've had people recommend class "invariants" to be static const members. I'm looking for some insight regarding the recommended approach to establishing class constants, and reasons why.
"Won't change" is not precise enough. The main question here is whether different objects of the class need to have different values of these const members (even if they don't change during the object's lifetime) or all objects should use (share) the same value. If the value is the same for all objects of the class, then, of course, it should be a static const member of the class. If different objects might require different values, then it should be just a non-static const member.
1,937,702
1,938,940
Visual Studio: Run C++ project Post-Build Event even if project is up-to-date
In Visual Studio (2008) is it possible to force the Post-Build Event for a C++ project to run even if the project is up-to-date? Specifically, I have a project which builds a COM in-process server DLL. The project has a post-build step which runs "regsvr32.exe $(TargetPath)". This runs fine on a "Rebuild", but runs on a "Build" only if changes have been made to the project's source. If I do a "Build" without making any changes, Visual Studio simply reports that the project is up-to-date and does nothing - the Post-Build Event is not run. Is there any way that I can force the Event to run in this situation? This is necessary since although the DLL itself is up-to-date, the registration information may not be.
You can use the Custom Build Step property page to set up a batch file to run. This runs if the File specified in the Outputs setting is not found, or is out-of-date. Simply specify some non-existent file there, and the custom build step will always run. It will run even if your project is up-to-date, since the Output file is never found.
1,937,707
1,937,714
Memory management with new keyword and an STL vector of pointers
How is the destructor for the vector managed when adding elements to this list? Is the object destroyed correctly when it goes out of scope? Are there cases where it would not delete the object correctly? For example what are the consequences if "table" was a child of object, and we added a new table to a vector of object pointers? vector <object*> _objectList; _objectList.PushBack(new object);
Since you're making a vector of "bare" pointers, C++ can't possibly know that the pointers in question are meant to have "ownership" of the objects they point to, and so it will not call those objects' destructors when the pointer goes away. You should use a simple "smart" pointer instead of a "bare" pointer as the vector's item. For example, Boost's shared_ptr would be perfectly adequate for the task (although you can surely do it with "cheaper", lighter-weight approaches, if you don't want to deal with Boost as a whole and have no other need for smart pointers in your code). Edit: since you (the OP) say that using a framework such as Boost is not feasible, and a couple comments usefully point out that even wrapping std::auto_ptr doesn't really qualify as a decent shortcut, you may have to implement your own smart pointers (or, if you find an open-source, stand-alone smart pointer template class that looks usable, audit it for compliance with your requirements). This article is a useful primer to smart pointers in C++, whether you have to roll your own or audit an existing implementation.
1,937,968
1,938,496
Boost Filesystem Compile Error
I'm writing some code that utilizes the boost filesystem library. Here is an excerpt of my code: artist = (this->find_diff(paths_iterator->parent_path(), this->m_input_path) == 1) ? (*(paths_iterator->parent_path().end() - 1)) : (*(paths_iterator->parent_path().end() - 2)); album = (this->find_diff(paths_iterator->parent_path(), this->m_input_path) == 1) ? "" : (*(paths_iterator->parent_path().end() - 1)); Types: artist and album are of type std::string this->find_diff returns an int this->m_input_path is a std::string paths_iterator is of type std::vector(open bracket)boost::filesystem::path>::iterator I get a compile error: error C2039: 'advance' : is not a member of 'boost::filesystem::basic_path<String,Traits>::iterator' d:\development\libraries\boost\boost\iterator\iterator_facade.hpp on line 546 This code is part of a program that outputs a batch script that uses lame.exe to convert files into mp3s. The music library this is designed for has the format: root/artist/song OR root/artist/album/song this->m_input_path is the path to root. I'm not sure if I'm approaching the problem properly. If I am, how do I fix the error that I am getting? EDIT: My code is now: boost::filesystem::path::iterator end_path_itr = paths_iterator->parent_path().end(); if(this->find_diff(paths_iterator->parent_path(), this->m_input_path) == 1) /* For cases where: /root/artist/song */ { album = ""; end_path_itr--; artist = *end_path_itr; } else /* For cases where: /root/artist/album/song */ { end_path_itr--; album = *end_path_itr; end_path_itr--; <-- Crash Here artist = *end_path_itr; } The error that I now get is: Assertion failed: itr.m_pos && "basic_path::iterator decrement pat begin()", file ... boost\filesystem\path.hpp, line 1444
basic_path::iterator is a bidirectional iterator. So arithmetic with -1 and -2 is not allowed. Operators + and - between an iterator and an integer value is defined for a RandomAccessIterator. Instead of using .end()-1, you could resort to using --.
1,938,244
1,938,273
how to have a shared variable in library across many applications in linux?
how to have a shared variable in library across all application in linux (c++)?
You can use POSIX shared memory to create a shared memory segment, and place the variable there. You will need to synchronise access to the shared variable using POSIX semaphores. See the shm_overview(7) and sem_overview(7) man pages to get started.
1,938,679
1,938,694
C/C++ Copy file with automatic recursive folder/directory creation
In Win32 API, there is CopyFile that literally copies a file. However, this API doesn't create folders. For example, I'd like to copy C:\Data\output.txt to D:\Temp\Data\output.txt. But, the target folders, D:\Temp and D:\Temp\Data', do not exist. In this case, this API just fails. Is there a handy API that can automatically and recursively create directory structure on copy? Definitely, I can make such function, but I expect someone already made the function.
SHFileOperation should do the trick. From MSDN: Copy and Move operations can specify destination directories that do not exist. In those cases, the system attempts to create them and normally displays a dialog box to ask the user if they want to create the new directory. To suppress this dialog box and have the directories created silently, set the FOF_NOCONFIRMMKDIR flag in fFlags.
1,938,750
1,938,784
Coming from C to C++
HI all. I have started a new job recently where I am supposed to work with C++/ I have been doing programming in C language for past 5 years. I am looking for ways to get me up to an acceptable level in OOP. I have all the basic concepts of C++ and OOP but don't have much experience of actual class designing. What I really am looking for is ways to learn class library designing as I will be working in a team who is writing C++ libraries for other programmers to use. Please suggest principles like "responsibility assignment" which can help me design classes in general.
Give a loook to Bob Martin SOLID principles: SRP The Single Responsibility Principle: A class should have one, and only one, reason to change. OCP The Open Closed Principle: You should be able to extend a classes behavior, without modifying it. LSP The Liskov Substitution Principle: Derived classes must be substitutable for their base classes. ISP The Interface Segregation Principle: Make fine grained interfaces that are client specific. DIP The Dependency Inversion Principle: Depend on abstractions, not on concretions.