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,640,718
1,640,838
Debugging C++ from core files with GDB
GDB seems to always just work for C programs, but for C++ I often get these cryptic stacks: (gdb) bt #0 0x08055fa4 in std::runtime_error::what () #1 0x080576c8 in std::runtime_error::what () #2 0x08057dda in std::runtime_error::what () #3 0x080580d2 in std::runtime_error::what () #4 0x08058662 in std::runtime_error::what () #5 0x08058725 in std::runtime_error::what () #6 0x0806ef7a in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string<char*> () #7 0x00c0adec in __libc_start_main () from /lib/libc.so.6 #8 0x0804d011 in std::runtime_error::what () Which on the surface offer absolutely no clues as to where the problem occurred. Is there anyway to get more information out of such a core file - or make the program dump something more useful?
It's unlikely that the text for std::runtime_error::what() actually covers a range from 0x0804d011 through 0x08058725 as suggested by the backtrace. That would be more than 45KB of code. It's more likely that the symbol lookup code that is trying to resolve 0x08055fa4, 0x080576c8, etc. is simply locating std::runtime_error::what() as the last usable symbol prior to those addresses, which is often the result of stripping the executable (as you have done by passing -s switch to the linker). I'd focus on stack frame #6. Since this is a ctor for a fairly straightforward class, my SWAG would be that you've passed in a NULL pointer or a pointer to a non-NULL terminated string. EDIT: Note that if you simply rebuild the executable from exactly the same sources without the -s switch, you will get a much more usable stack from GDB, using the core file you already have. There is no need to wait for the newly-built executable to dump core again.
1,640,720
28,518,981
How do I tell if the c function atoi failed or if it was a string of zeros?
When using the function atoi (or strtol or similar functions for that matter), how can you tell if the integer conversion failed or if the C-string that was being converted was a 0? For what I'm doing, 0 is an acceptable value and the C-string being converted may contain any number of 0s. It may also have leading whitespace.
For C++11 and later: The go-to function for string-to-integer conversion is now stoi, which takes a string and returns an int, or throws an exception on error. No need for the verbose istringstream hack mentioned in the accepted answer anymore. (There's also stol/stoll/stof/stod/stold for long/long long/float/double/long double conversions, respectively.)
1,640,758
1,640,769
Passing std::vector for any type to a function
Given: template<typename T> class A { B b; std::vector<T> vec1; std::vector<T> vec2; } I'd like B to have a member function that fill() that takes a reference to those to vectors and fills vec2 with values of T depending on some information contained in b. One way of doing this is overloading fill() for each possible argument T: fill(const std::vector<float>& a, std::vector<float>& b) and so on but this will mean a lot of unnecessary duplication as the operations are the same for every possible T. Inside of fill() I could use vector::value_type for the calculations but I don't know how to declare it in such a way that it takes every kind of std::vector. The obvious way would be to use a free function with templates. Is there a simpler way of doing this?
Templatize B. template<typename T> class B { void fill(const std::vector<T>& a, std::vector<T>& b) { } }; template<typename T> class A { B<T> b; std::vector<T> vec1; std::vector<T> vec2; } If you don't want to templatize B, then templatize the fill function: class B { template<typename T> void fill(const std::vector<T>& a, std::vector<T>& b) {} };
1,640,847
1,640,863
Are There Yacc Grammar Debuggers?
I've been helping augment a twenty-some year old proprietary language within my company. It is a large, Turing-complete language. Translating it to another grammar regime (such as Antlr) is not an option (I don't get to decide this). For the most part, extending the grammar has gone smoothly. But every once in awhile I'll get a reduce-reduce or shift-reduce that is difficult to eliminate sometimes just doesn't make sense (to my feeble brain) After a lot of painful staring at y.output files and experimental grammar refactorings, I've usually gotten where I wanted to go. Sometimes I've had to make unsatisfactory compromises. So, are there any tools out there which can suck in a yacc grammar, which enhance browsing, experimenting, and allow debugging of changes? If I add a production, I'd like to see more than "atomic production that is used everywhere" (think identifier) "conflicts with rule foo" (yes, there is more info, s/r, r/r, than that, but I think you get my drift). It would be nice to have some hint of the interplay beyond putting on my thinking cap and trying to imagine a symbol stack and state machine. Update: I guess I should clarify. We use Berkeley Yacc. I have been testing using a recent version of Bison. For output, I've compiled the grammar with --report=itemset. My goal with this post is to seek out external tools which augment the grammar debugging facilities which ship with yacc. It's painful today with the default set. Help me find better interactive tools, such as those you can use with Antlr.
You might get some help from yacc -d, which produces debugging output -- it basically gives a full listing of the symbol stack states and such. The output is dense and voluminous, so trying to read all of it directly rarely accomplishes much (never has for me anyway). However, when you make a change the gives (for example) an r/r conflict, you can run yacc -d on the old grammar and the new one, then run diff on the results, to get a much more detailed run-down on what change(s) caused the conflict. It's probably worth noting, however, that s/r conflicts are often benign -- unless you're fairly sure it's a problem, trying to "fix" it often isn't worthwhile. The same is not true with r/r conflicts though. While these are sometimes benign, it's comparatively rare. Edit: Oops -- sorry, that should be -v. You mention y.output, so you apparently already know how to do that part. The point is that you don't try to look at the y.output files directly, but do a diff between the one that came out cleanly and the one that didn't to get some detail about the actual conflict (without staring at 10 jillion lines of "stuff" that's just fine.
1,640,848
1,640,896
Generating getters & setters in XCode
I am currently using xcode for some c++ development & I need to generate getters & setters. The only way I know is generating getters & setters in Objective C style something like this - (string)name; - (void)setName:(string)value; I dont want this; I want c++ style generation with implementation & declaration for use in the header files. Any idea...?
It sounds like you're just looking for a way to reduce the hassle of writing getters/setters (i.e. property/synthesize statements) all the time right? There's a free macro you can use in XCode to even generate the @property and @synthesize statements automatically after highlighting a member variable that I find really helpful :) If you're looking for a more robust tool, there's another paid tool called Accessorizer that you might want to check out.
1,640,886
1,640,893
Does (!(i % j)) mean not modulus of i and j = 0?
int main() { int i,j; for (i=1; i<=25; i++) { for (j=2; j<= i/2; j++) if (!(i%j)) break; if (j>i/2) cout << i << "\n"; } return 0; } This program (not written by me) outputs the prime numbers from 1 to 25, including 1 even though 1 isnt prime. I am having trouble with this line: if (!(i%j)) break; Does this say "not modulus of i and j = 0?
!(i%j) is the same as (i%j)==0, or "i is divisible by j"
1,640,922
1,646,780
Restricting the size of components at design time
I am trying to inherit from TButton in order to provide some size aware capabilities, where the buttons are able to resize themselves and/or their font size (within certain constraints) to allow for changes in text e.g. | small | or |   this is a really long   | | sentence on a button | could happily be the same button on the same form, all I've done is reset the text and the button copes with the size change itself. I've implemented all the text measuring functions, and the functionality works to a point. what I have done is create new properties maxHeight, minHeight, defaultHeight and so forth for Width and Font. When the user changes the default height, my design time component will change and reflect this new default height. When the user uses the normal Height & Width properties however (or drags the corner) I don't know how to tie them to the default height and width. I intercepted OnCanResize and created an event handler and tried to confirm that the new size is within the min max. If it's not, set to the min or max as required, but if within the boundaries then update. I am able to intercept runtime resize events, but not design time. If it is possible to intercept the design time resizes, does anyone know how? sorry if that's a bit long-winded, hope it makes sense!
Override the virtual SetBounds() method. From there, you can adjust the user's requested dimensions as needed before then passing them to the ancestor SetBounds() method. For example: class TMyButton : public TButton { typedef TButton inherited; public: ... virtual void __fastcall SetBounds(int ALeft, int ATop, int AWidth, int AHeight); __published: __property int MaxHeight = ...; __property int MinHeight = ...; ... }; virtual void __fastcall SetBounds(int ALeft, int ATop, int AWidth, int AHeight) { if (AHeight > MaxHeight) AHeight = MaxHeight; if (AHeight < MinHeight) AHeight = MinHeight; ... inherited::SetBounds(ALeft, ATop, AWidth, AHeight); }
1,641,114
1,641,151
How to read a value with operator>> but no default constructor to the value?
template <class T> T Read () { T t; cin >> t; if (cin.fail()) { // ... } return t; } This generic code read value of type T with some additional error handling. It relies on having operator>> that can parse T, and in this way it is extensible to new types. What I didn't realize is that it relies on T having a default constructor. Now I've hit into this problem. What are my options? What is the right way to do it?
Streaming from an input stream always assumes a fully constructed object to write into. You can't get around having to construct an object, all you can do is allow for different ways to do so. One way to do this could be traits. The standard traits would do what you're doing: template< typename T > struct istream_traits { inline static T read(std::istream& is) { T obj; is >> obj; } } template< typename T > inline T read(std::istream& is) { is >> std::ws; T obj = istream_traits<T>::read(is); is >> std::ws; if(!is.eof()) throw "dammit!"; return obj; } If you have a type X that cannot be default-constructed, but can be constructed from an istream, the following specialization would do: template<> struct istream_traits<X> { inline static X read(std::istream& is) { return X(is); } }
1,641,182
1,641,223
How can I catch a ctrl-c event?
How do I catch a Ctrl+C event in C++?
signal isn't the most reliable way as it differs in implementations. I would recommend using sigaction. Tom's code would now look like this : #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> void my_handler(int s){ printf("Caught signal %d\n",s); exit(1); } int main(int argc,char** argv) { struct sigaction sigIntHandler; sigIntHandler.sa_handler = my_handler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); pause(); return 0; }
1,641,286
5,595,356
Using Qt with DirectX?
What exactly are my options? I have programs I need to write in OpenGL and DirectX, and I'd like to use Qt for OpenGL, and not have to re-implement half my program for the DirectX components of my task. I've looked on Google and I have found references to people complaining about Direct3D being a dependency of Qt, and people talking about implementing QD3DWidget sub-classing QWidget in a similar fashion to QGLWidget, yet nobody talked about how to implement it or where any examples are. I need help. I want to know if it is possible? What would I need to do to get it working? Has it been done before?
its pretty straightforward than I thought, -> Create a QWidget -> Override paintEngine() method, does nothing, just returns NULL -> Assign HWND to widget->winId() #ifdef USE_QTGUI QApplication a(argc, argv); CD3DWidget wndw; wndw.show(); wndw.resize(1280,960); hWnd = wndw.winId(); #else hWnd = CreateAppWindow(name,300,300); #endif //CD3DWidget class contains only the following definitions CD3DWidget::CD3DWidget(QWidget * parent):QWidget(parent){ } QPaintEngine *CD3DWidget::paintEngine (){ return NULL; } Thanks, CV
1,641,412
1,641,446
iPhone App: Making a webpage accessible only to people using a specific app
I was just wondering if it is possible and if so what the best way to create a web-page that is only accessible from a custom iPhone application? For example, if you tried to access the webpage from the iPhone's built in browser, or any other browser it would display an error page but when accessed from a custom built application it would be fully functional. One idea that has come up is to change the User-Agent string in the embedded browser inside the application to something custom. I'm not sure if this is viable though. I hope this makes sense. Thanks in advance. -Ben
Any and all request headers can and will be spoofed. Authentication is the only plausible solution.
1,641,501
1,641,526
How does Windows identify non-Unicode applications?
I am building an MFC C++ application with "Use Unicode Character Set" selected in Visual Studio. I have UNICODE defined, my CStrings are 16-bit, I handle filenames with Japanese characters in them, etc. But, when I put Unicode strings containing Japanese characters in a CComboBox (using AddString), they show up as ?????. I'm running Windows XP Professional x64 (in English). If I use Windows Control Panel Regional and Language Options, Advanced Tab, and set the Language for non-Unicode programs to Japanese, my combo box looks right. So, I want my combo box to look right, and I want to understand why the "Language for non-Unicode programs" setting is changing the behavior of my Unicode program. Is there something else I should do to tell Windows my application is a Unicode application? Thanks for any help!
Windows knows the difference between Unicode and non-Unicode programs by the functions they call. Most Windows API functions will come in two variants, one ending in A for non-Unicode and one ending in W for Unicode. The include files that define these functions will use the compiler settings to pick one or the other for you automatically. The characters might not be coming out properly because you've selected a font that doesn't include them to be your default UI font.
1,641,611
1,641,625
How do you do inheritance in a non-OO language?
I read that early C++ "compilers" actually translated the C++ code to C and used a C compiler on the backend, and that made me wonder. I've got enough technical knowledge to wrap my head around most of how that would work, but I can't figure out how to do class inheritance without having language support for it. Specifically, how do you define a class with a few fields, then a bunch of subclasses that inherit from it and each add their own new fields, and be able to pass them around interchangeably as function arguments? And especially how can you do it when C++ allows you to allocate objects on the stack, so you might not even have pointers to hide behind? NOTE: The first couple answers I got were about polymorphism. I know all about polymorphism and virtual methods. I've even given a conference presentation once about the low-level details of how the virtual method table in Delphi works. What I'm wondering about is class inheritance and fields, not polymorphism.
In C anyway you an do it the way cfront used to do it in the early days of C++ when the C++ code was translated into C. But you need to be quite disciplined and do all the grunt work manually. Your 'classes' have to be initialized using a function that performs the constructor's work. this will include initializing a pointer to a table of polymorphic function pointers for the virtual functions. Virtual function calls have to be made through the vtbl function pointer (which will point to a structure of function pointers - one for each virtual function). The virtual function structure for each derived calss needs to be a super-set of the one for the base class. Some of the mechanics of this might be hidden/aided using macros. Miro Samek's first edition of "Practical Statecharts in C/C++" has an Appendix A - "C+ - Object Oriented Programming in C" that has such macros. It looks like this was dropped from the second edition. Probably because it's more trouble than it's worth. Just use C++ if you want to do this... You should also read Lippman's "Inside the C++ Object Model" which goes into gory details about how C++ works behind the scenes, often with snippets of how things might work in C. I think I see what you're after. Maybe. How can something like this work: typedef struct foo { int a; } foo; void doSomething( foo f); // note: f is passed by value typedef struct bar { foo base; int b; } bar; int main() { bar b = { { 1 }, 2}; doSomething( b); // how can the compiler know to 'slice' b // down to a foo? return 0; } Well you can't do that as simply as that without language support - you'd need to do some things manually (that's what it means to not have language support): doSomething( b.base); // this works
1,641,819
1,641,829
Why is complex<double> * int not defined in C++?
The C++ program #include <complex> #include <iostream> int main() { std::complex<double> z(0,2); int n = 3; std::cout << z * n << std::endl; } yields an error: no match for ‘operator*’ in ‘z * n’. Why? I'm compiling with g++ 4.4.1. Perhaps the compiler is just following the C++ standard, in which case my question is: why does the standard not allow this?
This works: #include <complex> #include <iostream> int main() { std::complex<double> z(0,2); double n = 3.0; // Note, double std::cout << z * n << std::endl; } Because complex is composed of doubles, it multiplies with doubles. Looking at the declaration: template <typename T> inline complex<T> operator*(const complex<T>&, const T&); (The following is thanks to dribeas) The compiler is not allowed to make implicit type conversions during template deduction, so by passing a complex with T being double, and then another T being int, when trying to match the function treating T as double causes the second argument to mis-match, and vice-versa. For what you want to work, it would have to have a function defined similar to this: template <typename T, typename U> inline std::complex<T> operator*(std::complex<T> lhs, const U& rhs) { return lhs *= rhs; } Which allows the function to take differing types, which allows the cast to be done when calling operator*=.
1,641,928
1,642,285
DllImport method isn't receiving data
BYTE* pImageBuffer = NULL; eResult res = PlayerLib::CreateImageSnapshot( iPlayerRef, eBMP, &pImageBuffer ); if( res > 0 ) { .... // do something with the image WriteFile(FileHandle, pBuffer, eRes, NULL, NULL); ReleaseImageSnapshot( pImageBuffer ); // free the image buffer in not longer needed! } here i can receive the image data in pImageBuffer and i could do the some image process the same way I have tryed in c# like [DllImport("PlayerLib")] public static extern int CreateImageSnapshot(int iPlayerRef, eImageFormat imgFormat,byte[] ppImageBuffer); byte[] bte ; CreateImageSnapshot(iPlayerref,eImageFormat.ePNG,bte); here its giving some unhandeld Exception..... hopefully the problem is in byte[] but i can't point out... please help me to overcome it.... thanks in advance here it shoud return the imagedata in ppImageBuffer... but here it's giving zero byte only
My suggest to you would be to marshal BYTE ** as ref IntPtr. Your declaration would be: [DllImport("PlayerLib")] public static extern int CreateImageSnapshot(int iPlayerRef, eImageFormat imgFormat, ref IntPtr ppImageBuffer); P.S. and sorry for my English, guys ;)
1,642,021
1,642,125
Resources in a static lib file - MFC
MFC is failing to launch my dialog boxes, it seems, because it can't find the resource identifiers. The dialog boxes are in a separate .lib file (so it has a separate .rc file, which, I'm assuming, somehow conflicts with the one in my .exe file). How should I be handling this situation?
In the .rc file for the .exe file, add a line like this: #include "YourLibResourceFile.rc" Then, in the .exe's project settings, add an additional include directory to where YourLibResourceFile.rc is, in Resources/Additional Include Directories.
1,642,028
1,642,035
What is the "-->" operator in C++?
After reading Hidden Features and Dark Corners of C++/STL on comp.lang.c++.moderated, I was completely surprised that the following snippet compiled and worked in both Visual Studio 2008 and G++ 4.4. Here's the code: #include <stdio.h> int main() { int x = 10; while (x --> 0) // x goes to 0 { printf("%d ", x); } } Output: 9 8 7 6 5 4 3 2 1 0 I'd assume this is C, since it works in GCC as well. Where is this defined in the standard, and where has it come from?
--> is not an operator. It is in fact two separate operators, -- and >. The conditional's code decrements x, while returning x's original (not decremented) value, and then compares the original value with 0 using the > operator. To better understand, the statement could be written as follows: while( (x--) > 0 )
1,642,091
1,642,101
Storing char array in a class and then returning it
I need to store a char array inside a class and then return it. I have to admit that I'm a bit confused about pointers and have tried everything I can think of but can't get it to work. Here's what I have: #include <iostream> using namespace std; class Test { public: void setName(char *name); char getName(); private: char m_name[30]; }; void Test::setName(char *name) { strcpy(m_name, name); } char Test::getName() { return *m_name; } void main() { Test foobar; char name[] = "Testing"; foobar.setName(name); cout << foobar.getName(); } Of course, I expect setName() to store the string "Testing" inside the class, and getName() should return "Testing". But instead, I get only the first letter T. What am I doing wrong? I guess I should be using std strings but first I would like to understand why this does not work. As far as I know, this should work with char arrays as well?
Just return a pointer: const char* Test::getName() const { return m_name; } and add a constructor for the class Test that would null-terminate the encapsulated array: Test::Test() { m_name[0] = 0; } so that you don't ask for trouble if someone instantiates class Test and doesn't call setName() on the instance.
1,642,240
1,642,281
how to implement common functor for several classes in c++
suppose you have two (or more) classes with private member vectors: class A { private: std::vector<X> priv_vec; public: //more stuff } class B { private: std::vector<Y> priv_vec; public: //more stuff } and you have a functor-class which has a state and works on a generic vector (does sorting or counts elements or something like that). The state of the functor is initialized by the first vector the functor is working on. If the functor is applied to another vector later, it will change its behavior depending on the state (sorts in the same way or trims the second vector after as many elements as the first one, etc) What is the best way to implement such a functor (desgin-pattern or functional interface?) without exposing the private vectors to the other classes or the user of the classes? for example: The user would like to initialize this functor with an object of class A and then use this initialized functor for one or more objects of class B. The user isn't able (and shouldn't be) to use the private vectors directly as function-arguments for the functor.
Hum, first, beware on states in functors. Most STL implementation of the algorithms may copy your functors around, therefore you generally have to extract the state in an outer structure. Now, for the application of functors, well it is simple: have your classes declare a template member function! class A { public: template <class Functor> Functor Apply(Functor f); private: }; class B { public: template <class Functor> Functor Apply(Functor f); }; // Usage MyFunctor f; A a; B b; b.Apply(a.Apply(f)); As for the functor, if you need state: // Alternative 1 class FunctorState {}; class Functor { public: Functor(FunctorState& state): m_state(state) {} // some operator()(...) private: FunctorState& m_state; }; // Alternative 2 class Functor { struct FunctorState {}; public: Functor(): m_state(new FunctorState) {} // some operator()(...) private: boost::shared_ptr<FunctorState> m_state; }; This way, copies of the Functor all points to the same FunctorState instance. Just choose depending if you wish to actually access the state from outside the class or not.
1,642,696
1,642,704
How to abort getchar in a console application when closing it
I've written a simple command line tool that uses getchar to wait for a termination signal (something like: 'Press enter to stop'). I however also want to handle the SC_CLOSE case (clicking the 'close' button). I did this by using SetConsoleCtrlHandler. But how do I cancel my getchar? I tried doing fputc('\n', stdin);, but that results in a deadlock. I can call ExitProcess, but then I get a crash in CThreadLocalObject::GetData when deleting a global CWnd, because the CThreadLocalObject is already deleted (okay, maybe I was lying when claiming it was a simple console application). I guess this might have something to do with the fact that the HandlerRoutine is called from a separate thread (not the main thread). Maybe there's some sort of getchar with a timeout that I can call instead?
Maybe there's some sort of getchar with a timeout that I can call instead? You can read console input asynchronously: #ifdef WIN32 #include <conio.h> #else #include <sys/time.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #endif int main(int argc, char* argv[]) { while(1) { #ifdef WIN32 if (kbhit()){ return getc(stdin); }else{ Sleep(1000); printf("I am still waiting for your input...\n"); } #else struct timeval tWaitTime; tWaitTime.tv_sec = 1; //seconds tWaitTime.tv_usec = 0; //microseconds fd_set fdInput; FD_ZERO(&fdInput); FD_SET(STDIN_FILENO, &fdInput); int n = (int) STDIN_FILENO + 1; if (!select(n, &fdInput, NULL, NULL, &tWaitTime)) { printf("I am still waiting for your input...\n"); }else { return getc(stdin); } #endif } return 0; } In such a way, you can introduce bool bExit flag which indicates if your programs is required to terminate. You can read input in specialized thread or wrap this code into the function and call it periodically.
1,642,703
1,643,796
How to get boost wdirectory_iterator to return UTF32 on the Mac
directory_iterator returns UTF8 using both Visual Studio and Xcode as expected. wdirectory_iterator, however, returns UTF16 using Visual Studio, and UTF8 using Xcode, despite returning a wchar_t string. What can I change to get wdirectory_iterator to return UTF32? An answer to a question I asked previously suggests that changing the locale might be required, however according to 'locale -a' the only locales available are en_GB, en_GB.ISO8859-1, en_GB.ISO8859-15, en_GB.US-ASCII, en_GB.UTF-8 All are 8 bit, with the possible exception of en_GB I tried en_GB in case it might not be 8 bit, but this causes boost::filesystem::exists to throw a boost::filesystem::wpath::to_external conversion exception.
wdirectory_iterator is a typedef for basic_directory_iterator<wpath>. wpath is a typedef for basic_path<std::wstring, wpath_traits>. Similarily to what is done in std::basic_filebuf, A basic_path uses an "internal" encoding to represent names to the program, and an "external" encoding to interact with the platform's filesystem. Conversion between these encodings is done like in std::basic_filebuf, by using the std::codecvt of the locale imbued on it. So, names are obtained by the iterator from the operating system in the system's encoding (that's the "external" encoding), and converted to the "internal" encoding with Traits::to_internal. To perform the desired conversion, you can thus: Call wpath_traits::imbue() "early" in your program, passing it a locale with a codecvt facet performing UTF8->UTF32 conversion Or define and use you own Traits class, where you implement to_internal to perform a UTF8->UTF32 conversion
1,642,763
1,642,776
null pointer equivalence to int
In "The C++ Programming Language", Bjarne writes that the null pointer is not the same as the integer zero, but instead 0 can be used as an pointer initializer for a null pointer. Does this mean that: void * voidPointer = 0; int zero = 0; int castPointer = reinterpret_cast<int>(voidPointer); assert(zero == castPointer) // this isn't necessarily true
Yes, that means that castPointer isn't necessarily zero, and the assert may fail. Because while the null pointer constant is zero, the null pointer of some type is not necessarily an address with all bits zero. reinterpret_cast has no special provisions to yield zero when casting a null pointer to int. You can achieve that by using boolean operators, which will initialize the variable with either 0 or 1: int castPointer = (voidPointer != 0);
1,642,789
1,645,438
Fgets in C++ repeats last line
I have program like (from link text) FILE* soubor; char buffer[100]; soubor = fopen("file","r"); string outp = ""; while (! feof(soubor)) { fgets(buffer,100,soubor); fputs (buffer , stdout); } fclose(soubor); and file like A B C D E and the output of program is A B C D E E it repeats last line of file twice. I have this problem in other programs too.
Using feof() as the condition for a loop to read from a file nearly always leads to problems. The standard way would look like this: while (fgets(buffer, 100, infile)) fputs(buffer, stdout);
1,642,810
1,642,835
Is there such a C++ optimisation?
E.g. vector<string> a; vector<string> b; a.push_back("first"); b=a; Would it be optimised somehow as vector<string> b; b.push_back("first");
Short answer: Yes. Long answer: Not really an "optimization", as most modern compilers (read as: non-MSVC) will do that. It's called static single assignment (SSA) and GCC supports it since version 4.0 - and it kicks ass, too!
1,642,903
1,642,917
STL containers on the stack and the heap
If std::vector and friends are self resizing, does that mean if I declare a vector like so: std::vector<string> myvec; Then it'll resize using more stack, whereas: std::vector<string> *myvec = new std::vector<string>(); Would resize using more heap?
Vectors allocate on the heap in their internals. The only thing you pay for in the stack for a stack based bector is a couple of bytes, the inner buffer will always be allocated from the heap. So effectively when you do a vec = new vector() you are allocating a small quantity, which may not be really good.
1,642,955
1,643,090
How to identify more than 4 gb ram on 32-bit machine
I know that a 32-bit OS cannot see more than 4 GB of RAM. So if I were to install, say, 6 GB of RAM on a machine running 32-bit OS, is there any way to identify that? I know one way to get the installed RAM is through WMI class: win32_physicalmemory.Capacity But I don't know if it'll show the correct installed ram size rather than supported. I don't have the setup to test this scenario, but if some one already knows this, please confirm. Else, please let me know if there's some other way of doing the same. I'm asking this for any windows 32-bit OS. Thanks in advance. Samrat Patil.
32bit operating systems CAN see more than 4GB of memory with PAE-enabled CPUs. It's just that the 32bit address space is limited to 4GB. But as the application has only access to its own virtual address space, it can't tell if some memory it allocated lays in 1st or 5th gigabyte of memory. On windows, you can use the GetPhysicallyInstalledSystemMemory function: function retrieves the amount of physically installed RAM from the computer's SMBIOS firmware tables. This can differ from the amount reported by the GlobalMemoryStatusEx function, which sets the ullTotalPhys member of the MEMORYSTATUSEX structure to the amount of physical memory that is available for the operating system to use. Read more: http://www.geoffchappell.com/viewer.htm?doc=notes/windows/license/memory.htm
1,643,035
1,643,190
Propagating 'typedef' from based to derived class for 'template'
I'm trying to define base class, which contains typedef's only. template<typename T> class A { public: typedef std::vector<T> Vec_t; }; template<typename T> class B : public A<T> { private: Vec_t v; // fails - Vec_t is not recognized }; Why in B I receive an error that Vec_t is not recognized and I need to write it explicitly? typename A<T>::Vec_t v;
I believe that this question is duplicate, but I cannot find it now. C++ Standard says that you should fully qualify name according to 14.6.2/3: In the definition of a class template or a member of a class template, if a base class of the class template depends on a template-parameter, the base class scope is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member. UPD: I found duplicate finally: here it is.
1,643,197
1,643,261
What is this C++ technique for adding types to a class called?
I've just found some C++ code (at http://msdn.microsoft.com/en-us/library/k8336763(VS.71).aspx), which uses a technique I've never seen before to add types to an existing class: class Testpm { public: void m_func1() { cout << "m_func1\n"; } int m_num; }; // Define derived types pmfn and pmd. // These types are pointers to members m_func1() and m_num, respectively. void (Testpm::*pmfn)() = &Testpm::m_func1; int Testpm::*pmd = &Testpm::m_num; int main() { Testpm ATestpm; Testpm *pTestpm = new Testpm; // Access the member function (ATestpm.*pmfn)(); (pTestpm->*pmfn)(); // Parentheses required since * binds // Access the member data ATestpm.*pmd = 1; pTestpm->*pmd = 2; cout << ATestpm.*pmd << endl << pTestpm->*pmd << endl; } Can someone please tell me what this technique for defining derived types is called, or point me to some documentation on it? I've never come across it in 13 years of using C++, and would like to end my ignorance.
The comment is incorrect: pmfn and pmd are not "derived types" at all (they are not even types!). They are pointers to members.
1,643,690
1,643,873
Destruction of singleton in DLL
I’m trying to create a simple Win32 DLL. As interface between DLL and EXE I use C functions, but inside of DLL i use C++ singleton object. Following is an example of my DLL implementation: // MyDLLInterface.cpp file -------------------- #include "stdafx.h" #include <memory> #include "MyDLLInterface.h" class MySingleton { friend class std::auto_ptr< MySingleton >; static std::auto_ptr< MySingleton > m_pInstance; MySingleton() { m_pName = new char[32]; strcpy(m_pName, “MySingleton”); } virtual ~ MySingleton() { delete [] m_pName; } MySingleton(const MySingleton&); MySingleton& operator=(const MySingleton&); public: static MySingleton* Instance() { if (!m_pInstance.get()) m_pInstance.reset(new MySingleton); return m_pInstance.get(); } static void Delete() { m_pInstance.reset(0); } void Function() {} private: char* m_pName; }; std::auto_ptr<MySingleton> MySingleton::m_pInstance(0); void MyInterfaceFunction() { MySingleton::Instance()->Function(); } void MyInterfaceUninitialize() { MySingleton::Delete(); } // MyDLLInterface.h file -------------------- #if defined(MY_DLL) #define MY_DLL_EXPORT __declspec(dllexport) #else #define MY_DLL_EXPORT __declspec(dllimport) #endif MY_DLL_EXPORT void MyInterfaceFunction(); MY_DLL_EXPORT void MyInterfaceUninitialize(); The problem or the question that i have is following: If i don't call MyInterfaceUninitialize() from my EXEs ExitInstance(), i have a memory leak (m_pName pointer). Why does it happening? It looks like the destruction off MySingleton happens after EXEs exit. Is it possible to force the DLL or EXE to destroy the MySingleton a little bit earlier, so I don't need to call MyInterfaceUninitialize() function? EDIT: Thanks for all your help and explanation. Now i understand that this is a design issue. If i want to stay with my current solution, i need to call MyInterfaceUninitialize() function in my EXE. If i don't do it, it also OK, because the singleton destroys itself, when it leaves the EXE scope (but i need to live with disturbing debugger messages). The only way to avoid this behavior, is to rethink the whole implementation. I can also set my DLL as "Delay Loaded DLLs" under Linker->Input in Visual Studio, to get rid of disturbing debugger messages.
If i don't call MyInterfaceUninitialize() from my EXEs ExitInstance(), i have a memory leak (m_pName pointer). Why does it happening? This is not a leak, this is the way auto_ptrs are supposed to work. They release the instance when they go out of scope (which in your case is when the dll is unloaded). It looks like the destruction off MySingleton happens after EXEs exit. Yes. Is it possible to force the DLL or EXE to destroy the MySingleton a little bit earlier, so I don't need to call MyInterfaceUninitialize() function? Not without calling this function.
1,643,820
1,643,874
Why no warning with "#if X" when X undefined?
I occasionally write code something like this: // file1.cpp #define DO_THIS 1 #if DO_THIS // stuff #endif During the code development I may switch the definition of DO_THIS between 0 and 1. Recently I had to rearrange my source code and copy some code from one file to another. But I found that I had made a mistake and the two parts had become separated like so: // file1.cpp #define DO_THIS 1 and // file2.cpp #if DO_THIS // stuff #endif Obviously I fixed the error, but then thought to myself, why didn't the compiler warn me? I have the warning level set to 4. Why isn't #if X suspicious when X is not defined? One more question: is there any systematic way I could find out if I've made the same mistake elsewhere? The project is huge. EDIT: I can understand having no warning with #ifdef that makes perfect sense. But surely #if is different.
gcc can generate a warning for this, but its probably not required by the standard: -Wundef Warn if an undefined identifier is evaluated in an `#if' directive.
1,643,909
1,646,184
Get window handle on which mouse button was clicked
Hey, I'm using Windows Hook, I installed the mouse hook, system-wide and its working perfectly. Now there is a problem, I need to the get window handle on which the mouse was clicked.. How do I do that? Does the Mouse hook event passes us that information?
Since you're using WH_MOUSE_LL, you're making a low-level mouse hook, which actually receives a pointer to a MSLLHOOKSTRUCT that doesn't have an hwnd member. You need to set a normal mouse hook using WH_MOUSE; you'll then get a pointer to the MOUSEHOOKSTRUCT that you're expecting..
1,644,121
1,644,183
Storing data of unknown size in C++
I've been using PHP for about 4 years, however I've come across a problem that requires something with slightly (:P) better performance and so I've chosen C++. The program I'm writing is a Linux daemon that will scan a MySQL database for URLs to load, load them using cURL, search for a specified string, and then update the database accordingly. The problem that I'm facing is that I don't know the size of the data that needs to be stored in a variable in order to be searched for a specific string. I had the idea of using a linked list and allocating more nodes as the data fills the list. Is this a good way to go about doing things? Thanks in advance,
in c++ the vector class can store an unknown sized amount of data. #include <string> #include <vector> std::vector <std::string>Data; std::string newData = "a String"; Data.push_back(newData); std::string otherData = "a different String"; Data.push_back(otherData); of course 'string' could be any data type you want, and you can access the data using the Data[0] to return the first string, and you can use Data.size() to return the amount of strings in the vector/array. for(int x = 0; x != Data.size(); x++) { //Do what you want with the data here using Data[x] }
1,644,172
1,767,464
Building Qt 4.5 with Visual C++ 2010
Did somebody tried to build Qt 4.5 with Visual Studio 2010 (Beta 2)? Any hints on doing that successfuly? Later edit I tried to run configure from a Visual Studio 2010 console. There is no makespecs support for 2010, so configure fails because of that.
It worked for me to build just as if it was vs2008, but using the vs2010 tools: Open vs2010 command prompt. cd into the top-level Qt directory. configure.exe -platform win32-msvc2008 -no-webkit -no-phonon -no-phonon-backend -no-script -no-scripttools -no-multimedia -no-qt3support -fast nmake
1,644,212
3,870,775
Connecting multiple devices through RAPI2
The Microsoft RAPI2 interface is designed with the ability to talk to multiple devices. But, ActiveSync 4.5.0 allows only allows one device at a time to connect and only allows it over a USB connection. Is there a way to write a client-server piece for the desktop and mobile device that will allow more than one device to connect to the desktop through a RAPI2 connection? Preferably some way to put RAPI2 over TCP/IP. Thanks, PaulH
In msdn they wrote this: For Windows CE 5.0 and earlier, this enumeration sequence will only contain a single connected device.
1,644,325
1,649,788
C# call to unmanaged C++ returning string of squares symbols
I have some C# code calling into an unmanaged C++ DLL. The method I am calling is intended to accept a string as a ref. To handle this I pass in a StringBuilder, otherwise there is a StackOverflowException. This is working fine, but on some calls the string that comes back from the unmanaged code is a jumbled string like this: øŸE˜.,Ê. I know this must have something to do with encoding, but I've tried several things, listed below, and nothing works. This is not an issue in VB.Net code that someone else has written to do something similar. Here's what I've tried: 1. I'm using this: [DllImport("dmphnx32.dll")], but have tried all Charset options without success. Tried to use Encoding.Default.GetBytes, Encoding.ASCII, Encoding.Unicode, and the rest without success. I don't have any experience with C++ so I can really use the help. Here's the DLLIMport method: [DllImport("dmphnx32.dll")] public static extern int PhxQueryDataAttributes(int handle, StringBuilder lTableName, StringBuilder lColumnName, ref short lIteration, ref short type, ref short maxLen, ref short endorsement, StringBuilder endorsementId); Here's the C++ code: short DMEXP PhxQueryDataAttributes(HWND handle, char *lTableName, char *lColumnName, short *lIteration, short *Type, short *MaxLen, short *Endorsement, char *EndorsementID) { handle = PhxInfo.HiddenHwnd; strcpy(lTableName, PhxInfo.TableName); strcpy(lColumnName, PhxInfo.ColumnName); *Type = PhxInfo.PhnxDataType; // max len *MaxLen = PhxInfo.MaxDataLen; *Endorsement = PhxInfo.Endorsement; strcpy(EndorsementID, PhxInfo.EndorsementID); // determine which table we need the iteration of *lIteration = PhxIterationArray[PhxInfo.sEffectiveTableID]; return SUCCESS; } Here's the C# code that calls into the unmanaged code: public int PhxQueryDataAttributes(int handle, ref string lTableName, ref string lColumnName, ref short lIteration, ref short type, ref short maxLen, ref short endorsement, ref string endorsementId) { var sbTableName = new StringBuilder(); var sbColName = new StringBuilder(); var sbEndId = new StringBuilder(); var ret = RatingProxy.PhxQueryDataAttributes(handle, sbTableName, sbColName, ref lIteration, ref type, ref maxLen, ref endorsement, sbEndId); lTableName = sbTableName.ToString(); lColumnName = sbColName.ToString(); endorsementId = sbEndId.ToString(); return ret; } Thanks, Corey
After I tried the first 2 answers and learned that they weren't helping, I knew that something else must be suspect. I found a small bug somewhere else in my app where I was actually missing an initialization param on the unmanaged code. This was causing my strangely encoded string. Thanks for the help, Corey
1,644,490
1,647,690
emacs completions or IntelliSense the same as on Visual Studio
emacs 22.2.1 on Linux I am doing some C/C++ programming using emacs. I am wondering does emacs support completions (IntelliSense in Visual Studio). For example when filling structures I would like to see the list of members when I type the dot operator or arrow operator. The same would go for function signatures that give me the types I am passing would display.
I am using cedet with emacs. I tried using the cedet version in Debian but it has some bugs so I uninstalled that and downloaded the cvs version from http://sourceforge.net/projects/cedet/develop I compiled it in my ~/tmp/emacs-stuff/ directory and then added the following lines to my ~/.emacs.d/custom.el file: ;;needed if cedet is in a custom location (load-file "~/tmp/emacs-stuff/cedet/common/cedet.el") ;; Enable EDE (Project Management) features (global-ede-mode t) ;;to enable code folding (global-semantic-tag-folding-mode) ;; Enabling Semantic (code parsing, smart completion) features ;; (select only one) ;;(semantic-load-enable-minimum-features) ;;(semantic-load-enable-code-helpers) (semantic-load-enable-gaudy-code-helpers) ;;(semantic-load-enable-all-exuberent-ctags-support) (global-semantic-idle-scheduler-mode 1) ;The idle scheduler with automatically reparse buffers in idle time. (global-semantic-idle-completions-mode 1) ;Display a tooltip with a list of possible completions near the cursor. (global-semantic-idle-summary-mode 1) ;Display a tag summary of the lexical token under the cursor. ;;to work with my include files and cedet (semantic-add-system-include "~/include" 'c++-mode) (semantic-add-system-include "~/include" 'c-mode) ;;To use additional features for names completion, and displaying of information for tags & classes, ;; you also need to load the semantic-ia package. This could be performed with following command: (require 'semantic-ia) ;;to work with systme include files and gcc (require 'semantic-gcc) ;;integrate semantic with Imenu (defun my-semantic-hook () (imenu-add-to-menubar "TAGS")) (add-hook 'semantic-init-hooks 'my-semantic-hook) ;;load Semanticdb (require 'semanticdb) ;;(global-semanticdb-minor-mode 1) ;;working with tags ;; gnu global support (require 'semanticdb-global) (semanticdb-enable-gnu-global-databases 'c-mode) (semanticdb-enable-gnu-global-databases 'c++-mode) ;; ctags (require 'semanticdb-ectag) (semantic-load-enable-primary-exuberent-ctags-support) (defun my-semantic-hook () (imenu-add-to-menubar "TAGS")) (add-hook 'semantic-init-hooks 'my-semantic-hook) This file gets called by my ~/.emacs file which the following line in it: (load-file "~/.emacs.d/custom.el") Now when you are typing a variable and press CTRL+SHIFT+ENTER, a menu of selections will come up with suggestions. Further, if you have set semantic-complete-inline-analyzer-idle-displayor-class variable to quote semantic-displayor-tooltip, a tooltip with suggestions will also come up after some idle time (1 or 2 seconds). For some short intro, see http://xtalk.msk.su/~ott/en/writings/emacs-devenv/EmacsCedet.html For Cedet docs, see: http://cedet.sourceforge.net/ Good luck.
1,644,598
1,647,213
Firing a COM Event From Another Thread
I have created an in-process COM object (DLL) using ATL. Note that this is an object and not a control (so has no window or user-interface.) My problem is that I am trying to fire an event from a second thread and I am getting a 'Catastrophic failure' (0x8000FFFF). If I fire the event from my main thread, then I don't get the error. The second thread is calling CoInitializeEx but this makes no difference. I am using the Apartment threading model but switching to Free Threaded doesn't help. The fact I am trying to do this from a second thread is obviously crucial. Is there an easy way to do this or am I going to have to implement some hidden-window form of messaging? For example, in my main object's source file: STDMETHODIMP MyObject::SomeMethod(...) { CreateThread(NULL, 0, ThreadProc, this, 0, NULL); // Succeeds with S_OK FireEvent(L"Hello, world!"); return S_OK; } DWORD WINAPI ThreadProc(LPVOID param) { CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); MyObject* comObject = reinterpret_cast<MyObject*>(param); // Fails with 0x8000FFFF comObject->FireEvent(L"Hello, world!"); } void MyObject::FireEvent(BSTR str) { ... // Returns 0x8000FFFF if called from ThreadProc // Returns S_OK if called from SomeMethod pConnection->Invoke(dispid, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, &params, NULL, NULL, NULL); }
COM basics In STA your object lives on a single thread (The Thread). This thread is the one it's created on, it's methods are executed on and it's events are fire on. The STA makes sure that no two methods of your object are executed simultaneously (because they have to be executed on The Thread so this is a nice consequence). This does not mean that your object can't be accessed from other threads. This is done by creating proxies of your object for every thread other than The Thread. On The Thread you pack an IUnknown with CoMarshalInterThreadInterfaceInStream and on the other thread you unpack with CoGetInterfaceAndReleaseStream which actually creates the proxy on the other thread. This proxy uses the message pump to sync calls to you object, calls that are still executed on The Thread, so The Thread has to be free (not busy) to executed a call from another thread. In your case you want your object to be able to execute methods on one thread and rise events on another thread. So this has to happen in MTA, so your object has to live in MTA, so your class has to be free-threaded. Threads belong to exactly one apartment, so a thread can not be in MTA and STA simultaneously. If your object lives in MTA whenever an STA object tries to use it, it will have to create a proxy. So you get a slight overhead. What I guess is that you are thinking of some very clever "technique" to offload your main thread, and do some "async" events, which will not fly in the end :-)) If you think about it there has to a listener on this second [worker] thread... Btw, this line MyObject* comObject = reinterpret_cast<MyObject*>(param); can be done in MTA only.
1,644,619
1,644,742
CPython is bytecode interpreter?
I don't really get the concept of "bytecode interpreter" in the context of CPython. Can someone shed some light over the whole picture? Does it mean that CPython will compile and execute pyc file (bytecode file?). Then what compile py file to pyc file? And how is Jython different from CPython (except they are implemented in different languages). I also read somewhere that Python is C++ interpretation. Is this correct? And what does that mean? I'm still very new to Python, so forgive me if I ask the dumb questions... Thank you so much!
CPython is the implementation of Python in C. It's the first implementation, and still the main one that people mean when they talk about Python. It compiles .py files to .pyc files. .pyc files contain bytecodes. The CPython implementation also interprets those bytecodes. CPython is not written in C++, it is C. The compilation from .py to .pyc happens transparently as needed. When you execute a .py file, it will first be compiled to a .pyc file if needed, then the .pyc file will be interpreted. Jython is different because (in addition to being implemented in Java instead of C) it compiles .py files into .class files so they can be executed in the JVM.
1,645,309
1,645,446
Help me evaluate this casting
I found this in the PowerVR mesh drawing code and I don't really know how to read it. &((unsigned short*)0)[3 * mesh.sBoneBatches.pnBatchOffset[batchNum]] What is going on here? Is this a reference to void cast as an unsigned short pointer and then offset by (3*mesh(etc...) + batchNum)? It's breaking my brain. It's found in the context of a glDrawElements call: glDrawElements(GL_TRIANGLES, i32Tris * 3, GL_UNSIGNED_SHORT, &((unsigned short*)0)[3 * mesh.sBoneBatches.pnBatchOffset[batchNum]]);
Let's go from the inside out. (unsigned short*)0 This is casting 0 to an unsigned short pointer. This will be used for computing a memory offset, computed in terms of the size of an unsigned short. 3 * mesh.sBoneBatches.pnBatchOffset[batchNum] This is, presumably, the offset in memory of some batch of triangles. A triangle is composed of 3 shorts, so it looks like they are storing an offset in terms of numbers of triangles, and then multiplying by 3 to get the number of shorts. ((unsigned short*)0)[3 * mesh.sBoneBatches.pnBatchOffset[batchNum]] This is now using that 0 pointer to find the memory location of the given offset. This would normally return the value of that memory location, but they want a pointer to pass into glDrawElements, so the use the & operator to get a pointer to that memory location: &((unsigned short*)0)[3 * mesh.sBoneBatches.pnBatchOffset[batchNum]]
1,645,324
1,645,344
Is it a good practice to always create a .cpp for each .h in a C++ project?
Some classes, like exceptions or templates, only need the header file (.h), often there is no .cpp related to them. I have seen some projects were (for some classes) there aren't any .cpp files associated to the headers files, perhaps because the implementation is so short that it is done directly in the .h, or maybe for other reasons, such as template classes, where it is mandatory to include the implementation in the header. What is your opinion, if a class is too short, sould I avoid creating a .cpp file and writing the code directly on the header file ? If the code is written in the header file, should I include an empty .cpp so the files in the project remains consistent ?
I wouldn't add unnecessary .cpp files. Each .cpp file you add must be compiled, which just slows down the build process. In general, using your class will only require the header file anyways - I see no advantage to an "empty" .cpp file for consistency in the project.
1,645,326
1,645,365
non-blocking thread-safe queue in C++?
Is there a thread-safe, non-blocking queue class in the C++? Probably a basic question but I haven't been doing C++ for a long time... EDIT: removed STL requirement.
Assuming your CPU has a double-pointer-wide compare-and-swap (compxchg8b on 486 or higher, compxchg16b on most amd64 machines [not present on some early models by Intel])... There is an algorithm here. Update: It's not hard to translate this to C++ if you aren't afraid of doing a bit of work. :P This algorithm assumes a "pointer with tag" structure which looks like this: // Be aware that copying this structure has to be done atomically... template <class T> struct pointer { T *ptr; uintptr_t tag; }; Then you want to wrap the instructions lock cmpxchg{8|16}b with some inline asm... Maybe then you can write the queue node like this: template <class T> struct queue_node { T value; pointer<queue_node<T> > next; }; The rest is more or less a transcription of the algorithm I linked to...
1,645,474
1,645,499
C++ Boost: is it included by default in most Linux distros?
Is the C++ Boost library usually included by default on most Linux distros?
Many distributions include boost in their official repositories, but do not provide it by default on a standard install (in other words, it's not installed by default, but is relatively easy to install). On the other hand, presuming you're asking this because you're wondering if you can use boost in a project that you want to work on many distributions: most of boost's libraries are header only because they're templates, which means they get compiled into your project and it doesn't matter whether or not a distribution has them installed (same effect as statically linking). For those parts of boost that aren't header only, you can statically link and still make a binary that will run on distros that don't come with boost.
1,645,492
1,645,583
std::map, references, pointers and memory allocation
I am having a lil hard time with map and the valuetype allocation. consider this simple class: class Column { private: char *m_Name; public: // Overrides const char *Name(){ return this->m_Name; } // Ctors Column(const char *NewName){ this->m_Name = new char[strlen(NewName) + 1]; strcpy(this->m_Name, NewName); } // Dtors ~Column(){ cout << "wtf?\n"; delete this->m_Name; } }; now I have this map: // Typedefs typedef std::map<int, Column> ColumnContainer; ColumnContainer *m_Container; When i call this: Column *c = new Column("Test"); cout << "CREATED: " << c->Name() << "\n"; it = this->m_Container->insert(std::make_pair(0, *c)).first; cout << "AGAIN: " << c->Name() << "\n"; the console is printing the "wtf?" after the insert in the map. it seems to be destroying the column. Is this right? or am I doing something wrong? I was wondering if the value_type of the std::map has to a struct type with defined memory size, like with POD or array of POD? the cout << AGAIN doesn't print the "Test" what I need is a map to a columns based on int key
The underlying reason why your string m_Name doesn't print the second time is because of the way the STL builds a map. It makes various copies of the value during its insertion. Because of this, m_Name gets destroyed in one of the copies of the original column. Another piece of advice is to use pointers to objects when the object is a value in the map. Otherwise you could be taking a major performance hit of the object is large enough.
1,645,913
1,645,924
Inserting objects into hash table (C++)
This is my first time making a hash table. I'm trying to associate strings (the keys) with pointers to objects (the data) of class Strain. // Simulation.h #include <ext/hash_map> using namespace __gnu_cxx; struct eqstr { bool operator()(const char * s1, const char * s2) const { return strcmp(s1, s2) == 0; } }; ... hash_map< const char *, Strain *, hash< const char * >, struct eqstr > liveStrainTable; In the Simulation.cpp file, I attempt to initialize the table: string MRCA; for ( int b = 0; b < SEQ_LENGTH; b++ ) { int randBase = rgen.uniform(0,NUM_BASES); MRCA.push_back( BASES[ randBase ] ); } Strain * firstStrainPtr; firstStrainPtr = new Strain( idCtr, MRCA, NUM_STEPS ); liveStrainTable[ MRCA ]= firstStrainPtr; I get an error message that reads "no match for ‘operator[]’ in ‘((Simulation*)this)->Simulation::liveStrainTable[MRCA]’." I've also tried using "liveStrainTable.insert(...)" in different ways, to no avail. Would really love some help on this. I'm having a difficult time understanding the syntax appropriate for SGI hash_map, and the SGI reference barely clarifies anything for me. Thanks.
Try liveStrainTable[ MRCA.c_str() ]= firstStrainPtr;. It expects const char * as type of key value, but MRCA has type string. Another way is to change liveStrainTable to: hash_map< string, Strain *, hash<string>, eqstr > liveStrainTable;
1,645,978
1,646,011
C/C++ function/method decoration
DISCLAIMER: I haven't done C++ for some time... Is it common nowadays to decorate C/C++ function/method declarations in order to improve readability? Crude Example: void some_function(IN int param1, OUT char **param2); with the macros IN and OUT defined with an empty body (i.e. lightweight documentation if you will in this example). Of course I understand this goes somewhat in parallel with the "doc comment block" associated with the method/function. Could you provide some other examples... assuming this topic is useful to the community. Please bear in mind that the example above is just what it is.
I wouldn't appreciate such decoration. Much better to use const and references and constant references, like in void some_function(AClass const &param1, AnotherClass &param2) Usually int are passed by value and not by reference, so I used AClass and AnotherClass for the example. It seems to me that adding empy IN and OUT would be distracting.
1,646,163
1,646,248
Does an ATL COM Object Have a Message Pump?
If you create a new ATL project and add a simple COM object to it (note: an object and not a control) that uses the Apartment threading model, will there be a message pump running under the hood? I want to create a hidden window that is a member of my COM object class but I'm not sure if any messages will actually be delivered to it or not. Is this handled behind the scenes or does it matter what sort of application is actually creating the COM object?
No, an ATL COM object does not implement a message pump by default. Your code must explicitly use on via a normal Windowing library or explicit message pump implementation.
1,646,266
1,646,288
Difference between hash_map and unordered_map?
I recently discovered that the implementation of the hash map in C++ will be called unordered_map. When I looked up why they weren't just using hash_map, I discovered that apparently there are compatibility issues with the implementation of hash_map that unordered_map resolves (more about it here). That wiki page doesn't give much more information so I wondering if anyone knew some of the issues with hash_map that unordered_map resolves.
Since there was no hash table defined in the C++ standard library, different implementors of the standard libraries would provide a non-standard hash table often named hash_map. Because these implementations were not written following a standard they all had subtle differences in functionality and performance guarantees. Starting with C++11 a hash table implementation has been added to the C++ standard library standard. It was decided to use an alternate name for the class to prevent collisions with these non-standard implementations and to prevent inadvertent use of the new class by developers who had hash_table in their code. The chosen alternate name is unordered_map which really is more descriptive as it hints at the class's map interface and the unordered nature of its elements.
1,646,312
1,647,812
What caused the mysterious duplicate entry in my stack?
I'm investigating a deadlock bug. I took a core with gcore, and found that one of my functions seems to have called itself - even though it does not make a recursive function call. Here's a fragment of the stack from gdb: Thread 18 (Thread 4035926944 (LWP 23449)): #0 0xffffe410 in __kernel_vsyscall () #1 0x005133de in __lll_mutex_lock_wait () from /lib/tls/libpthread.so.0 #2 0x00510017 in _L_mutex_lock_182 () from /lib/tls/libpthread.so.0 #3 0x080d653c in ?? () #4 0xf7c59480 in ?? () from LIBFOO.so #5 0x081944c0 in ?? () #6 0x081944b0 in ?? () #7 0xf08f3b38 in ?? () #8 0xf7c3b34c in FOO::Service::releaseObject () from LIBFOO.so #9 0xf7c3b34c in FOO::Service::releaseObject () from LIBFOO.so #10 0xf7c36006 in FOO::RequesterImpl::releaseObject () from LIBFOO.so #11 0xf7e2afbf in BAR::BAZ::unsubscribe (this=0x80d0070, sSymbol=@0xf6ded018) at /usr/lib/gcc/x86_64-redhat-linux/3.4.6/../../../../include/c++/3.4.6/bits/stl_tree.h:176 ...more stack I've elided some of the names: FOO & BAR are namespaces.BAZ is a class. The interesting part is #8 and #9, the call to Service::releaseObject(). This function does not call itself, nor does it call any function that calls it back... it is not recursive. Why then does it appear in the stack twice? Is this an artefact created by the debugger, or could it be real? You'll notice that the innermost call is waiting for a mutex - I think this could be my deadlock. Service::releaseObject() locks a mutex, so if it magically teleported back inside itself, then a deadlock most certainly could occur. Some background: This is compiled using g++ v3.4.6 on RHEL4. It's a 64-bit OS, but this is 32-bit code, compiled with -m32. It's optimised at -O3. I can't guarantee that the application code was compiled with exactly the same options as the LIBFOO code. Class Service has no virtual functions, so there's no vtable. Class RequesterImpl inherits from a fully-virtual interface, so it does have a vtable.
The reason you get "bad" stack is that __lll_mutex_lock_wait has incorrect unwind descriptor (it is written in hand-coded assembly). I believe this was fixed somewhat recently (in 2008), but can't find the exact patch. Once the GDB stack unwinder goes "off balance", it creates bogus frames (#2 through #8), but eventually stumbles on a frame which uses frame pointer, and produces correct stack trace for the rest of the stack.
1,646,672
1,646,714
Boost installation -Simplified Build From Source
As mentioned in the docs what do i need to install to run the commands : bootstrap .\bjam The BoostPro Computing folks maintain the Boost installer for Windows, but if I first run the installer and download a minimal build and then run the installer again, the installer doesn't detect that I've already installed Boost already and I need some more libraries. Is there a way around ?
Set up Your BOOST_ROOT environment variable first: winXP: set BOOST_ROOT=D:\your\boost\sources then in the BOOST_ROOT directory run: boostrap.bat this will create your bjam.exe and it's environment. Next step is to invoke: bjam toolset=msvc stage This will compile Your boost library and place all libs into the folder: %BOOST_ROOT%\stage\lib If you want to build everything use: bjam toolset=msvc -a --build-type=complete stage instead stage you can put install this will simply install this to lib. During building there will be created huge directory bin.v2 with all object files. Total installation is aprox: 1.5 GB for libs (shared+static+debug&release).
1,646,994
1,648,013
boost lib build configuration variations
I am new to boost - can you please tell me what are the difference b/w the following variations of the boost lib and which one do I need to link to in which case? libboost_unit_test_framework-vc80-1_35.lib libboost_unit_test_framework-vc80-gd-1_35.lib libboost_unit_test_framework-vc80-mt-1_35.lib libboost_unit_test_framework-vc80-mt-gd-1_35.lib libboost_unit_test_framework-vc80-mt-s-1_35.lib libboost_unit_test_framework-vc80-mt-sgd-1_35.lib libboost_unit_test_framework-vc80-s-1_35.lib libboost_unit_test_framework-vc80-sgd-1_35.lib Well, what I actually after is to understand the whole taxonomy of the _gd, mt, sgd things.
Here is the link to the docs for full info on what the many suffixes means: windows: http://www.boost.org/doc/libs/1_40_0/more/getting_started/windows.html#library-naming linux: http://www.boost.org/doc/libs/1_40_0/more/getting_started/unix-variants.html#library-naming Although it seems it's the same anyway so either link should be good.
1,647,261
1,647,269
Way to link 2 variables in a class in C++
Say I wanted to have one variable in a class always be in some relation to another without changing the "linked" variable explicitly. For example: int foo is always 10 less than int bar. Making it so that if I changed bar, foo would be changed as well. Is there a way to do this? (Integer overflow isn't really possible so don't worry about it.) Example: (Obviously doesn't work, but general code for an understanding) class A { int x; int y = x - 10; // Whenever x is changed, y will become 10 less than x };
No, you can't do that. Your best option for doing this is to use accessor and mutator member functions: int getFoo() { return foo_; } void setFoo(int newFoo) { foo_ = newFoo; } int getBar() { return foo_ + 10; } void setBar(int newBar) { foo_ = newBar - 10; }
1,647,298
1,647,316
Why don't STL containers have virtual destructors?
Does anyone know why the STL containers don't have virtual destructors? As far as I can tell, the only benefits are: it reduces the size of an instance by one pointer (to the virtual method table) and it makes destruction and construction a tiny bit faster. The downside is that it's unsafe to subclass the containers in the usual way. Another way my question could be rephrased is "Why weren't STL containers designed to allow for inheritance?" Because they don't support inheritance, one is stuck with the following choices when one wants to have a new container that needs the STL functionality plus a small number of additional features (say a specialized constructor or new accessors with default values for a map, or whatever): Composition and interface replication: Make a new template or class that owns the STL container as a private member and has one pass-through inline method for each STL method. This is just as performant as inheritance, avoids the cost of a virtual method table (in the cases where that matters). Unfortunately, the STL containers have fairly broad interfaces so this requires many lines of code for something that should seemingly be easy to do. Just make functions: Use bare (possibly templated) file-scoped functions instead of trying to add member functions. In some ways this can be a good approach, but the benefits of encapsulation are lost. Composition with public STL access: Have the owner of the STL container let users access the STL container itself (perhaps guarded through accessors). This requires the least coding for the library writer, but it's much less convenient for users. One of the big selling points for composition is that you reduce coupling in your code, but this solution fully couples the STL container with the owner container (because the owner returns a true STL container). Compile-time polymorphism: Can be somewhat tricky to do write, requires some code gymnastics, and isn't appropriate for all situations. As a side question: is there a standards-safe way of subclassing with non-virtual destructors (let's assume that I don't want to override any methods, just that I want to add new ones)? My impression is that there is no generic and safe way of doing this if one does not have the power to change the code defining the non-virtual class.
I guess it follows the C++ philosophy of not paying for features that you don't use. Depending on the platform, a pointer for the virtual table could be a hefty price to pay if you don't care about having a virtual destructor.
1,647,327
1,647,394
C++ : struggle with generic const pointer
I've run into some annoying issues with const-correctness in some templated code, that ultimately boils down to the following observation: for some reason, given an STL-ish Container type T, const typename T::pointer does not actually seem to yeild a constant pointer type, even if T::pointer is equivalent to T::value_type*. The following example illustrates the problem. Suppose you have a templated function that takes a Container which must meet the STL Random Access Container concept requirements. template <class Container> void example(Container& c) { const typename Container::pointer p1 = &c[0]; // Error if c is const const typename Container::value_type* p2 = &c[0]; } Then, if we pass this function a const container... const std::vector<int> vec(10); example(vec); ...we get an invalid conversion from const int* to int*. But why is const typename Container::pointer not the same as const int* in this example? Note that if I change const typename Container::pointer to simply typename Container::const_pointer it compiles fine, however, as far as I can tell, the const_pointer typedef is an extension, (I don't see it mentioned in the C++ standard Container Requirements (23.5, Table 65)), and so therefore I don't want to use it. So how can I obtain a generic, const-correct pointer type from a container T? (I really can't see how to do this without using boost::mpl::if_ along with type_traits to check if the container is constant...but there must be a less verbose way to do this) Edit: In case it matters, I'm using gcc 4.3.2 to compile this.
It doesn't work because your const does not apply to what you think it applies to. For example, if you have typedef int* IntPtr; then const IntPtr p; does not stand for const int* p; but rather stands for int* const p; Typedef-name is not a macro. Once the "pointerness" of the type is wrapped into a typedef-name, there's no way to use it to create a pointer-to-const type anymore. I.e. there's absolutely no way to use the above IntPtr typedef-name to produce an equivalent of const int* p; You have to either use to pointee type explicitly (as you did with value_type), or check whether your container defines a different typedef-name, with const already wrapped "inside" (like const_pointer or something like that).
1,647,373
1,647,437
Difference between pass-by-reference & and *?
What is the difference between passing-by-reference and using the C pointer notation? void some_function(some_type& param) and void some_function(some_type *param) Thanks
When you pass a pointer to a variable in a subroutine call, the address of that variable is passed to the subroutine. To access the variable in the subroutine, the pointer has to be dereferenced. When you pass a reference to a variable, the compiler takes care of obtaining the address of the variable when the variable is passed to the subroutine and dereferencing the variable in the subroutine.
1,647,469
1,647,699
Nokia QT 4 for Visual Studio 2005 and Visual Studio 2008
I downloaded the latest open source version of QT4-and its installed in c:\qt\2009.04. I've also downloaded the QT4 Visual Studio add-in 1.1.0. I want to set it up for both Visual Studio 2005 and Visual Studio 2008 . Most of the docs online are for older versions. What steps do I follow?
Current docs are at link text. However, most for most of the basics, any QT4.x documentation will lead you in the right direction. Do use their demo programs. They are really, really good at showing how to do things. I've built a few applications using them as a starting point. The integration with VS is via Visual Studio Add-IN. Installs like any other plug in. Couple of things to watch out for - If you want to use their integration, you have to create project as a QT project. Add a QT based class to an existing project works fine as long as you don't use any events. DO NOT CHANGE their default directory structure for QT projects. If you do, their pre-compilers to generate event handling code will not work unless you are really good at editing project files. Good Luck, I really liked programming in it (back to c#). Especially their new graphics/animation code. If you now .NET programming, most of the concepts are the same in QT, just different syntax.
1,647,557
1,647,574
ifstream: how to tell if specified file doesn't exist
I want to open a file for reading. However, in the context of this program, it's OK if the file doesn't exist, I just move on. I want to be able to identify when the error is "file not found" and when the error is otherwise. Otherwise means I need to quit and error. I don't see an obvious way to do this with fstream. I can do this with C's open() and perror(). I presumed that there was a fstream way to do this as well.
Since the result of opening a file is OS-specific, I don't think standard C++ has any way to differentiate the various types of errors. The file either opens or it doesn't. You can try opening the file for reading, and if it doesn't open (ifstream::is_open() returns false), you know it either doesn't exist or some other error happened. Then again, if you try to open it for writing afterwards and it fails, that might fall under the "something else" category.
1,647,621
1,647,655
Deleting a Shared Pointer
I have a pointer to a QScriptEngine that I'm passing through the overloaded class constructor of class Evaluator and assigns it to QScriptEngine *engine_ (class Property subclasses Evaluator, and calls this constructor of Evaluator, passing it an already allocated QScriptEngine). The constructor with no arguments creates the new QScriptEngine pointer (class Generic subclasses Evaluator in this way). In the destructor I test if engine_ is not NULL, delete the pointer, then assign it NULL. Should the pointer (engine_) in the derived Property now also be NULL? Something tells me this is not the case. If not, how do you deal with this situation? I need the QScriptEngine to be the same instance throughout. QScriptEngine's = operator is private, or I would be avoiding the pointer all together. I saw some info on shared pointers (boost::shared_ptr and std:tr1::shared_ptr) in another SO question. I'm already using boost for the regex library, so boost is not out of the question if that's the best way to deal with this. Hopefully there's a non-boost way, for general C++ knowledge and future projects.
You can solve this by giving one of the classes (class A) lifetime control of that pointer, along with a 'getter' method. The other class (class B) would always call A's getter whenever it needed the pointer. That way, A remains in control of the pointer at all times. Downside is the getter function (it will probably inline, but it's still a second indirection). Also, B is going to have to check that pointer for NULL on pretty much every use. Your other choice is to wrap the pointer in something like boost::shared_ptr which takes care of the problem (if used properly) by holding the underlying pointer, and only deleting it when all objects that share that pointer are deleted. You could write this yourself, but since you already have boost in play, I'd just use their implementation. A third choice is to re-factor the whole thing so that you don't need a shared pointer. I'd personally never design a C++ program that needed shared pointers, just because it's a spot where memory management bugs could easily creep in over the years, but that's just me.
1,647,631
1,647,679
C state-machine design
I am crafting a small project in mixed C and C++. I am building one small-ish state-machine at the heart of one of my worker thread. I was wondering if you gurus on SO would share your state-machine design techniques. NOTE: I am primarily after tried & tested implementation techniques. UPDATED: Based on all the great input gathered on SO, I've settled on this architecture:
State machines that I've designed before (C, not C++) have all come down to a struct array and a loop. The structure basically consists of a state and event (for look-up) and a function that returns the new state, something like: typedef struct { int st; int ev; int (*fn)(void); } tTransition; Then you define your states and events with simple defines (the ANY ones are special markers, see below): #define ST_ANY -1 #define ST_INIT 0 #define ST_ERROR 1 #define ST_TERM 2 : : #define EV_ANY -1 #define EV_KEYPRESS 5000 #define EV_MOUSEMOVE 5001 Then you define all the functions that are called by the transitions: static int GotKey (void) { ... }; static int FsmError (void) { ... }; All these function are written to take no variables and return the new state for the state machine. In this example global variables are used for passing any information into the state functions where necessary. Using globals isn't as bad as it sounds since the FSM is usually locked up inside a single compilation unit and all variables are static to that unit (which is why I used quotes around "global" above - they're more shared within the FSM, than truly global). As with all globals, it requires care. The transitions array then defines all possible transitions and the functions that get called for those transitions (including the catch-all last one): tTransition trans[] = { { ST_INIT, EV_KEYPRESS, &GotKey}, : : { ST_ANY, EV_ANY, &FsmError} }; #define TRANS_COUNT (sizeof(trans)/sizeof(*trans)) What that means is: if you're in the ST_INIT state and you receive the EV_KEYPRESS event, make a call to GotKey. The workings of the FSM then become a relatively simple loop: state = ST_INIT; while (state != ST_TERM) { event = GetNextEvent(); for (i = 0; i < TRANS_COUNT; i++) { if ((state == trans[i].st) || (ST_ANY == trans[i].st)) { if ((event == trans[i].ev) || (EV_ANY == trans[i].ev)) { state = (trans[i].fn)(); break; } } } } As alluded to above, note the use of ST_ANY as wild-cards, allowing an event to call a function no matter the current state. EV_ANY also works similarly, allowing any event at a specific state to call a function. It can also guarantee that, if you reach the end of the transitions array, you get an error stating your FSM hasn't been built correctly (by using the ST_ANY/EV_ANY combination. I've used code similar for this on a great many communications projects, such as an early implementation of communications stacks and protocols for embedded systems. The big advantage was its simplicity and relative ease in changing the transitions array. I've no doubt there will be higher-level abstractions which may be more suitable nowadays but I suspect they'll all boil down to this same sort of structure. And, as ldog states in a comment, you can avoid the globals altogether by passing a structure pointer to all functions (and using that in the event loop). This will allow multiple state machines to run side-by-side without interference. Just create a structure type which holds the machine-specific data (state at a bare minimum) and use that instead of the globals. The reason I've rarely done that is simply because most of the state machines I've written have been singleton types (one-off, at-process-start, configuration file reading for example), not needing to run more than one instance. But it has value if you need to run more than one.
1,647,649
1,647,671
Do shallow copies share pointers? (C++)
I know that if I do something like this: class Obj { public: int* nine; }; Obj Obj1; //Awesome name int eight = 8; Obj1.nine = &eight; Obj Obj2 = Obj1; //Another Awesome name then Obj1's and Obj2's nines will point to the same 8, but will they share the same pointer? I.e.: int Necronine = 9; Obj1.nine = &Necronine; Obj2.nine == ??? will Obj2's nine point to Necronine, or will it remain pointing at 8?
will Obj2's nine point to Necronine, or will it remain pointing at 8? It will remain pointing at 8. When this line is executed: Obj Obj2 = Obj1; // every object has his own pointer the value(copy) of obj1.nine is copied into obj2.nine and thats it.
1,647,723
1,647,733
strings.h and wrapping this macro with a macro check of whether
I infer from Google search results that strings.h (from here) is for UNIX systems. I would like to wrap the following line with a macro check of whether the host's operating system is Linux/UNIX. It would be much appreciated to hear suggestions about it. Thanks in advance. #include <strings.h>
One option would be: #ifndef _WIN32 #include <strings.h> #endif Per MSDN, _WIN32 is "defined for applications for Win32 and Win64. Always defined." A compiler or standard library for an operating system other than Windows is, of course, free to define _WIN32, but that would be... most unusual.
1,647,895
1,647,921
What does static_assert do, and what would you use it for?
Could you give an example where static_assert(...) ('C++11') would solve the problem in hand elegantly? I am familiar with run-time assert(...). When should I prefer static_assert(...) over regular assert(...)? Also, in boost there is something called BOOST_STATIC_ASSERT, is it the same as static_assert(...)?
Static assert is used to make assertions at compile time. When the static assertion fails, the program simply doesn't compile. This is useful in different situations, like, for example, if you implement some functionality by code that critically depends on unsigned int object having exactly 32 bits. You can put a static assert like this static_assert(sizeof(unsigned int) * CHAR_BIT == 32); in your code. On another platform, with differently sized unsigned int type the compilation will fail, thus drawing attention of the developer to the problematic portion of the code and advising them to re-implement or re-inspect it. For another example, you might want to pass some integral value as a void * pointer to a function (a hack, but useful at times) and you want to make sure that the integral value will fit into the pointer int i; static_assert(sizeof(void *) >= sizeof i); foo((void *) i); You might want to asset that char type is signed static_assert(CHAR_MIN < 0); or that integral division with negative values rounds towards zero static_assert(-5 / 2 == -2); And so on. Run-time assertions in many cases can be used instead of static assertions, but run-time assertions only work at run-time and only when control passes over the assertion. For this reason a failing run-time assertion may lay dormant, undetected for extended periods of time. Of course, the expression in static assertion has to be a compile-time constant. It can't be a run-time value. For run-time values you have no other choice but use the ordinary assert.
1,648,127
1,648,169
C++ boost::thread and automatically locking containers
Is there a way to automatically lock an STL container on access, without having to lock and release around it?
The currrent C++ standard does not say anything about thread safety for STL containers. Officially it is possible for an STL implementation to be thread safe, but it's very unusual. If your STL implementation is not thread safe, then you will need to "lock and release around it" or find some other way to coordinate access. You may be interested in Intel's Threading Building Blocks which includes some thread safe containers similar to STL containers.
1,648,229
1,648,318
QTimer vs individual threads
My program's really consuming CPU time far more than I'd like (2 displays shoots it up to 80-90%). I'm using Qtimers, and some of them are as short as 2ms. At any given time, I can have 12+ timers going per display -- 2ms, 2ms, 2ms, 250ms, the rest ranging between 200ms and 500ms. Would it be better if I used threads for some or all of these (especially the short ones)? Would it make much of a difference?
The main time issue is going to come in on the high priority timers. First off make sure you really need these every 2ms, secondly to overcome some of the overhead in the QTimer class you could group your 3 2ms timeouts into one, and everytime it goes off just execute the 3 sections of code sequentially. I don't think threading will solve the issue though.
1,648,618
1,648,632
Techniques for obscuring sensitive strings in C++
I need to store sensitive information (a symmetric encryption key that I want to keep private) in my C++ application. The simple approach is to do this: std::string myKey = "mysupersupersecretpasswordthatyouwillneverguess"; However, running the application through the strings process (or any other that extracts strings from a binary app) will reveal the above string. What techniques should be used to obscure such sensitive data? Edit: OK, so pretty much all of you have said "your executable can be reverse engineered" - of course! This is a pet peeve of mine, so I'm going to rant a bit here: Why is it that 99% (OK, so perhaps I exaggerate a little) of all security-related questions on this site are answered with a torrent of "there is no possible way to create a perfectly secure program" - that is not a helpful answer! Security is a sliding scale between perfect usability and no security at one end, and perfect security but no usability at the other. The point is that you pick your position on that sliding scale depending on what you're trying to do and the environment in which your software will run. I'm not writing an app for a military installation, I'm writing an app for a home PC. I need to encrypt data across an untrusted network with a pre-known encryption key. In these cases, "security through obscurity" is probably good enough! Sure, someone with enough time, energy and skill could reverse-engineer the binary and find the password, but guess what? I don't care: The time it takes me to implement a top-notch secure system is more expensive than the loss of sales due to the cracked versions (not that I'm actually selling this, but you get my point). This blue-sky "lets do it the absolute best way possible" trend in programming amongst new programmers is foolish to say the least. Thank you for taking the time to answer this question - they were most helpful. Unfortunately I can only accept one answer, but I've up-voted all the useful answers.
Basically, anyone with access to your program and a debugger can and will find the key in the application if they want to. But, if you just want to make sure the key doesn't show up when running strings on your binary, you could for instance make sure that the key is not within the printable range. Obscuring key with XOR For instance, you could use XOR to split the key into two byte arrays: key = key1 XOR key2 If you create key1 with the same byte-length as key you can use (completely) random byte values and then compute key2: key1[n] = crypto_grade_random_number(0..255) key2[n] = key[n] XOR key1[n] You can do this in your build environment, and then only store key1and key2 in your application. Protecting your binary Another approach is to use a tool to protect your binary. For instance, there are several security tools that can make sure your binary is obfuscated and starts a virtual machine that it runs on. This makes it hard(er) to debug, and is also the convential way many commercial grade secure applications (also, alas, malware) is protected. One of the premier tools is Themida, which does an awesome job of protecting your binaries. It is often used by well known programs, such as Spotify, to protect against reverse engineering. It has features to prevent debugging in programs such as OllyDbg and Ida Pro. There is also a larger list, maybe somewhat outdated, of tools to protect your binary. Some of them are free. Password matching Someone here discussed hashing password+salt. If you need to store the key to match it against some kind of user submitted password, you should use a one-way hashing function, preferrably by combining username, password and a salt. The problem with this, though, is that your application has to know the salt to be able to do the one-way and compare the resulting hashes. So therefore you still need to store the salt somewhere in your application. But, as @Edward points out in the comments below, this will effectively protect against a dictionary attack using, e.g, rainbow tables. Finally, you can use a combination of all the techniques above.
1,648,689
1,648,781
How to code Jon Skeet's Singleton in C++?
On Jon's site he has thisvery elegantly designed singleton in C# that looks like this: public sealed class Singleton { Singleton() { } public static Singleton Instance { get { return Nested.instance; } } class Nested { // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static Nested() { } internal static readonly Singleton instance = new Singleton(); } } I was wondering how one would code the equivalent in C++? I have this but I am not sure if it actually has the same functionality as the one from Jon. (BTW this is just a Friday exercise, not needed for anything particular). class Nested; class Singleton { public: Singleton() {;} static Singleton& Instance() { return Nested::instance(); } class Nested { public: Nested() {;} static Singleton& instance() { static Singleton inst; return inst; } }; }; ... Singleton S = Singleton::Instance();
This technique was introduced by University of Maryland Computer Science researcher Bill Pugh and has been in use in Java circles for a long time. I think what I see here is a C# variant of Bill's original Java implementation. It does not make sense in a C++ context as the current C++ standard is agnostic on parallelism. The whole idea is based on the language guarantee that the inner class will be loaded only at the instance of first use, in a thread safe manner. This does not apply to C++. (Also see this Wikipedia entry)
1,649,139
1,649,213
Searching a C++ Vector<custom_class> for the first/last occurence of a value
I'm trying to work out the best method to search a vector of type "Tracklet" (a class I have built myself) to find the first and last occurrence of a given value for one of its variables. For example, I have the following classes (simplified for this example): class Tracklet { TimePoint *start; TimePoint *end; int angle; public: Tracklet(CvPoint*, CvPoint*, int, int); } class TimePoint { int x, y, t; public: TimePoint(int, int, int); TimePoint(CvPoint*, int); // Relevant getters and setters exist here }; I have a vector "vector<Tracklet> tracklets" and I need to search for any tracklets with a given value of "t" for the end timepoint. The vector is ordered in terms of end time (i.e. tracklet.end->t). I'm happy to code up a search algorithm, but am unsure of which route to take with it. I'm not sure binary search would be suitable, as I seem to remember it won't necessarily find the first. I was thinking of a method where I use binary search to find an index of an element with the correct time, then iterate back to find the first and forward to find the last. I'm sure there's a better way than that, since it wastes binary searches O(log n) by iterating. Hopefully that makes sense: I struggled to explain it a bit! Cheers!
If the vector is sorted and contains the value, std::lower_bound will give you an iterator to the first element with a given value and std::upper_bound will give you an iterator to one element past the last one containing the value. Compare the value with the returned element to see if it existed in the vector. Both these functions use binary search, so time is O(logN). To compare on tracklet.end->t, use: bool compareTracklets(const Tracklet &tr1, const Tracklet &tr2) { return (tr1.end->t < tr2.end->t); } and pass compareTracklets as the fourth argument to lower_bound or upper_bound
1,649,344
1,649,389
Create a new EXE from within C
Am working in VC++ 2008 (express) and I would like to write something in C that creates an "empty" exe that I can later call LoadLibrary on and use BeginUpdateResource, UpdateResource, EndUpdateResource to modify the contents. Just writing a 0-byte file doesn't allow me to open it with LoadLibrary because it isn't a resource.
You can compile an empty .exe file with, for example, int main() { return 0; } and use it as a template. (Or an empty .dll, whatever)
1,649,398
1,649,423
How do I ensure buffer memory is aligned?
I am using a hardware interface to send data that requires me to set up a DMA buffer, which needs to be aligned on 64 bits boundaries. The DMA engine expects buffers to be aligned on at least 32 bits boundaries (4 bytes). For optimal performance the buffer should be aligned on 64 bits boundaries (8 bytes). The transfer size must be a multiple of 4 bytes. I create buffers using posix_memalign, as demonstrated in the snippet bellow. posix_memalign ((void**)&pPattern, 0x1000, DmaBufferSizeinInt32s * sizeof(int)) pPattern is a pointer to an int, and is the start of my buffer which is DmaBufferSizeinInt32s deep. Is my buffer aligned on 64bits?
Yes, your buffer IS aligned on 64-bits. It's ALSO aligned on a 4 KByte boundary (hence the 0x1000). If you don't want the 4 KB alignement then pass 0x8 instead of 0x1000 ... Edit: I would also note that usually when writing DMA chains you are writing them through uncached memory or through some kind of non-cache based write queue. If this is the case you want to align your DMA chains to the cache line size as well to prevent a cache write-back overwriting the start or end of your DMA chain.
1,649,529
1,649,979
Sorting by blocks of elements with std::sort()
I have an array of edges, which is defined as a C-style array of doubles, where every 4 doubles define an edge, like this: double *p = ...; printf("edge1: %lf %lf %lf %lf\n", p[0], p[1], p[2], p[3]); printf("edge2: %lf %lf %lf %lf\n", p[4], p[5], p[6], p[7]); So I want to use std::sort() to sort it by edge length. If it was a struct Edge { double x1, y1, x2, y2; }; Edge *p;, I would be good to go. But in this case, the double array has a block size that is not expressed by the pointer type. qsort() allows you to explicitly specify the block size, but std::sort() infers the block-size by the pointer type. For performance reasons (both memory-usage and CPU), let's say that it's undesirable to create new arrays, or transform the array somehow. For performance reasons again, let's say that we do want to use std::sort() instead of qsort(). Is it possible to call std::sort() without wasting a single CPU cycle on transforming the data? Possible approach: An obvious approach is to try to force-cast the pointer: double *p = ...; struct Edge { double arr[4]; }; Edge *p2 = reinterpret_cast<Edge*>(p); std::sort(...); But how do I make sure the data is aligned properly? Also, how do I make sure it will always be aligned properly on all platforms and architectures? Or can I use a typedef double[4] Edge;?
How about having a reordering vector? You initialize vector with 1..N/L, pass std::sort a comparator that compares elements i1*L..i1*L+L to i2*L..i2*L+L, and when your vector is properly sorted, reorder the C array according to new order. In response to comment: yes things get complicated, but it may just be good complication! Take a look here.
1,649,859
2,565,615
In native C++, how does one use a SqlCe .sdf database?
Is there a simple way, without .NET? I've found some libraries but none for SqlCe 3.5. There is http://sqlcehelper.codeplex.com/ but it's far from done, since a major feature like using a password is not yet implemented. I've looked at the source and it uses OLEdb to handle the database. The official Microsoft Northwind example (that is shipped with SQL Compact 3.1, but not with 3.5) also doesn't work, I've tried setting it up with no success. Actually I don't have a sample working code. Was anyone able to set it up paired with a passworded .sdf? What are the alternatives? Thanks.
Several months ago, I compared certain database implementations for our desktop application. Using SqlCE with native C++ code is awful. If I remember right, some of native examples contains "goto" type jumps, hard to bind data and so on. If you have a choice then use SQLite.
1,650,035
1,650,074
how to convert CString to Bytes
i am actually tryin to convert a csharp code to c... below is the C# code.. CString data = "world is beautiful"; Byte[] quote = ASCIIEncoding.UTF8.GetBytes(data); in the above code... it converts the string into bytes..similarily is ther a way that i can convert it using C.. Can any body tell what wud be the quivalent code in C? Please help me guys
Well CString is a C++ class so doing it in C is a little unlikely. But if you wish to get it as a standard multi-byte encoded string then you can do the following CString data = "world is beautiful"; CStringA mbStr = data; char* bytes = mbStr.GetString();
1,650,094
1,650,371
How to keep only the last duplicate when iterating through rows
Following code iterates through many data-rows, calcs some score per row and then sorts the rows according to that score: unsigned count = 0; score_pair* scores = new score_pair[num_rows]; while ((row = data.next_row())) { float score = calc_score(data.next_feature()) scores[count].score = score; scores[count].doc_id = row->docid; count++; } assert(count <= num_rows); qsort(scores, count, sizeof(score_pair), score_cmp); Unfortunately, there are many duplicate rows with the same docid but different score. Now i like to keep the last score for any docid only. The docids are unsigned int, but usually big (=> no lookup-array) - using a HashMap to lookup the last count for a docid would probably be too slow (many millions of rows, should only take seconds not minutes...). Ok, i modified my code to use a std:map: map<int, int> docid_lookup; unsigned count = 0; score_pair* scores = new score_pair[num_rows]; while ((row = data.next_row())) { float score = calc_score(data.next_feature()) map<int, int>::iterator iter; iter = docid_lookup.find(row->docid); if (iter != docid_lookup.end()) { scores[iter->second].score = score; scores[iter->second].doc_id = row->docid; } else { scores[count].score = score; scores[count].doc_id = row->docid; docid_lookup[row->docid] = count; count++; } } It works and the performance hit is not as bad as i expected - now it runs a minute instead of 16 seconds, so it's about a factor of 3. Memory usage has also gone up from about 1Gb to 4Gb.
The first thing I'd try would be a map or unordered_map: I'd be surprised if performance is a factor of 60 slower than what you did without any unique-ification. If the performance there isn't acceptable, another option is something like this: // get the computed data into a vector std::vector<score_pair>::size_type count = 0; std::vector<score_pair> scores; scores.reserve(num_rows); while ((row = data.next_row())) { float score = calc_score(data.next_feature()) scores.push_back(score_pair(score, row->docid)); } assert(scores.size() <= num_rows); // remove duplicate doc_ids std::reverse(scores.begin(), scores.end()); std::stable_sort(scores.begin(), scores.end(), docid_cmp); scores.erase( std::unique(scores.begin(), scores.end(), docid_eq), scores.end() ); // order by score std::sort(scores.begin(), scores.end(), score_cmp); Note that the use of reverse and stable_sort is because you want the last score for each doc_id, but std::unique keeps the first. If you wanted the first score you could just use stable_sort, and if you didn't care what score, you could just use sort. The best way of handling this is probably to pass reverse iterators into std::unique, rather than a separate reverse operation. But I'm not confident I can write that correctly without testing, and errors might be really confusing, so you get the unoptimised code... Edit: just for comparison with your code, here's how I'd use the map: std::map<int, float> scoremap; while ((row = data.next_row())) { scoremap[row->docid] = calc_score(data.next_feature()); } std::vector<score_pair> scores(scoremap.begin(), scoremap.end()); std::sort(scores.begin(), scores.end(), score_cmp); Note that score_pair would need a constructor taking a std::pair<int,float>, which makes it non-POD. If that's not acceptable, use std::transform, with a function to do the conversion. Finally, if there is much duplication (say, on average 2 or more entries per doc_id), and if calc_score is non-trivial, then I would be looking to see whether it's possible to iterate the rows of data in reverse order. If it is, then it will speed up the map/unordered_map approach, because when you get a hit for the doc_id you don't need to calculate the score for that row, just drop it and move on.
1,650,637
1,651,980
Why do I get wrong text size for the toolbar?
In a Win32 GUI application I need to determine the width of area occupied by a string on a toolbar button so that I adjust the button width accordingly. The toolbar is plain old ToolbarWindow32 windows class. I use the following code: HDC dc = GetDC( toolbarWindowHandle ); SIZE size; GetTextExtentPoint32( dc, stringToMeasure, tcslen(stringToMeasure), &size ); For some fixed string (say "Hello") size.cx is filled with say 72 but when I make a screenshot of the toolbar with the very same string displayed on a button I see that the string occupies say 56 pixels. The difference clearly depends on system fonts settings. I use "large fonts" and the value obtained by code is bigger than what is occupied on screen. On machines with "small fonts" the value obtained is smaller. I thought if I use GetTextExtentPoint32() on a window device context it will return exactly the right size. What am I doing wrong?
The font used by the toolbar won't be selected into the DC so you'll need to work out what font it is using, create a copy, select it into the DC, get the size and then select the font out (else you could end up with a resource leak). You will currently be getting the size of the system font I expect, or whatever the default DC font is. You could try finding the font handle used by sending a WM_GETFONT message to the toolbar window but this isn't guaranteed to return the actual font used when the text is displayed. It all depends on how the toolbar works internally. However I'm pretty sure that the Win32 toolbar uses the menu font for rendering button text, which can be discovered using a combination of SystemParametersInfo and the NONCLIENTMETRICS structure. If I was at work I'd post some code. Don't you just love Win32? BTW, I use the toolbar button text feature and have never had to size the button by hand in this way. http://msdn.microsoft.com/en-us/library/ms724947(VS.85).aspx http://msdn.microsoft.com/en-us/library/ms724506(VS.85).asp
1,650,763
1,657,267
Call unmanaged Code from C# - returning a struct with arrays
[EDIT] I changed the source as suggested by Stephen Martin (highlighted in bold). And added the C++ source code as well. I'd like to call an unmanaged function in a self-written C++ dll. This library reads the machine's shared memory for status information of a third party software. Since there are a couple of values, I'd like to return the values in a struct. However, within the struct there are char [] (Arrays of char with a fixed size). I now try to receive that struct from the dll call like this: [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_OUTPUT { UInt16 ReadyForConnect; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] String VersionStr; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)] String NameOfFile; // actually more of those } public partial class Form1 : Form { public SYSTEM_OUTPUT output; [DllImport("testeshm.dll", EntryPoint="getStatus")] public extern static int getStatus(out SYSTEM_OUTPUT output); public Form1() { InitializeComponent(); } private void ReadSharedMem_Click(object sender, EventArgs e) { try { label1.Text = getStatus(out output).ToString(); } catch (AccessViolationException ave) { label1.Text = ave.Message; } } } I will post code from the c++ dll as well, I'm sure there's more to hunt down. The original struct STATUS_DATA has an array of four instances of the struct SYSTEM_CHARACTERISTICS and within that struct there are char[]s, that are not being filled (yet), resulting in a bad pointer. That's why I'm trying to extract a subset of the first SYSTEM_CHARACTERISTICS item in STATUS_DATA. #include <windows.h> #include <stdio.h> #include <conio.h> #include <tchar.h> #include <iostream> #if defined(_MSC_VER) #include <windows.h> #define DLL extern "C" __declspec(dllexport) #else #define DLL #endif using namespace std; enum { SYSID_LEN = 1024, VERS_LEN = 128, SCENE_LEN = 1024 }; enum { MAX_ENGINES = 4 }; struct SYSTEM_CHARACTERISTICS { unsigned short ReadyForConnect; char VizVersionStr[VERS_LEN]; char NameOfFile[SCENE_LEN]; char Unimplemented[SCENE_LEN]; // not implemented yet, resulting to bad pointer, which I want to exclude (reason to have SYSTEM_OUTPUT) }; struct SYSTEM_OUTPUT { unsigned short ReadyForConnect; char VizVersionStr[VERS_LEN]; char NameOfFile[SCENE_LEN]; }; struct STATUS_DATA { SYSTEM_CHARACTERISTICS engine[MAX_ENGINES]; }; TCHAR szName[]=TEXT("E_STATUS"); DLL int getStatus(SYSTEM_OUTPUT* output) { HANDLE hMapFile; STATUS_DATA* pBuf; hMapFile = OpenFileMapping( FILE_MAP_READ, // read access FALSE, // do not inherit the name szName); // name of mapping object if (hMapFile == NULL) { _tprintf(TEXT("Could not open file mapping object (%d).\n"), GetLastError()); return -2; } pBuf = (STATUS_DATA*) MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0); if (pBuf == NULL) { _tprintf(TEXT("Could not map view of file (%d).\n"), GetLastError()); CloseHandle(hMapFile); return -1; } output->ReadyForConnect = pBuf->engine[0].ReadyForConnect; memcpy(output->VizVersionStr, pBuf->engine[0].VizVersionStr, sizeof(pBuf->engine[0].VizVersionStr)); memcpy(output->NameOfFile, pBuf->engine[0].NameOfFile, sizeof(pBuf->engine[0].NameOfFile)); CloseHandle(hMapFile); UnmapViewOfFile(pBuf); return 0; } Now I'm getting an empty output struct and the return value ist not 0 as intended. It is rather a changing number with seven digits, which leaves me puzzled... Have I messed up in the dll? If I make the unmanaged code executable and debug it, I can see, that output is being filled with the appropriate values.
When returning information in a struct the standard method is to pass a pointer to a struct as a parameter of the method. The method fills in the struct members and then returns a status code (or boolean) of some kind. So you probably want to change your C++ method to take a SYSTEM_OUTPUT* and return 0 for success or some error code: public partial class Form1 : Form { public SYSTEM_OUTPUT output; [DllImport("testeshm.dll", EntryPoint="getStatus")] public extern static int getStatus(out SYSTEM_OUTPUT output); public Form1() { InitializeComponent(); } private void ReadSharedMem_Click(object sender, EventArgs e) { try { if(getStatus(out output) != 0) { //Do something about error. } } catch (AccessViolationException ave) { label1.Text = ave.Message; } } }
1,650,904
1,650,929
OpenCV K-Means (kmeans2)
I'm using Opencv's K-means implementation to cluster a large set of 8-dimensional vectors. They cluster fine, but I can't find any way to see the prototypes created by the clustering process. Is this even possible? OpenCV only seems to give access to the cluster indexes (or labels). If not I guess it'll be time to make my own implementation!
I can't say I used OpenCV's implementation of Kmeans, but if you have access to the labels given to each instance, you can simply get the centroids by calculating the average vector of instances belong to each of the clusters.
1,650,942
1,650,959
Large dynamic array in c++
Short problem: #include <iostream> using namespace std; int main() { double **T; long int L_size; long int R_size = 100000; long int i,j; cout << "enter L_size:"; cin >> L_size; cin.clear(); cin.ignore(100,'\n'); cout << L_size*R_size << endl; cout << sizeof(double)*L_size*R_size << endl; T = new double *[L_size]; for (i=0;i<L_size;i++) { T[i] = new double[R_size]; } cout << "press enter to fill array" << endl; getchar(); for (i=0;i<L_size;i++) { for (j=0;j<R_size;j++) { T[i][j] = 10.0; } } cout << "allocated" << endl; for (i=0;i<L_size;i++) { delete[] T[i]; } delete [] T; cout << "press enter to close" << endl; getchar(); return 0; } with 2GB of RAM (on 32bit OS) I can't make it work with L_size = 3000 which is pretty obvious since it would need approx. 2.4GB. But when I start 2 copies of above program each with L_size = 1500 it works - really slow but finally both returns allocated in console. So the question is - how is that possible? Is it related to virtual memory? It is possible to have one big array stored in virtual memory while operating on another - within one program? Thx.
Yes. The operating system will allow you to allocate up to 2GB of RAM per process. When you start two copies, it will let this grow using virtual memory, which will be very, very slow (since it's using the hard drive), but still function.
1,650,963
4,429,618
uSTL or STLPort for Android?
I'm working with the Android NDK, and since it does not currently support the STL, I was wondering if there are any brilliant people out there who have had success with this, or know which is better suited for the Android platform: uSTL or STLPort. EDIT: Looks like another option may be CrystaX .NET. From their website: ...customized distribution of Android NDK r3 which I have rebuilt from official sources. Support of C++ exceptions, RTTI and Standard C++ Library added.
STLport supported since Android2.3 now!!!
1,650,964
1,650,998
compile errors w/wininet & winhttp in MFC application
Strangely I had this working before but I reinstalled my system, upgraded to w7 and now I can't seem to get this code to compile. The problem is that I'm using winhttp.h in most of my application, but I have a simple FTP client object that I wrote using wininet.h functionality. I can't seem to get the application to compile now, no matter how/where I include which headers. Currently I have in my stdafx.h: #include <winhttp.h> And in my ftp client .c #include <wininet.h> This compiles all objects successfully except for the FTP client object which fails with: c:\Program Files\Microsoft Platform SDK\Include\WinInet.h(52) : warning C4005: 'BOOLAPI' : macro redefinition c:\Program Files\Microsoft Platform SDK\Include\winhttp.h(45) : see previous definition of 'BOOLAPI' c:\Program Files\Microsoft Platform SDK\Include\WinInet.h(270) : error C2143: syntax error : missing '}' before '(' c:\Program Files\Microsoft Platform SDK\Include\WinInet.h(270) : fatal error C1903: unable to recover from previous error(s); stopping compilation Any advice?
Ah got it, finally by moving the winhttp include into the cpp files and putting wininet into the ftp client header.
1,650,981
1,650,988
How do you output the \ symbol using cout?
How do you output \ symbol using cout?
Use two backslashes \\
1,650,987
1,651,846
What's the best way to optimise the build of a project which uses Boost?
I was a bit staggered today by the sheer number of auto generated includes that Boost produces when doing a compile if we turn on verbose includes. We're averaging 3000 header files included per compilation unit and sometimes getting up to 5000. Virtually all of it is caused by Boost's preprocessor-meta programming funk with large numbers of the same header file getting included again and again in a massive preprocessor recursion. Do you think 3000 per compilation is normal for a Boost project? What can I do to optimise Boost builds other than buying an array of SSDs?
One thing that can really help is the use of precompiled headers, so that many or most of the Boost headers get compiled once for the whole build, not once for every translation unit. Both Microsoft Visual C++ and GCC support precompiled headers (as do other compilers).
1,651,244
1,651,285
Do I really need Visual Studio
Do I really need Visual studio to build c/C++ application on Windows. Is there any way to have makefiles and get the application built.
If you want to stick to the Microsoft toolchain but don't want the IDE, you can use cl and link to build from the command line in conjuction with either the MSBUILD system or NMAKE. If you don't have the compiler it is available free with VC++ Express.
1,651,531
1,652,425
Loading an image from memory, GDI+
Here's a quick and easy question: using GDI+ from C++, how would I load an image from pixel data in memory?
Probably not as easy as you were hoping, but you can make a BMP file in-memory with your pixel data: If necessary, translate your pixel data into BITMAP-friendly format. If you already have, say, 24-bit RGB pixel data, it is likely that no translation is needed. Create (in memory) a BITMAPFILEHEADER structure, followed by a BITMAPINFO structure. Now you've got the stuff you need, you need to put it into an IStream so GDI+ can understand it. Probably the easiest (though not most performant) way to do this is to: Call GlobalAlloc() with the size of the BITMAPFILEHEADER, the BITMAPINFO, and your pixel data. In order, copy the BITMAPFILEHEADER, BITMAPINFO, and pixel data into the new memory (call GlobalLock to get the new memory pointer). Call CreateStreamOnHGlobal() to get an IStream for your in-memory BMP. Now, call the GDI+ Image::FromStream() method to load your image into GDI+. Good luck!
1,651,563
1,652,444
Inserting (string, object * ) into hash table (C++)
This question is an offgrowth of my previous question on creating a hash table to store string keys and pointers as data. I'm getting a seg fault post-construction when I try to add entries to my hash table. I'm still very confused about what syntax is appropriate. I currently have (thanks to previous posters): // Simulation.h #include <ext/hash_map> using namespace __gnu_cxx; ... typedef struct { size_t operator()( const string& str ) const { return __gnu_cxx::__stl_hash_string( str.c_str() ); } } strhash; struct eqstr { bool operator()(string s1, string s2) const { return ( s1.compare(s2) == 0 ); } }; .... hash_map< string, Strain *, strhash, eqstr > strainTable; In my Simulation constructor, I have: // Simulation.cpp Simulation::Simulation() : ... { string MRCA; for ( int b = 0; b < SEQ_LENGTH; b++ ) { int randBase = rgen.uniform(0,NUM_BASES); MRCA.push_back( BASES[ randBase ] ); } Strain * firstStrainPtr; firstStrainPtr = new Strain( idCtr, MRCA, NUM_STEPS ); strainTable[ MRCA ]= firstStrainPtr; // <-- Hash table initialization .... } This seems to work fine. I get a seg fault when the following insertion is attempted: void Simulation::updateSimulation( double t ) { .... // Add mutants to liveStrains() and strainTable vector< Strain * >::const_iterator mItr = newMutants.begin(); for ( mItr = newMutants.begin(); mItr != newMutants.end(); ++mItr ) // for each mutant in deme { string mutantSeq = ( *mItr )->getSequence(); cout << "mutantSeq is " << mutantSeq << endl; // <-- This is fine liveStrains.push_back( *mItr ); strainTable[ mutantSeq ] = *mItr; // <-- Seg fault happens here } newMutants.clear(); .... } Reading the third note on the operator[] in the SGI documentation, this seems like it should be fine. What's wrong? I'm thinking of switching to a map container just to save debugging time... Update Something about the initialization seems wrong. When I get to strainTable[ mutantSeq ] = *mItr; the debugger reports "EXC_BAD_ACCESS" and jumps to _Node* __first = _M_buckets[__n]; of hashtable.h.
As a diagnosis approach, you actually have 2 instructions executed on the line: Lookup in strainTable, which returns a reference Dereferencing the iterator Assignation of a value to the reference Here you might want to take a Divide and Conquer approach: strainTable[ mutantSeq ] = *mItr; // <-- Seg fault happens here Becomes Strain*& aReference = strainTable[ mutantSeq ]; Strain* const aPtr = *mItr; aReference = aPtr; (which is a general advice) On which line does the seg fault occur ? Would it be possible to have the 10 first frames of the stack ? While looking up Google, I came up this bug report, which suggests there might be issues with the hash_map... You might be better off using the unordered_map if possible, as it's clearly indicated that no time will be taken fixing the hsah_map viewed as a legacy container (and this was 2005...). Note that it should be available if you use GCC 4.x (not sure for 3.x) The main advantage is that the hash structure and comparison predicate already work for std::string so you don't even have to implement them yourself :) All you have to do, therefore, if you have this in your compiler, is to write this: #include <tr1/unordered_map> typedef std::tr1::unordered_map<std::string, Strain*> strain_hash_map;
1,651,616
61,785,481
Qt: does "new without delete" cause memory leaks with controls?
I was looking at Qt example here: and inside the constructor, they have: Window::Window() { editor = new QTextEdit(); // Memory leak? QPushButton *sendButton = new QPushButton(tr("&Send message")); // Memory leak? connect(sendButton, SIGNAL(clicked()), this, SLOT(sendMessage())); QHBoxLayout *buttonLayout = new QHBoxLayout(); // Memory leak? buttonLayout->addStretch(); buttonLayout->addWidget(sendButton); buttonLayout->addStretch(); QVBoxLayout *layout = new QVBoxLayout(this); // Memory leak? layout->addWidget(editor); layout->addLayout(buttonLayout); setWindowTitle(tr("Custom Type Sending")); } Those lines with comments // Memory leak? aren't those memory leaks? If so, since the Window class has no constructor, then I should make all of those variables (editor already is) Window member variables ? Or..does Qt internally "delete" those member variables when it goes out of scope?
As of C++14 you can use the std::make_unique() convenience function template for creating an std::unique_ptr<> that has exclusive ownership of the widget. Then, at the moment of passing the widget to addLayout(), you make the smart pointer give up ownership by calling release(): auto buttonLayout = std::make_unique<QHBoxLayout>(); // ... // an exception could be thrown here // ... layout->addLayout(buttonLayout.release());
1,651,682
1,651,726
How to "watch" a C++ dynamic array using gdb?
Consider the following example: int size = 10, *kk = new int[size]; for (int i = 0; i < size; i++) { kk[i] = i; } delete [] kk; How can I add a watch for the whole array? I can add a watch one by one (kk[0],kk[1]...), but since I know the array's length is there a way to do it automatically? I mean something like kk[0..size-1] or so. I'm using NetBeans IDE together with cygwin g++ and gdb.
Try display *kk@<size> From the doc for the print command: @ is a binary operator for treating consecutive data objects anywhere in memory as an array. FOO@NUM gives an array whose first element is FOO, whose second element is stored in the space following where FOO is stored, etc. FOO must be an expression whose value resides in memory.
1,651,737
1,651,771
LoadStringW - winuser.h. What does it do?
I have been unable to find any decent documentation on this function. The code base I am working with uses a function from winuser.h called LoadStringW which takes as arguments: (HINSTANCE hInstance, UINT uID, LPWSTR lpBuffer, int cchBufferMax). What is this function? What is it for? When might it return 0?
LoadStringW is the Unicode version of LoadString. The documentation states "If the function succeeds, the return value is the number of TCHARs copied into the buffer, not including the terminating NULL character, or zero if the string resource does not exist. To get extended error information, call GetLastError."
1,651,936
1,651,979
Changing std::endl to put out CR+LF instead of LF
I'm writing a program on a Linux platform that is generating text files that will be viewed on, inevitably, a Windows platform. Right now, passing std::endl into a ostream generates the CR character only for newlines. Naturally, these text files look wrong in MS Notepad. Is there a way to change std::endl such that it uses CR+LF for newline instead of LF? I know I could write my own custom manipulator, like win_endl, for generating my own newlines, but I use the std::endl symbol in a lot of places, and like many programmers, have a tendency to do the thing that requires the least work possible. Could I simply overload std::endl to produce CR+LF, or is this a dumb idea for maintainability? NB: I checked out this question, but it's asking about going the other way, and the accepted answer seems rather incomplete.
Opening a file in text mode should cause std::endl to be converted to the appropriate line ending for your platform. Your problem is that newline is appropriate for your platform, but the files you create aren't intended for your platform. I'm not sure how you plan on overloading or changing endl, and changing its behavior would certainly be surprising for any developers new to your project. I'd recommend switching to win_endl (should be a simple search-and-replace) or maybe switching from a standard ostream to a Boost.Iostreams filtering stream to do the conversion for you.
1,652,126
1,652,198
const char * as a function parameter in C++
NOTE: I know there are many questions that talked about that but I'm still a beginner and I couldn't understand the examples. I got a function prototype that goes like this: int someFunction(const char * sm); Here, as you know, const char* means that this function can accept const or non-const pointer-to-char. I tried something like that in the function body: someMemberVar = sm; someMemberVar is just a pointer-to-char. The compiler gives me an error telling me: cannot convert from const char* to char*. Here, I didn't pass a constant, so either sm or someMemberVar aren't constants. So, what constant the compiler is talking about?
I'll try to put in simpler terms what others are saying: The function someFunction takes a read-only string (for simplicity's sake, though char * could be used in umpteen other cases). Whether you pass in a readonly string to someFunction or not, the parameter is treated as read-only by the code executing in the context of this function. Within this function therefore, the compiler will try to prevent you from writing to this string as much as possible. A non-const pointer is such an attempt to disregard the read-only tag to the string and the compiler, rightly and loudly informs you of such disregard for its type system ;) What's the difference between: int someFunction(const char * sm) const{...} and this: int someFunction(const char * sm){...} The first is a function which takes a readonly parameter. The second const written after the closing parentheses is valid only for member functions. It not only takes a read-only parameter, but also gurantees to not alter the state of the object. This is typically referred to as design level const.
1,652,183
1,652,520
How should I save and load user configuration files for a game in C++?
I need a way to save and load user configurations for a game (controls, graphics, etc.) to a file. I want to do this in a cross-platform manner, and if I have to use libraries, I want them to have a simple enough syntax. How do I save and load config files, and what format should I use? XML and INI seem popular but all of the parsers I have found have confusing syntax, and I have no clue where to start to get my own parser going. By the way, the config files probably won't get too complex, so something lightweight and fast would be best. An aside - I was thinking about using scripting to define things like items, but would a markup language like xml be better or a scripting language (like angelscript, which is what I'm using) be better?
Google Protocol Buffers There is a long standing confusion I think, between serialization and messaging. Serialization Is generally short-lived and involves passing around objects. As stated in the article, COM and CORBA are well-known examples of its uses. Messaging Is about communication between different entities. The problem is that many people, when they see a messaging problem simply think: serialize and be done with it. But this is not adapted. Serialization of an object means being able to 'encode' the object, and restore it... what happens if suddenly you change your ways and what was one object is now 2, how do you deal with backward compatibility ? The problem here is that if Serialization works pretty well with stable model, any change of the model may be a pain. Messaging on the other hand decorrelates the message encoding and decoding from the current model, therefore, changes to the model just have to be treated in the encoding and decoding of the message, and the model is freed from the burden of backward compatibility. Now for a configuration file, you probably want backward compatibility. Then it is in your best interest to elect a Messaging solution. I suggest Google Protocol Buffers, because it's sound and proven. Forward and Backward compatibility is easy handled May generate either human readable or binary format A same message can be encoded / decoded in a wide variety of languages I don't have to present why 1. is important. 2. means that you can simply edit the file manually to tweak it, 3. means that you can easily code a GUI or a checking script.
1,652,255
1,652,266
accessing struct variable inside getter setter in a c++ class
Okay, I have something like this in C++: class MyClass{ private: int someVariable; int someOtherVariable; struct structName{ int someStructVariable; int someOtherStructVariable; };//end of struct public: //getters & setters for the defined variables. int getSomeStructVariable() { // this does not work I get this error: "error: expected primary-expression // before '.' token" return structName.someStructVariable; } };//end of class How should I write my getter or setter in this case?
structName is part of the type name, not the variable name. You need to give it a name, something like: struct structName { int someStructVariable; int someOtherStructVariable; } myStructure; And then in your accessor use: return myStructure.someStructVariable; That should get you the result you want. Other alternatives for the structure variable are to separate out the structure definition from the variable declaration: struct structName { int someStructVariable; int someOtherStructVariable; }; struct structName myStructure; or to add in typedef: typedef struct structName { int someStructVariable; int someOtherStructVariable; } structTypedefName; structTypedefName myStructure;
1,652,396
1,652,404
What is the difference between (type)value and type(value)?
What is the difference between (type)value and type(value) in C++?
There is no difference; per the standard (§5.2.3): A simple-type-specifier (7.1.5) followed by a parenthesized expression-list constructs a value of the specified type given the expression list. If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4). Since the question specified the difference between type(value) and (type)value, there is absolutely no difference. If and only if you're dealing with a comma-separated list of values can there be a difference. In this case: If the expression list specifies more than a single value, the type shall be a class with a suitably declared constructor (8.5, 12.1), and the expression T(x1, x2, ...) is equivalent in effect to the declaration T t(x1, x2, ...); for some invented temporary variable t, with the result being the value of t as an rvalue. As Troubadour pointed out, there are a certain names of types for which the type(value) version simply won't compile. For example: char *a = (char *)string; will compile, but: char *a = char *(string); will not. The same type with a different name (e.g., created with a typedef) can work though: typedef char *char_ptr; char *a = char_ptr(string);
1,652,901
1,653,012
Basic questions: Pointers to objects in unordered_maps (C++)
I'm new to C++ programming and would greatly appreciate replies that don't assume much prior knowledge. Thanks to suggestions here, I've created an unordered map: typedef std::tr1::unordered_map<std::string, Strain*> hmap; The data in this map are pointers to instances of class Strain. As soon as these instances are created, I create pointers to them, and I then add these pointers to my hash table (hmap strainTable) and to another vector (vector< Strain *> liveStrains), e.g., string MRCA; for ( int b = 0; b < SEQ_LENGTH; b++ ) { int randBase = rgen.uniform(0,NUM_BASES); MRCA.push_back( BASES[ randBase ] ); } Strain * firstStrainPtr; firstStrainPtr = new Strain( idCtr, MRCA, NUM_STEPS ); liveStrains.push_back( firstStrainPtr ); strainTable[ MRCA ]= firstStrainPtr; Instances of class Strain are never deleted, nor are pointers to them removed from strainTable. Pointers do occasionally move between vector< Strain * > liveStrains and vector< Strain * > deadStrains, but once on strainTable, they stay on strainTable. Is this kosher? As long as the underlying instances are never destroyed, will the pointers added to them remain intact? Is it also correct that I should always be able to get member attributes from the pointers in strainTable by using, e.g., for the first entry, hmap::const_iterator itr1 = strainTable.begin(); int id = (itr1->second)->getStrainID(); I'm finding that after a while, pointers in my strainTable point to garbage.
A pointer to any object allocated with new will remain valid until you call delete on the object. You can copy the pointer as much as you like, and it will be valid as long as the underlying object has not been deleted. Secondly, yes, you are correct that you can access object attributes from the stored pointers via container iterators. But always check to make sure that the return value of hmap::find() is not equal to hmap::end(). So what you describe is fine. Now, as to why the pointers in your strainTable are ending up pointing to garbage, I couldn't say without more details. Are you sure you're not deleting any objects anywhere? Are you sure that when you copy pointers from one vector to the other, you are doing it correctly?
1,653,047
1,653,057
Avoid linking to libstdc++
I'm working on an embedded project that currently uses C in Linux and uClibc. We're interested in moving it to C++, but I don't want the overhead associated with linking in libstdc++. My impression is that this is possible provided we don't use anything from STL, such as iostream or vector. How does one direct g++ to compile without linking to libstdc++?
When you compile, use g++ -c to compile only. Then for linking, use ld instead of g++. This invokes the linker directly, which requires you to name all your libraries on the command line (including libc and libcrt), however. Alternatively, if you're using g++ as a "better c", you may be able to use gcc for your final link step (which will include libc automatically)
1,653,203
1,653,225
Where to put containers of user defined types?
Consider one has some user defined types, and containers of those types that are often manipulated because there are often multiple instances of those types on screen at a time. Currently I have a header with an associated source file and a namespace to hold these containers, but should I create a separate class to hold them? Should I put the containers in the same header file as the class that they contain (but obviously outside the class)? What is the standard practice for situations like this?
I once typedef'd them whenever a specific class has the container as part of that class's interface. Then anyone who needed to use that class easily figured out that a "FooVec" is a std::vector of Foo without a lot of fus. However, this is an imperfect solution, consider the following code: namespace bar { typedef std::vector<Foo> FooVec; class CClass { CClass(FooVec&) { ... } }; } Naturally the problem comes in when your colleague redefines FooVec for their class: namespace bar { typedef std::vector<const Foo> FooVec; class CAnotherClass { CAnotherClass(FooVec&) { ... } } }; The simplest thing I've found to solve this is to have them in roughly one common include per namespace/library/group of associated classes. So when someone else adds a typedef to something in the bar namespace, you can have them all in one place. IE: barTypes.h namespace bar { typedef std::vector<Foo> FooVec; typedef std::vector<const Foo> FooConstVec; } By keeping it to one header per small set of classes (ie per namespace) you don't get a gigantic file full of typedefs. It still gives your users good visibility into the types that are a part of your class's interface. Once this header is established, its just a matter of maintaining discipline on your team to use it instead of establishing additional typedefs. May also wish to have this header as part of a precompiled header if you're anal about build performance.
1,653,465
1,653,485
Unable to open fstream when specifying an absolute path
I know this is rather laughable, but I can't seem to get simple C++ ofstream code to work. Can you please tell me what could possibly be wrong with the following code: #include <fstream> ... ofstream File("C:\temp.txt"); if(File) File << "lolwtf"; Opening the ofstream fails whenever I specify an absolute path. Relative paths seems to work with no issues. I'm really uncertain as to what the issue is here.
Your path is invalid: "C:\temp.txt" The \ is escaping the "t" as a horizontal tab character, so the path value ends up as: "C: emp.txt" What you want is: "C:\\temp.txt" or "C:/temp.txt"
1,653,517
1,653,531
Why is C and C++ IDE tool support behind what's available for managed platforms?
If you have used any decent java or .net IDE you can see the abundance of features that they provide that either do not exist in c/c++ IDEs or exist in a much more limited form. I am thinking about features like: Code Completion Syntax Errors (and compilation errors with no need to compile) Refactoring Debugging (the amount of information that the debugger can show you about objects) Code exploration and analysis (viewing type hierarchies, who calls this function etc...) What is the main feature of managed languages that enables them to provide this (most would say) superior support in tooling?
C++ is an extremely difficult language to parse. For the parsers that do successfully process it (compilers), they are way too slow and not flexible enough to support IDE-style code support. Unlike in a compiler, in an IDE, the parser has to be very fast and be able to process syntactically incorrect code. Until now, no one's taken the time to do it because the people with skills required to do so are focused purely on actual compilers. Visual Studio 2010 has a revamped C++ IntelliSense engine. It took them many, many years to get it done but its massively improved.
1,653,585
1,653,646
What's a decent events library for non-GUI applications under *nix? (C++)
First, I'm using Qt at the moment. However, I want the program eventually able to run without a GUI environment, leaving the graphical aspects for configuration mainly. The program makes hefty use of Qt timers and signals/slots, partially for QtScript. So if I want to make it non-GUI operable, hopefully parts of Qt can run without a GUI environment. If not, maybe I'll look into a different Javascript implementation, although QtScript is very convenient how it integrates into Qt's and C++'s OO structure. First, can parts of Qt be used in a non-GUI environment, and if not what other choices are there as far as an events and scheduling library? Preferably OO design.
Have you looked at the Boost.Signals library? (I haven't used it myself.)
1,653,605
1,653,611
Is including C++ source files an approved method?
I have a large C++ file (SS.cpp) which I decided to split in smaller files so that I can navigate it without the need of aspirins. So I created SS_main.cpp SS_screen.cpp SS_disk.cpp SS_web.cpp SS_functions.cpp and cut-pasted all the functions from the initial SS.cpp file to them. And finally I included them in the original file : #include "SS_main.cpp" #include "SS_screen.cpp" #include "SS_disk.cpp" #include "SS_web.cpp" #include "SS_functions.cpp" This situation remains for some months now , and these are the problems I've had : The Entire Solution search (Shift-Ctrl-F in VS) does not search in the included files, because they are not listed as source files. I had to manually indicate them for Subversion inclusion. Do you believe that including source files in other sources is an accepted workaround when files go really big ? I should say that splitting the implemented class in smaller classes is not an option here.
Don't include cpp files in other files. You don't have to define every class function in one file, you can spread them across multiple files. Just add them individually to the project and have it compile all of them separately.
1,653,681
1,653,737
Serialization/Deserialization of a struct to a char* in C
I have a struct struct Packet { int senderId; int sequenceNumber; char data[MaxDataSize]; char* Serialize() { char *message = new char[MaxMailSize]; message[0] = senderId; message[1] = sequenceNumber; for (unsigned i=0;i<MaxDataSize;i++) message[i+2] = data[i]; return message; } void Deserialize(char *message) { senderId = message[0]; sequenceNumber = message[1]; for (unsigned i=0;i<MaxDataSize;i++) data[i] = message[i+2]; } }; I need to convert this to a char* , maximum length MaxMailSize > MaxDataSize for sending over network and then deserialize it at the other end I can't use tpl or any other library. Is there any way to make this better I am not that comfortable with this, or is this the best we can do.
since this is to be sent over a network, i strongly advise you to convert those data into network byte order before transmitting, and back into host byte order when receiving. this is because the byte ordering is not the same everywhere, and once your bytes are not in the right order, it may become very difficult to reverse them (depending on the programming language used on the receiving side). byte ordering functions are defined along with sockets, and are named htons(), htonl(), ntohs() and ntohl(). (in those name: h means 'host' or your computer, n means 'network', s means 'short' or 16bit value, l means 'long' or 32 bit value). then you are on your own with serialization, C and C++ have no automatic way to perform it. some softwares can generate code to do it for you, like the ASN.1 implementation asn1c, but they are difficult to use because they involve much more than just copying data over the network.
1,653,874
1,654,791
Implementing Globalization / Multilingual feature in win32 API application
I have developend a window application(Win32 API) in visual C++. I have to add multilingual feature in this application. Can any one Pls guide me how to get forward with this task.
the basics for a multilingual application on Windows is the use of "resources". a resource is a chunk appended at the end of your executable, which only contains data, and is formatted in a very specific way in order for Windows to be able to interpret those data. in your resources, you can find dialog boxes, string tables, but also version informations (those which are displayed in the properties dialog box of a file in the explorer). you can watch the resources of any dll or exe by opening the exe or dll in Visual C++. when developing an application, you can create a resource (File/New), add it to your project (the same as you when you add a file) and edit the resources (using the resource editor, generally a tab next to the File View in project explorer). each resource (dialog, dialog, template, version info, string table, ...) contains a language identifier which you can change. you can create the same resource multiple times using different language identifier. once compiled, when the application is loaded by Windows, it will try to open resources which language are the closer to the Windows UI language. a set of functions is defined in the Windows SDK to make good use of those resources: LoadString, LoadCursor, LoadBitmap, and everything in the resources chapter. Now every time you use a string in your code, put it in a String Table resource and use the LoadString function to retrieve it. windows and dialog boxes are generally loaded in the correct language without needing any specific function call, as long as you have set the correct language identifier in the resources. voila, that's the shortest introduction to multilingual development under Windows that i could do. i am sure that you can find a lot of well-written articles about resources or multilingual development under Windows on the net.