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,...
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 a...
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 so...
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 Stud...
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 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....
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 th...
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...
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;...
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 kin...
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-u...
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 ...
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 ob...
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 .c...
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 mo...
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; }; ...
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...
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 samplec...
## 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 ...
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...
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 gua...
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 ...
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 ...
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/76...
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...
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_direct...
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...
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() { }...
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 st...
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 som...
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 XORin...
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,...
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"...
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: $ ...
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 aski...
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...
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 = &My...
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 ...
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 ...
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> #de...
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 us...
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! }...
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 shortc...
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, ...
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 ...
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; }...
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 ea...
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...
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...
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 loc...
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 po...
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...
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 nev...
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 pass...
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 allocatio...
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 sco...
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 ge...
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 ...
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. ...
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. Wh...
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 ...
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 registe...
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 executab...
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, tha...
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...
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...
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...
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 c...
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...
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 1...
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 ...
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 gath...
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 althoug...
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'...
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...
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 aut...
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 hi...
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 precisio...
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_GCCOLLEC...
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 cu...
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" ...
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 #in...
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 t...
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...
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 ...
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::Connecte...
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 ...
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 o...
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 a...
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 rep...
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 kn...
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 implement...
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 insid...
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() in...
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.ba...
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 com...
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 exten...
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 so...
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...
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()' me...
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 mu...
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 ...
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 en...
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* simbRes...
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...
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...
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...
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 lon...
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...
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... Thank...
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 ...
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( ...
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 ge...
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...
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]; ...
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...
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 descripti...
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 t...
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 a...
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# c...
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 cont...
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; ...
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...
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; ...
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> #...
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...
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 p...
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]...
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 + ...
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 a...
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 myfil...
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 ...
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 {...
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...
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.GetCo...
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...
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 t...
"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, th...
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 ...
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 ...
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 obj...
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 ve...
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->pare...
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 automati...
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 h...
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 re...
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 sub...