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
2,232,012
2,232,035
C++, Seg Faults, and Memory Management
I'm moving from Java to C++ and have really enjoyed it. One thing I don't enjoy is not understanding memory at all because Java used to do that for me. I've purchased a book : Memory as a Programming Concept in C and C++ - Frantisek Franek Are there some good sites for me to go and learn interactively about C/C++ and memory use (tutorials, forums, user groups)?
Try these: http://www.mycplus.com/tutorials/cplusplus-programming-tutorials/memory-management/ http://www.cantrip.org/wave12.html http://linuxdevcenter.com/pub/a/linux/2003/05/08/cpp_mm-1.html And in wikibook: http://en.wikibooks.org/wiki/C++_Programming/Memory_Management This article will compare the Java memory management operators with the C++ equivalents: http://www.javamex.com/java_equivalents/memory_management.shtml http://www.infosys.tuwien.ac.at/Staff/tom/Teaching/UniZH/CPP/slides/cpp_07.pdf Hope these will help you!
2,232,056
2,232,343
Input asked for better programming practices
As I'm learning C++ I started implementing some common datastructures as a form of practice. The first one being a Stack (this was the first to spring in mind). I've done some programming and it's working, but now I need some input as to what I should do otherwise. Like deleting certain stuff or other pro tips. What should I do different and why? template <class T> class Stack { private: int* values; int capacity; int itemsOnStack; public: /////////////////// Stack() { Stack(32); } /////////////////// Stack(const int sz) { values = new T[sz]; capacity = sz; itemsOnStack = 0; } ~Stack() { values = 0; // delete? } //////////////////// void Push(const T& item) { *(values + itemsOnStack) = item; itemsOnStack++; if(itemsOnStack > capacity) { capacity *= 2; T* temp = new T[capacity]; temp = values; values = new T[capacity]; values = temp; } } /////////////////// T Pop() { if(itemsOnStack > 0) { int current = --itemsOnStack; return *(values + current); } return NULL; // ? good? } /////////////////// T Peek() { if(itemsOnStack > 0) { int current = itemsOnStack - 1; return *(values + current); } return NULL; // find something better here or shouldnt? } /////////////////// int Count() { return itemsOnStack; } /////////////////// int Capacity() { return capacity; } /////////////////// bool IsEmpty() { return itemsOnStack == 0; } };
Did a first pass of fixes on your code: template <class T> class Stack { private: int* values; int capacity; int itemsOnStack; public: //Stack() : //{ // Stack(32); // doesn't do what you expect. This would create an unnamed temporary stack object //} Stack(const int sz = 32) // C++ doesn't yet have delegating constructors. You can't call one ctor from another. But in this case, a simple default parameter can be used instead : values(new T[sz]), capacity(sz), itemsOnStack() {} // use the initializer list for initializing members ~Stack() { delete[] values; // you allocated it, so you delete it as well } //////////////////// void Push(const T& item) { values[itemsOnStack] = item; // cleaner syntactically than your version // *(values + itemsOnStack) = item; ++itemsOnStack; // prefer pre-increment by default. if(itemsOnStack > capacity) // you need to check this before writing the element. Move this to the top of the function { int newCapacity = capacity * 2; // what's this supposed to do? You're just copying pointers around, not the contents of the array T* temp = new T[newCapacity ]; std::copy(values, values+capacity, temp); // copy the contents from the old array to the new one delete[] values; // delete the old array values = temp; // store a pointer to the new array capacity = newCapacity; } } /////////////////// T Pop() { T result = Peek(); // you've already got a peek function. Why not use that? --itemsOnStack; return result; } /////////////////// T Peek() { if(itemsOnStack > 0) { int current = itemsOnStack - 1; return values[current]; // again, array syntax is clearer than pointer arithmetics in this case. } // return NULL; // Only pointers can be null. There is no universal "nil" value in C++. Throw an exception would be my suggestion throw StackEmptyException(); } /////////////////// int Count() { return itemsOnStack; } /////////////////// int Capacity() { return capacity; } /////////////////// bool IsEmpty() { return itemsOnStack == 0; } }; Things left to fix: Copy constructor and assignment operator. At the moment, if I try to do this, it'll break horribly: Stack<int> s; Stack<int> t = s; // no copy constructor defined, so it'll just copy the pointer. Then both stacks will share the same internal array, and both will try to delete it when they're destroyed. Stack<int> u; u = s; // no assignment operator, so much like above, it'll blow up Const correctness: Shouldn't I be able to call Peek() or Count() on a const Stack<T>? Object lifetime: Popping an element off the stack doesn't call the element's destructor. Pushing an element doesn't call the element's constructor. Simply expanding the array calls the default constructor immediately for all new elements. The constructor should be called when the user inserts an element and not befre, and the destructor immediately when an element is removed. And, uh, proper testing: I haven't compiled, run, tested or debugged this in any way. So I've most likely missed some bugs, and introduced a few new ones. ;)
2,232,206
2,232,388
Invalid conversion char to char* - Copying char in string array to another string array
I'm a beginner in C++ Programming language. I wanted to write a program that take the alphabets in a string array called str, and copy it in a new array called str_alpha. And the same goes to numbers, the program copies it from str array to str_digit array. There's my humble code, it might be full of errors and stuff. But this is what I could do now with my very little experience. #include <iostream> #include <cstdio> #include <cstring> #include <cctype> using namespace std; char str[100], str_alpha[100], str_digit[100]; int main() { gets(str); for (int i=0 ; str[i] ; i++) { if (isalpha(str[i])) { strcpy (str_alpha[i] , str[i]); } else if (isdigit(str[i])) { strcpy (str_digit[i] , str[i]); } } cout << "Alpha is " << str_alpha << endl ; cout << "Number is : " << str_digit << endl ; return 0; } And it gives my those errors : F:\C++Progs\string\main.cpp||In function `int main()':| F:\C++Progs\string\main.cpp|18|error: invalid conversion from `char' to `char*'| F:\C++Progs\string\main.cpp|18|error: initializing argument 1 of `char* strcpy(char*, const char*)'| F:\C++Progs\string\main.cpp|18|error: invalid conversion from `char' to `const char*'| F:\C++Progs\string\main.cpp|18|error: initializing argument 2 of `char* strcpy(char*, const char*)'| F:\C++Progs\string\main.cpp|22|error: invalid conversion from `char' to `char*'| F:\C++Progs\string\main.cpp|22|error: initializing argument 1 of `char* strcpy(char*, const char*)'| F:\C++Progs\string\main.cpp|22|error: invalid conversion from `char' to `const char*'| F:\C++Progs\string\main.cpp|22|error: initializing argument 2 of `char* strcpy(char*, const char*)'| ||=== Build finished: 8 errors, 0 warnings ===| Help me please. Thanks in advance.
First of all, strcpy copies C strings (character arrays) not chars. Additionally, the lines strcpy(str_digit[i],str[i]) and strcpy(str_alpha[i], str[i]) would still probably be wrong even if this wasn't the case. Since you haven't initialised the arrays str_digit and str_alpha, you'll get a lot of garbage values while printing them and if any of those garbage values happen to be 0x00, the cout statements will fail to print the whole string. As already mentioned, you really should be using std::string rather than char[] or char*. Having said that, here are corrected versions of your code for both char[] and std::string. Using gets is bad practice and you might consider using std::cin instead. And you might want to use an iterator rather than a simple for loop. //using char[] #include <iostream> using namespace std; int main() { char str[100] , str_alpha[100] , str_digit[100] ; int alpha_counter=0, digit_counter=0; cin.get(str, 99); for (int i=0 ; str[i] ; i++) { if(isalpha(str[i])) { str_alpha[alpha_counter] = str[i]; alpha_counter++; } else if (isdigit(str[i])) { str_digit[digit_counter] = str[i]; digit_counter++; } } str_alpha[alpha_counter] = 0; str_digit[digit_counter] = 0; cout << "Alpha is " << str_alpha << endl ; cout << "Number is : " << str_digit << endl ; return 0; } And the version using std::string: //using std::string #include <iostream> using namespace std; int main() { string str, str_alpha , str_digit; cin >> str ; for (string::iterator it = str.begin();it<str.end();it++) { if(isalpha(*it)) { str_alpha += *it; } else if (isdigit(*it)) { str_digit += *it; } } cout << "Alpha is " << str_alpha << endl ; cout << "Number is : " << str_digit << endl ; return 0; } Both versions compile without warnings on g++ 4.2.1 with -Wall and -pedantic.
2,232,226
2,232,234
initialize reference in initialization list
I was told the reference variable must be initialized in the initialization list, but why this is wrong? class Foo { public: Foo():x(0) { y = 1; } private: int& x; int y; }; Because 0 is a temporary object? If so, what kind of object can reference be bound? The object which can take an address? Thanks!
0 is not an lvalue, it's an rvalue. You cannot modify it, but you're trying to bind to a reference where it could be modified. If you make your reference const, it will work as expected. Consider this: int& x = 0; x = 1; // wtf :( This obviously is a no-go. But const&'s can be bound to temporaries (rvalues): const int& x = 0; x = 1; // protected :) [won't compile] Note that the life-time of the temporary is ended at the completion of the constructor. If you make static-storage for your constant, you'll be safe: class Foo { public: static const int Zero = 0; Foo() : x(Zero) // Zero has storage { y = 1; } private: const int& x; int y; };
2,232,243
2,232,696
c++, truncate a char array
I'm working on a project where I have a Time class and I need to format the time. void Time::FormatTime(char *string, unsigned int max_string_len) { ostrstream fd; ft << hour << ":" << minutes; cout << ft.str() << endl; } The user passes in a pointer to their string and the max length of the string and I need to check that the time string isn't longer than max_string_len and if it is, then truncate it. I'm not sure how to do the truncation as it's been awhile since I've written any C++. I'd like to not use the STL if possible. Thanks
Always use strncpy() to safely truncate a string into a char[N]. void Time::FormatTime(char *str, unsigned int max_string_len) { if ( max_string_len == 0 ) return; ostringstream ft; // strstream is obsolete, use stringstream ft << hour << ":" << minutes; strncpy( str, ft.str().c_str(), max_string_len ); str[ max_string_len - 1 ] = 0; }
2,232,309
2,464,470
Creating a System::String object from a BSTR in Managed C++ - is this way a good idea?
My co-worker is filling a System::String object with double-byte characters from an unmanaged library by the following method: RFC_PARAMETER aux; Object* target; RFC_UNICODE_TYPE_ELEMENT* elm; elm = &(m_coreObject->m_pStructMeta->m_typeElements[index]); aux.name = NULL; aux.nlen = 0; aux.type = elm->type; aux.leng = elm->c2_length; aux.addr = m_coreObject->m_rfcWa + elm->c2_offset; GlobalFunctions::CreateObjectForRFCField(target,aux,elm->decimals); GlobalFunctions::ReadRFCField(target,aux,elm->decimals); Where GlobalFunctions::CreateObjectForRFCField creates a System::String object filled with spaces (for padding) to what the unmanaged library states the max length should be: static void CreateObjectForRFCField(Object*& object, RFC_PARAMETER& par, unsigned dec) { switch (par.type) { case TYPC: object = new String(' ',par.leng / sizeof(_TCHAR)); break; // unimportant afterwards. } } And GlobalFunctions::ReadRFCField() copies the data from the library into the created String object and preserves the space padding: static void ReadRFCField(String* target, RFC_PARAMETER& par) { int lngt; _TCHAR* srce; switch (par.type) { case TYPC: case TYPDATE: case TYPTIME: case TYPNUM: lngt = par.leng / sizeof(_TCHAR); srce = (_TCHAR*)par.addr; break; case RFCTYPE_STRING: lngt = (*(_TCHAR**)par.addr != NULL) ? (int)_tcslen(*(_TCHAR**)par.addr) : 0; srce = *(_TCHAR**)par.addr; break; default: throw new DotNet_Incomp_RFCType2; } if (lngt > target->Length) lngt = target->Length; GCHandle gh = GCHandle::Alloc(target,GCHandleType::Pinned); wchar_t* buff = reinterpret_cast<wchar_t*>(gh.AddrOfPinnedObject().ToPointer()); _wcsnset(buff,' ',target->Length); _snwprintf(buff,lngt,_T2WFSP,srce); gh.Free(); } Now, on occasion, we see access violations getting thrown in the _snwprintf call. My question really is: Is it appropriate to create a string padded to a length (ideally to pre-allocate the internal buffer), and then to modify the String using GCHandle::Alloc and the mess above. And yes, I know that System::String objects are supposed to be immutable - I'm looking for a definitive "This is WRONG and here is why". Thanks, Eli.
Actually, the issue was not with the .NET string as an output buffer, but with the input buffer instead. The sprintf("%s") class functions (including wsprintf and so on) will perform a strlen-type operation on any parameters on the string - EVEN if it is snwprintf - the "n" part only limits the amount WRITTEN to the string, NOT the characters read from the input buffer. Turns out the input buffer was never guaranteed to be null terminated. Often times we get lucky because if the data returned was small, it would hit SOMETHING null before reaching bad memory. However, if the data in there is big enough, it would go to the end of the memory page. When the strlen keeps going, it walks off the page, and Access Violation city! Luckily I found this when testing something else with a native mode debugger attached and ready with all the debug symbols from MS for the C runtime! We switched the snwprintf to a wcsncpy() instead (the snwprintf was a legacy operation when we had to do ANSI->Unicode conversion - why he didn't do MultiByteToWideChar() instead, I'll never know. thanks for the advice at any rate.
2,232,493
2,232,522
Accessing data members shadowed by parameters
In Java you can access variables in a class by using the keyword this, so you don't have to figure out a new name for the parameters in a function. Java snippet: private int x; public int setX(int x) { this.x = x; } Is there something similar in C++? If not, what the best practice is for naming function parameters?
If you want to access members via this, it's a pointer, so use this->x.
2,232,496
2,232,519
Is it wrong to use C++ 'using' keyword in a header file?
I've been told it's bad to have "using namespace ns123" in a header file, but I can't remember what the reason given was. Is it in fact a bad thing to do, and why?
It's a bad practice, in general, because it defeats the purpose of namespaces. By defining in a header you're not enforcing strict control over the scope of the using declaration, meaning that you can run into name clashes in unexpected places.
2,232,580
2,232,651
Win32: BitTest, BitTestAndComplement, ... <- How to disable this junk?
WinNT.h has the following lines in it, in the VS2008 SP1 install: #define BitTest _bittest #define BitTestAndComplement _bittestandcomplement #define BitTestAndSet _bittestandset #define BitTestAndReset _bittestandreset #define InterlockedBitTestAndSet _interlockedbittestandset #define InterlockedBitTestAndReset _interlockedbittestandreset I have a number of templates that are based on BitTest<>() Does anyone know of a simple way to disable these #defines? Oftentimes MS does provide a #define XXX symbol which, if defined, will disable some offending portion of their header - e.g. NOMINMAX. I have been unable to find such a solution to the above problem. If you share frustration with Microsoft's many dubious choices, the read on. If not, stop here. ;) Editorializing: Why couldn't Microsoft just use the _bittest itself??? Or why couldn't they use BITTEST like every knows you should - always use all-caps for macros! Microsoft is still #defining things in 2010?! WTF?
Unfortunately, Microsoft believes it's OK to make their APIs use macros for names since they do it for 95% or more of their APIs to make them work 'transparently' for ANSI vs. Unicode APIs. It doesn't look like they've provided a clean way to prevent the macro from being defined. I think you're stuck with choosing from several bad options, including: #undef BitTest yourself modify the winnt.h header segregate your code that uses Windows APIs directly into modules that aren't dependent on your BitTest<> template I'm sure there are other options - I'm just not sure sure which one is the least distasteful.
2,232,692
2,232,891
Detecting a misspelt virtual function
I've been caught by this problem more than once: class A{ public: virtual ~A() {} virtual int longDescriptiveName(){ return 0; } }; class B: public A{ public: virtual int longDescriptveName(){ return 1; } // Oops }; If the function is pure virtual, the compiler catches the error. But if it's not this can be a terrible bug to track down. Part of the problem is that function names are maybe too long. But I still wonder, is there a way to see these bugs earlier?
One possibility is the little-used pure virtual function with implementation: virtual int longDescriptiveName() = 0 { return 0; } This forces deriving classes to override it. They can then call the base-class implementation alone if they only want that behaviour. Also you need to make sure your inheritance hierarchy is flat, rather than multi-layers, which is generally good anyway because inheritance is fragile enough without piling on the layers.
2,233,149
2,233,176
Two classes and inline functions
I have two classes and both of them uses some of the other class, on example: // class1.h class Class1; #include "class2.h" class Class1 { public: static Class2 *C2; ... }; // class2.h class Class2; #include "class1.h" class Class2 { public: static Class1 *C1; ... }; And when I define it like in example above, it works (I also have some #ifndef to avoid infinite header recurency). But I also want to add some inline functions to my classes. And I read here that I should put definition of inline function in header file, because it won't work if I'll put them in cpp file and want to call them from other cpp file (when I do it I get undefined reference during linking). But the problem here is with something like this: // class1.h ... inline void Class1::Foo() { C2->Bar(); } I get error: invalid use of incomplete type ‘struct Class2’. So how can I do it?
You need to delay including the header, but then include it and define your inline methods. By doing this in each header, they are self-sufficient and including one will always include the other, with include guards preventing infinite recursion. A.hpp #ifndef INCLUDE_GUARD_B9392DB18D114C1B8DFFF9B6052DBDBD #define INCLUDE_GUARD_B9392DB18D114C1B8DFFF9B6052DBDBD struct B; struct A { B* p; void foo(); }; #include "B.hpp" inline void A::foo() { if (p) p->bar(); } #endif B.hpp #ifndef INCLUDE_GUARD_C81A5FEA876A4C6B953D1EB7A88A27C8 #define INCLUDE_GUARD_C81A5FEA876A4C6B953D1EB7A88A27C8 struct A; struct B { A* p; void bar(); }; #include "A.hpp" inline void B::bar() { if (p) p->foo(); } #endif
2,233,166
2,233,180
Most efficient way to find the greatest of three ints
Below is my pseudo code. function highest(i, j, k) { if(i > j && i > k) { return i; } else if (j > k) { return j; } else { return k; } } I think that works, but is that the most efficient way in C++?
To find the greatest you need to look at exactly 3 ints, no more no less. You're looking at 6 with 3 compares. You should be able to do it in 3 and 2 compares. int ret = max(i,j); ret = max(ret, k); return ret;
2,233,401
2,239,081
Are redundant include guards necessary?
Are 'redundant include guards' necessary in Codegear RAD Studio 2009? Is the compiler smart enough to deal with this on it's own? For example, I might have the following 'include guard' in foo.h: #ifndef fooH #define fooH // ... declaration here #endif and the following 'redundant include guard' in use_foo.h: #ifndef fooH #include "foo.h" #endif Additionally, if the compiler is not smart enough, are 'redundant include guards' necesarry if they are being included in a source file. e.g. use_foo.cpp. ?
The portion of the code you marked as "redundant include guard" is not necessary but it is a possible optimization. In the case of C++Builder, there is logic to detect header guards, so it should not be necessary. In the general case, the preprocessing pass is usually pretty fast anyhow, so it's unlikely that this optimisation would buy you much anyhow.
2,233,503
2,233,521
How to get the size of the used space in an array? (NOT sizeof); c++
#include<iostream> using namespace std; int main() { char arr[200]; while(1) { cin >> arr; int i = sizeof(arr); cout << "The arr input is "<< arr << " and the size of the array is "<< i << endl; } return 0; } For the input of 34, This code outputs :The arr input is 34 and the size of the array is 200 while I want it to get the size of the used space of the array . So for The last input i want it to output :The arr input is 34 and the size of the array is 2 Can someone tell me how?
Maybe you want strlen(arr) here. It must be null terminated, otherwise the cout << arr would not have worked. You would need to #include <cstring>
2,233,578
2,233,585
FxCop (or equivalent) for non-.Net C++ code
Is there a way to get FxCop to analyze unmanaged C++ code? Setting the /clr flag allowed FxCop to open the .exe. It find a LOT of C++ items, but the analysis on the code is very weak. For example, the following code was skipped: int i=0; if (i=2) printf("Don't worry..everything will be okay."); I would like a tool that can catch the i=2 and warn that it should be i==2. Any advice on either getting FxCop to be more thorough or another tool that others found useful?
MSVC (at least VC9/VS2008) already warns about your specific example: warning C4706: assignment within conditional expression (Oops: I just realized that I have my test projects settings cranked up to Warning level 4 - /W4. MSVC doesn't issue this warning at the default setting). So set the project settings to /W4 and get more diagnostics (hopefully without too much noise). I find the warnings in VC9 to be pretty decent, and you can easily set the compiler to treat them as errors if you want to force the issue. The Team Server edition of Visual Studio contains support for PREfast - a static analysis tool from Microsoft (the option is in the C++ project's Advanced/Enable Code Analysis For C/C++). You can also get the tool in the Windows Driver Kit and/or the Windows SDK, though I can't vouch for the instructions on getting the WDK/SDK version integrated into Visual Studio: http://blogs.msdn.com/vcblog/archive/2008/02/05/prefast-and-sal-annotations.aspx http://buildingsecurecode.blogspot.com/2007/08/security-code-scanning-with-microsoft.html Another alternative some people like (non-free) is Gimpel's PC-Lint product.
2,233,932
2,233,949
C++ Confused about Threads
Basicly this is what I have: Server:: Server (int port) { cout << "Initializing server.\n"; (...) pthread_t newthread; pthread_create(&newthread, NULL, &Server::_startListening, NULL); cout << "Exit\n"; pthread_exit(NULL); // <-- Question } void* Server::_startListening (void* param) { cout << "Start listening for clients ...\n"; return 0; } Question: If I don't put pthread_exit(NULL); in the code, it will work when I compile it on Linux (Ubuntu) but it won't work on Mac OSX 10.6.2. When I compile and run it on linux it will say Initializing server, Start listening for clients, Exit while on Mac OSX it will say Initializing for server, Exit, Start listening for clients. The problem seems to occur around the pthread_exit, if I place it above the cout << Exit. That message will never be displayed (how weird is that). Am I doing something wrong?
you probably intend to use pthread_join rather than exit.
2,234,039
2,235,920
Slow writing to array in C++
I was just wondering if this is expected behavior in C++. The code below runs at around 0.001 ms: for(int l=0;l<100000;l++){ int total=0; for( int i = 0; i < num_elements; i++) { total+=i; } } However if the results are written to an array, the time of execution shoots up to 15 ms: int *values=(int*)malloc(sizeof(int)*100000); for(int l=0;l<100000;l++){ int total=0; for( unsigned int i = 0; i < num_elements; i++) { total+=i; } values[l]=total; } I can appreciate that writing to the array takes time but is the time proportionate? Cheers everyone
The first example can be implemented using just CPU registers. Those can be accessed billions of times per second. The second example uses so much memory that it certainly overflows L1 and possibly L2 cache (depending on CPU model). That will be slower. Still, 15 ms/100.000 writes comes out to 1.5 ns per write - 667 Mhz effectively. That's not slow.
2,234,046
2,235,107
Software to track several memory errors in old project?
I am programming a game since 2 years ago. sometimes some memory errors (ie: a function returning junk instead of what it was supposed to return, or a crash that only happen on Linux, and never happen with GDB or Windows) happen seemly at random. That is, I try to fix it, and some months later the same errors return to haunt me. There are a software (not Valgrind, I already tried it... it does not find the errors) that can help me with that problem? Or a method of solving these errors? I want to fix them permanently.
The Totalview debugger (commercial software) may catch the crash. Purify (commercial software) can help you find memory leaks. Does your code compile free of compiler warnings? Did you run lint?
2,234,071
2,234,088
The relationship between iterators and containers in STL
Good Day, Assume that I am writing a Python-like range in C++. It provides all the characteristics of Random Access containers(Immutable of course). A question is raised in my mind about the following situation: I have two different iterators, that point to different instances of the range container. The thing is that these two ranges are equal. i.e. they represent the same range. Would you allow the following situation: fact: range1 == range2 e.g. --------------------------- range range1(10, 20, 1), range2((10, 20, 1); range::iterator i = range1.begin(), j = range2.begin(); assert(i == j); // would you allow this? Sorry if I am missing a simple design rule in STL :)
By default, in the STL, two iterators from two different container are not comparable. This means, the behavior is unspecified. So you do whatever you want, nobody should even try. edit After looking carefully at the standard, section 24.1, paragraph 6 states: An iterator j is called reachable from an iterator i if and only if there is a finite sequence of applications of the expression ++i that makes i == j. If j is reachable from i, they refer to the same container. Which means that if you allow i == j with i and j in two different container, you really consider both container as being the same. As they are immutable, this is perfectly fine. Just a question of semantic.
2,234,133
2,234,152
Break out of an overloaded extraction operator? (C++)
I'm trying to use an overloaded ">>" to scan input from a file. The problem is, I have no idea how to deal with end of file. In this case, my file is composed of a number, followed by several chars Ex: 9rl 8d 6ff istream &operator>>(istream &is, Move &move) { char c; int i = 0; c = is.get(); if (!isalnum(c)) return; move.setNum(c); // I convert the char to an int, but I'l edit it out while ( (c = is.get()) != '\n') { move.setDirection(i, c); //sets character c into in array at index i i++; } // while chars are not newline return is; } // operator >> The test for the character being alpha numeric worked when I had this as a regular function, but doesn't work here as it expects an input stream to be returned. I've tried returning NULL as well. Suggestions? EDIT: this is being called in a while loop, So i'm trying to figure out some way to have this trigger some flag so that I can break out of the loop. In my previous function, I had this return a boolean, returning true if successful or false if the character was not alphanumeric
Return is. Callers should check the stream for errors. Be sure to set error bits as appropriate: std::istream &operator>>(std::istream &is, Move &move) { char c; int i = 0; c = is.get(); if (is.eof()) return is; else if (c < '0' || c > '9') { is.setstate(std::ios::badbit); return is; } else move.setNum(c-'0'); while ( (c = is.get()) != '\n' && is) move.setDirection(i++, c); if (c != '\n') is.setstate(std::ios::badbit); return is; } Use it as in the following: int main(int argc, char **argv) { std::stringstream s; s << "9rl\n" << "8d\n" << "6ff\n"; s.seekg(0); Move m; while (s >> m) std::cout << m; if (s.bad()) std::cerr << argv[0] << ": extraction failed\n"; return 0; } Notice that the code uses the instance m only after successful extraction.
2,234,135
2,234,241
Fastest way to convert 16.16 fixed point to 32 bit float in c/c++ on x86?
Most people seem to want to go the other way. I'm wondering if there is a fast way to convert fixed point to floating point, ideally using SSE2. Either straight C or C++ or even asm would be fine.
It's easy as long as you have a double-precision FPU: there are 53 bits of significant figures. SSE2 has double-precision. float conv_fx( int32_t fx ) { double fp = fx; fp = fp / double(1<<16); // multiplication by a constant return fp; }
2,234,257
2,234,260
How do I append a string to a char?
How do I append a string to a char? strcat(TotalRam,str); is what i got but it does not support strings
std::String has a function called c_str(), that gives you a constant pointer to the internal c string, you can use that with c functions. (but make a copy first)
2,234,294
2,234,313
position.hh:46: error: expected unqualified-id before ‘namespace’
Here's my code: 34 35 /** 36 ** \file position.hh 37 ** Define the example::position class. 38 */ 39 40 #ifndef BISON_POSITION_HH 41 #define BISON_POSITION_HH 42 43 #include <iostream> 44 #include <string> 45 46 namespace example 47 { 48 /// Abstract a position. 49 class position 50 { 51 public: 52 53 /// Construct a position. 54 position () 55 : filename (0), line (1), column (0) 56 { Thanks, speeder, that's great. Necrolis, thank you as well. Both of you guys are onto the same track on the compilation units. Here's the full error report: In file included from location.hh:45, from parser.h:64, from scanner.h:25, from scanner.ll:8: position.hh:46: error: expected unqualified-id before ‘namespace’ location.hh looks like this: 35 /** 36 ** \file location.hh 37 ** Define the example::location class. 38 */ 39 40 #ifndef BISON_LOCATION_HH 41 # define BISON_LOCATION_HH 42 43 # include <iostream> 44 # include <string> 45 # include "position.hh" 46 47 namespace example 48 { 49 50 /// Abstract a location. 51 class location 52 { 53 public: I should also add that these files are being generated by bison. it's when i try to compile the c++ scanner class generated by flex++ that I get to this stage. I get the .cc code by issuing flex --c++ -o scanner.cc scanner.ll.
this happen when a ; or some other closing thing is lacking before the namespace. Are you sure that the lines before 34 have no code? If they have code (even if that code is other #include) the error is there. EDIT: Or in case all 34 lines have no code, the error is on the file that includes this header, most likely there are a code without a ending ; or } or ) or some other ending character, and right after it (ignoring comments, of course) there are the #include position.hh Or if there are two includes in a row, one before position.hh, the last lines of the header included before position.hh are with the error, usually a structure without a ; after the closing }
2,234,310
3,597,032
Using Mysql blocking API with Boost::asio
I am building a aync single threaded server that receives data from clients. It processes the data and then saves it to the MySQL Database. The problem is that, MySQL C API does not support non-blocking calls and asio mainly does not like blocking calls. So I am thinking something like Python Twisted's deferToThread() like semantics. Is there anyone who already developed such thing? Or should I implement it?
There was a post to the Asio mailing list over the summer describing a generic asynchronous service class that seems like it might be useful for you. This pseudo code is from the author's email I linked: // Create a command processor with 5 threads allocated // to processing the commands. async_command_processor processor(io_service, 5); // Execute the command asynchronously and call the // MyCommandComplete callback when completed. processor.async_execute(MyCommand, MyCommandComplete);
2,234,508
2,234,678
Initialization of list with for_each to random variables
I'm trying to initialize a list to random integers using a for_each and a lambda function. I'm new to boost.lambda functions so I may be using this incorrectly but the following code is producing a list of the same numbers. Every time I run it the number is different but everything in the list is the same: srand(time(0)); theList.resize(MaxListSize); for_each(theList.begin(), theList.end(), _1 = (rand() % MaxSize));
Boost lambda will evaluate rand before the functor is made. You need to bind it, so it's evaluated at lambda evaluation time: #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> // for bind #include <algorithm> #include <cstdlib> #include <ctime> #include <iostream> #include <vector> int main() { namespace bl = boost::lambda; typedef std::vector<int> int_vec; static const size_t MaxListSize = 10; static const int MaxSize = 20; int_vec theList; theList.resize(MaxListSize); std::srand(static_cast<unsigned>(std::time(0))); std::for_each(theList.begin(), theList.end(), bl::_1 = bl::bind(std::rand) % MaxSize); std::for_each(theList.begin(), theList.end(), std::cout << bl::_1 << ' ' ); } This works as expected. However, the correct solution is to use generate_n. Why make a bunch of 0's just to overwrite them? #include <boost/lambda/lambda.hpp> #include <boost/lambda/bind.hpp> #include <algorithm> #include <cstdlib> #include <ctime> #include <iostream> #include <vector> int main() { namespace bl = boost::lambda; typedef std::vector<int> int_vec; static const size_t MaxListSize = 10; static const int MaxSize = 20; int_vec theList; theList.reserve(MaxListSize); // note, reserve std::srand(static_cast<unsigned>(std::time(0))); std::generate_n(std::back_inserter(theList), MaxListSize, bl::bind(std::rand) % MaxSize); std::for_each(theList.begin(), theList.end(), std::cout << bl::_1 << ' ' ); }
2,234,553
2,235,131
UseQueryResult is not a member of mysqlpp
That's the error I get when I run this code : if(mysqlpp::UseQueryResult res = conn.query(sql).use()) Whats more interesting is that the next line doesn't have any problems while(mysqlpp::Row row = res.fetch_row()) Really driving me crazy. I've even manually included result.h I tried all combos of these include result.h, mysql++.h, connection.h
Is it possible that you're using an old version of MySQL++? The StoreQueryResult class used to be called Result before version 3.0.0. Edit: Er... and UseQueryResult used to be called ResUse, which is a bit more relevant to your error message.
2,234,557
2,234,955
C++ using getline() prints: pointer being freed was not allocated in XCode
I'm trying to use std:getline() but getting a strange runtime error: malloc: * error for object 0x10000a720: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug This is the code that produces this error: //main.cpp #include <iostream> #include <sstream> int main (int argc, char * const argv[]) { std::istringstream my_str("demo string with spaces"); std::string word; while (std::getline(my_str, word, ' ')) { std::cout << word << std::endl; } return 0; } Before each word I get this error. From the comments it seems to be a OSX/XCode specific error. Any hints on that? Update: The error is only printed in Debug mode. If I build this code in Release mode everything is fine. Update 2: More info on that issue can be found here. Solution: Set _GLIBCXX_FULLY_DYNAMIC_STRING=1 in your Preprocessor Macros in targets info build tab. System info: OSX 10.6.2 | XCode 3.2 | g++ 4.2 | debug config for i386
At least one person has reported problems with g++ 4.2.1 on Apple that seem possibly related to yours having to do with an improper configuration of the standard library with the _GLIBCXX_FULLY_DYNAMIC_STRING definition (not that I understand any of what I'm typing here). You might get a bit of a clue from the newsgroup thread that includes this message: http://gcc.gnu.org/ml/gcc-bugs/2009-10/msg00807.html
2,234,952
2,234,980
Ambiguity between IID_IDropTarget and Virtualtrees::IID_IDropTarget
I'm currently going through a process of refactoring includes to reduce compile time, and I've come across the following compile error: [C++ Error] some_class.cpp(53): E2015 Ambiguity between 'IID_IDropTarget' and 'Virtualtrees::IID_IDropTarget' The line of code it points to is: if (iid == IID_IUnknown || iid == IID_IDropTarget) If I use Virtualtrees::IID_IDropTarget it compiles fine, however I need to use COMs IDropTarget interface which I have implemented. I believe the problem might be that the Virtualtrees component has another implementation of the IDropTarget interface and they are conflicting. Any ideas how I can specify that I don't want Virtualtrees::IID_IDropTarget? Or the namespace I use for COM's IID_IDropTarget?
COM's IID_DropTarget is declared like so: EXTERN_C const IID IID_IDropTarget; Since it's extern "C", it's in the root namespace: ::IID_IDropTarget
2,235,137
2,243,559
c++: following piece of code crashes
#include <iostream> using namespace std; class B { public: B() { cout << "Base B()" << endl; } ~B() { cout << "Base ~B()" << endl; } private: int x; }; class D : public B { public: D() { cout << "Derived D()" << endl; } virtual ~D() { cout << "Derived ~D()" << endl; } }; int main ( void ) { B* b = new D; delete b; } ---- output---------- Base B() Derived D() Base ~B() *** glibc detected *** ./a.out: free(): invalid pointer: 0x0930500c *** ======= Backtrace: ========= /lib/tls/i686/cmov/libc.so.6[0xb7d41604] /lib/tls/i686/cmov/libc.so.6(cfree+0x96)[0xb7d435b6] /usr/lib/libstdc++.so.6(_ZdlPv+0x21)[0xb7f24231] ./a.out[0x8048948] /lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe5)[0xb7ce8775] ./a.out[0x80487c1] Aborted If i remove the private member "int x" from the base class, it works fine
What you are doing is UB, but for the specific compiler you are using behavior can be described as follows. To ease the ASCII-graphics below, modifying the example, adding a y member to D and modifying main. #include <iostream> using namespace std; class B { public: B() { cout << "Base B()" << endl; } ~B() { cout << "Base ~B()" << endl; } private: int x; }; class D : public B { public: D() { cout << "Derived D()" << endl; } virtual ~D() { cout << "Derived ~D()" << endl; } private: int y; // added. }; int main ( void ) { D* d = new D; // modified. B* b = d; delete b; } In the compiler you are using, the vtable, if any, is placed in the beginning of the memory block. In the compiler you are using the memory layout for this is as follows: +--------+ | vtable | <--- d points here, at the start of the memory block. +--------+ | x | <--- b points here, in the middle of the memory block. +--------+ | y | +--------+ Later when calling delete b the program will try to free the memory block using the b pointer, which points to the middle of the memory block. This will in turn result in the crash due to the invalid pointer error.
2,235,208
2,306,125
How to decode huffman code quickly?
I have implementated a simple compressor using pure huffman code under Windows.But I do not know much about how to decode the compressed file quickly,my bad algorithm is: Enumerate all the huffman code in the code table then compare it with the bits in the compressed file.It turns out horrible result:decompressing 3MB file would need 6 hours. Could you provide a much more efficient algorithm?Should I use Hash or something? Update: I have implementated the decoder with state table,based on my friend Lin's advice.I think this method should be better than travesal huffman tree,3MB within 6s. thanks.
One way to optimise the binary-tree approach is to use a lookup table. You arrange the table so that you can look up a particular encoded bit-pattern directly, allowing for the maximum possible bit-width of any code. Since most codes don't use the full maximum width, they are included at multiple locations in the table - one location for each combination of the unused bits. The table indicates how many bits to discard from the input as well as the decoded output. If the longest code is too long, so the table is impractical, a compromise is to use a tree of smaller fixed-width-subscript lookups. For example, you can use a 256-item table to handle a byte. If the input code is more than 8 bits, the table entry indicates that decoding is incomplete and directs you to a table that handles the next up-to 8 bits. Larger tables trade memory for speed - 256 items is probably too small. I believe this general approach is called "prefix tables", and is what BobMcGees quoted code is doing. A likely difference is that some compression algorithms require the prefix table to be updated during decompression - this is not needed for simple Huffman. IIRC, I first saw it in a book about bitmapped graphics file formats which included GIF, some time before the patent panic. It should be easy to precalculate either a full lookup table, a hashtable equivalent, or a tree-of-small-tables from a binary tree model. The binary tree is still the key representation (mental model) of how the code works - this lookup table is just an optimised way to implement it.
2,235,219
2,235,274
Overloading the global type conversion operator
To test and display the result of some functions of my library, I am creating a set of handy functions. I have an execute function that looks like : template <typename R, typename I> std::string execute( const std::string& func_name, R(*func_ptr)( const I& ), const I& func_input ); It calls the function, and display the results and arguments in a formatted string that I can send to std::cout. The problem is that some of my functions do not return convertible-to-string results. I thought I could simply overload the global ::operator std::string with something like: template <typename T> operator std::string( const std::vector<T>& v ); But GCC complains: error: 'operator std::string(const std::vector<T, std::allocator<_CharT> >&)' must be a nonstatic member function Well, the problem of course is that I cannot add member operators to std::vector, and even for my classes, I don't want to pollute them with "for testing" conversion operators. I guess that I can add a layer of indirection and use a function instead of a conversion operator, but that would not be the more aesthetic solution. I could also overload ::operator << for std::ostream and use a std::ostringstream, but that also is not the cleanest solution. I wondered if the global conversion operator is really not overloadable, and if so, why.
Conversion operators (cast operators) must be a member of the convertible class that produces the converted type. As assignment operators, they must be member functions, as your compiler is telling you. Depending on how much effort you want to put into the debug part of it, you could try to use metaprogramming to forward your execute method to different actual implementations, providing specific ones for containers that will print the contents. Why don´t you want to provide operator<< for your types? I think that is actually the idiomatic solution. Unlike other languages that you use methods that convert to string to produce printable results, in C++ the idiomatic way is providing operator<< and then using stringstreams (or boost::lexical_cast or some similar solution) to convert to strings based on the operator<< implementation. There is a simple utility class here to create a string from elements that override operator<< if you want to use that for a start point.
2,235,325
2,235,349
Simple C++ syntax question about colon
I just saw a code snippet with a piece of syntax that I have never seen before. What does bool start : 1; mean? I found it inside a class definition in a header file.
struct record { char *name; int refcount : 4; unsigned dirty : 1; }; Those are bit-fields; the number gives the exact size of the field, in bits. (See any complete book on C for the details.) Bit-fields can be used to save space in structures having several binary flags or other small fields, and they can also be used in an attempt to conform to externally-imposed storage layouts. (Their success at the latter task is mitigated by the fact that bit-fields are assigned left-to-right on some machines and right-to-left on others). Note that the colon notation for specifying the size of a field in bits is only valid in structures (and in unions); you cannot use this mechanism to specify the size of arbitrary variables. References: K&R1 Sec. 6.7 pp. 136-8 K&R2 Sec. 6.9 pp. 149-50 ISO Sec. 6.5.2.1 H&S Sec. 5.6.5 pp. 136-8
2,235,360
2,235,382
Making a borderless window with for Qt
I'm new to Qt C++. I downloaded the latest windows version, did some tutorials and its great. I saw some styling options that the Qt framework has and its great, but now I need to build my application that its main windows (form) it designed/skinned with image without the rectangle borders (borderless?). How can I do it with Qt?
If your looking for some advanced styling in the shape of a widget, maybe this example will help you: Shaped Clock Example Or maybe you're simply looking for this kind of flag: Qt::CustomizeWindowHint or simply Qt::FramelessWindowHint.
2,235,366
2,235,393
How to assign a string to char *pw in c++
How to assign a string to char *pw in c++ like... char *pw = some string ??
For constant initialization you can simply use const char *pw = "mypassword"; if the string is stored in a variable, and you need to make a copy of the string then you can use strcpy() function char *pw = new char(strlen(myvariable) + 1); strcpy(pw, myvariable); // use of pw delete [] pw; // do not forget to free allocated memory
2,235,447
2,236,083
XML in C++ Builder 6
How can I use XML as a simple data storage in Borland C++ Builder 6? Is there an internal class, which I could use? Thank's for help
I'm not sure whether the TXmlDocument is implemented in C++Builder 6, but a more simple solution would be to use the TinyXML [1] library, which is indeed simple, and easy to use. I have used it with different versions of C++ Builder and it works like a charm. [1] http://www.grinninglizard.com/tinyxml/
2,235,457
2,235,492
How to explain undefined behavior to know-it-all newbies?
There'a a handful of situations that the C++ standard attributes as undefined behavior. For example if I allocate with new[], then try to free with delete (not delete[]) that's undefined behavior - anything can happen - it might work, it might crash nastily, it might corrupt something silently and plant a timed problem. It's so problematic to explain this anything can happen part to newbies. They start "proving" that "this works" (because it really works on the C++ implementation they use) and ask "what could possibly be wrong with this"? What concise explanation could I give that would motivate them to just not write such code?
"Congratulations, you've defined the behavior that compiler has for that operation. I'll expect the report on the behavior that the other 200 compilers that exist in the world exhibit to be on my desk by 10 AM tomorrow. Don't disappoint me now, your future looks promising!"
2,235,767
2,235,838
Storing function pointers
The following uses a simple function pointer, but what if I want to store that function pointer? In that case, what would the variable declaration look like? #include <iostream> #include <vector> using namespace std; double operation(double (*functocall)(double), double wsum); double get_unipolar(double); double get_bipolar(double); int main() { double k = operation(get_bipolar, 2); // how to store get_bipolar? cout << k; return 0; } double operation(double (*functocall)(double), double wsum) { double g = (*functocall)(wsum); return g; } double get_unipolar(double wsum) { double threshold = 3; if (wsum > threshold) return threshold; else return threshold; } double get_bipolar(double wsum) { double threshold = 4; if (wsum > threshold) return threshold; else return threshold; }
You code is almost done already, you just seem to call it improperly, it should be simply double operation(double (*functocall)(double), double wsum) { double g; g = functocall(wsum); return g; } If you want to have a variable, it's declared in the same way double (*functocall2)(double) = get_bipolar; or when already declared functocall2 = get_bipolar; gives you a variable called functocall2 which is referencing get_bipolar, calling it by simply doing functocall2(mydouble); or passing it to operation by operation(functocall2, wsum);
2,235,826
2,235,983
Winsock2 recv() hook into a remote process
I was trying to hook a custom recv() winsock2.0 method to a remote process, so that my function executes instead of the one in the process, i have been googling this and i found some really good example, but they lack description typedef (WINAPI * WSAREC)( SOCKET s, char *buf, int len, int flags ) = recv; Now my question is, what does this mean, or does, is this some sort of a pointer to the real recv() function? And then the other piece of code for the custom function int WINAPI Cus_Recv( SOCKET s, char *buf, int len, int flags ) { printf("Intercepted a packet"); return WSAREC( s, buf, len, flags ); // <- What is this? } Sorry if these questions sound really basic, i only started learning 2 or 3 weeks ago. Thanks.
where did you find such an example ? the first line tries to define a new type WSAREC, which is a pointer to a function having the same signature as recv(). unfortunately, it is also trying to declare a variable of this type to store the address of the recv() function. the typedef is wrong since the function is lacking a return type. so it does not compile under Visual Studio 2003. you may have more luck using: int (WINAPI * WSAREC)( SOCKET s, char *buf, int len, int flags ) = &recv; which declares only a variable of type "pointer to function", which stores the address of the recv(). now the second snippet is a function which has the same signature as the recv()function, which prints a message, then calls the original recv() through the function pointer declared above. the code here only shows how to call a function through a pointer: it does not replace anything in the current process. also, i am not sure you can interfere with another process and replace one function at your will. it would be a great threat to the security of the system. but why would you do that in the first place ??
2,236,007
2,236,139
ActiveX code from Visual C++ port to Borland C++ Builder
I have the following code example for Visual C++ which creates an ActiveX object which can then be used. // create a smart pointer for ActiveDSO _DActiveDSOPtr activeDSO; HRESULT hr = activeDSO.GetActiveObject(__uuidof(ActiveDSO)); if (FAILED(hr)) { hr = activeDSO.CreateInstance(__uuidof(ActiveDSO)); if (FAILED(hr)) _com_issue_error(hr); } How should this be ported to Borland C++ builder. I am unsure how it creates ActiveX objects. What should I be looking for to help find the solution, or at least work towards it.
I used to know how to do this, but I haven't used C++ Builder in more than 5 years. I do remember that C++ Builder comes at ActiveX from a completely different direction, and that code sample won't "translate". Better to find C++ Builder tutorials and work from there (looking at Deliphi tutorials will also help, they use the same components to wrap the ActiveX objects). I know this is more "advice" than an answer, but it the best I can do for you. From a quick search, I found this page that says how to import a specific ActiveX dll, once it's imported I think you use it like any other VCL object. I hope this helps. How to use ActiveX in Borland C++ Builder 4
2,236,182
2,236,232
What is the difference between using a struct with two fields and a pair?
What is the difference regarding memory allocation and efficiency between using a struct with two fields and a pair?
std::pair provides pre-written constructors and comparison operators. This also allows them to be stored in containers like std::map without you needing to write, for example, the copy constructor or strict weak ordering via operator < (such as required by std::map). If you don't write them you can't make a mistake (remember how strict weak ordering works?) so it's more reliable just to use std::pair.
2,236,197
2,236,227
What is the easiest way to initialize a std::vector with hardcoded elements?
I can create an array and initialize it like this: int a[] = {10, 20, 30}; How do I create a std::vector and initialize it similarly elegant? The best way I know is: std::vector<int> ints; ints.push_back(10); ints.push_back(20); ints.push_back(30); Is there a better way?
One method would be to use the array to initialize the vector static const int arr[] = {16,2,77,29}; vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
2,236,302
13,014,365
Crashing C++ application including ada dll does not generate core dump
How do I get a C++ application including a loaded ada shared library to generate a core dump when crashing? I have a C++ application which loads a ada shared library, inside the ada code I get a stack overflow error which causes program termination along with the console output: raised STORAGE ERROR No core dump file is generated even thou I have issued a "ulimit -c unlimited" before starting the application. Same thing happens if I send a kill SIGSEGV to the application. Sending kill SIGSEGV to another application that does not use the ada dll generates a core dump file just the way I want it to. Found some information here: http://objectmix.com/ada/301203-gnat-fstack-check-does-work.html UPDATED! As mentioned by Adrien, there is no contradiction, -s sets the stack limit while -c sets the core file limit. Still the problem remains. I checked the flags when building the ada library and the fstack-check flag was not set, so it should generate a core dump. Althou I haven't tried it yet, it seems somewhat strange. It mentions the -fstack-check compiler option + setting the GNAT_STACK_LIMIT variable but at the same time refers to the ulimit command which seems like a contradiction, setting "ulimit -c " is the only way I know of getting a core dump to be generated at the time of crash, if this infers with the fstack-check option then we have a catch 22.
Now, almost 2 years later (still working at the same company as Kristofer did when he asked the question), was the question raised again - and finally I think that I understands why no core-dump is generated!! The problem is caused by the Ada run-time, which by default implements a signal handler for some POSIX-signals (for Linux: SIGABRT, SIGFPE, SIGILL, SIGSEGV and SIGBUS). For GNAT/linux the signal handler is called __gnat_error_handler in a-init.c, which looks something like this: static void __gnat_error_handler (int sig) { struct Exception_Data *exception; char *msg; static int recurse = 0; ... switch (sig) { case SIGSEGV: if (recurse) { exception = &constraint_error; msg = "SIGSEGV"; } else { ... msg = "stack overflow (or erroneous memory access)"; exception = &storage_error; } break; } recurse = 0; Raise_From_Signal_Handler (exception, msg); } This handler is "process wide", and will be called by any trigged signal, no matter from which part of the process it originates from (no matter if coded in Ada/C/C++...). When called, the handler rises an Ada-exception and leaves it to the Ada runtime to find an appropriate exception handler - if no such handler is found (eg. when an SIGSEGV is generated by any part of the C++-code), the Ada-runtime falls back to just terminate the process and just leave a simple printout from __gnat_error_handler (eg. "stack overflow (or erroneous memory access)"). http://www2.adacore.com/gap-static/GNAT_Book/html/node25.htm To prevent Ada-runtime from handling a POSIX-signal, and convert it to an Ada-exception, it is possible to disable the default beahviour by using pragma Interrupt_State (Name => value, State => SYSTEM | RUNTIME | USER);, eg. to disable handling of SIGSEGV, define Pragma Interrupt_State(SIGSEGV, SYSTEM); in your Ada-code - now the system's default behaviour will be trigged when a SIGSEGV is raised, and a core-dump will be generated that allows you to trace down the origin of the problem! I think this is a quite important issue to be aware of when mixing Ada and C/C++ on *NIX-platforms, since it may mislead you to think that problems origins from the Ada-code(since the printout indicates an exception generated from Ada) when the real source of the problem lays in the C/C++-code... Although it is probably safe to disable the Ada-runtime default handling of SIGSEGV (I guess no sane programmer using this in any "expected" error handling... Well, maybe used in aviation software or similar, when some sort of "last resort" functionallity needs to be maintained to avoid something really bad from happening..) i guess a bit caution should be taken then "overriding" the Ada-runtime handling for signals. One issue may be the SIGFPE-signal, which also raises an Ada Constraint_Error-exception by default. This type of exception may be used by the Ada-code as an "excpected behaviour". Disabling SIGFPE by Pragma Interrupt_State may seriously affect the execution of the Ada-code, and crash your application during "normal circumstances" - on the other hand will any division by zero in the C/C++-code trig the Ada-exception handling mechanism, and leave you without any real trace of the origin of the problem...
2,236,445
2,236,519
deleting element (objects) within a vector (not referenced by pointer) , memory handling
This is an extension of this question . I have searched on the web but couldn't find a satisfactory answer. I have a class A which defines a vector that contains a number of instances of class Region. The memory handling for these Region instances need to be managed by Class A My questions are: 1. In the following code snippet, do I need to explicitly delete these instances in the desctuctor of class A? 2. Should I create instances as new Region(i) ? Is it better over the first option (not using new) Class A is quite a large object. How should I determine whether to use new or not? 3. If Answer to #2 is yes, how should I delete these instances in the destructor ? delete Region(i) (in a for loop) or delete [] reg?? I am guessing former way is the correct way, but want to confirm. 4. Other than "Region instances are not deleted" , do you see any obvious memory leak... especially in the construction of Region object in A's constructor? class Region{ public: Region(int num); int number; std::vector <elemt*> elements; int info; } class A{ public: std::vector<Region> reg; const int numOfRegions = 100; } A::A(){ int i; for ( i=0; i<numOfRegions; i++){ reg.push_back(Region(i)); } } A::~A(){ // How should the elements within vector Region be deleted?? // Should I use "new" to allocate memory to instances of Region() } UPDATE: A BIG Thanks to all who answered!
In the following code snippet, do I need to explicitly delete these instances in the desctuctor of class A? No - they will be automatically deleted for you - if you don't create it with new, you don't delete it. Should I create instances as new Region(i) ? Is it better over the first option (not using new) Class A is quite a large object. How should I determine whether to use new or not? The size of A is not an issue. There is no clear answer to this question but the general rule is that if you don't have to create objects dynamically using new, then don't do so. If Answer to #2 is yes, how should I delete these instances in the destructor ? delete Region(i) (in a for loop) or delete [] reg?? I am guessing former way is the correct way, but want to confirm. If you created them using new, you would delete them in a for loop as: delete reg[i]; reg would have to be a vector of pointers of course. a better option would be to use a vector of smart pointers. Other than "Region instances are not deleted" , do you see any obvious memory leak.. especially in the construction of Region object in A's constructor? They are deleted - just not by you. This is known as RAII and is very, very good C++ practice - you should use RAII whenever possible.
2,236,467
2,379,414
CMake + find package or check out and install
I just switched to CMake. And yet found it very useful and realized some simple apps and libs. Somewhere I read that it's possible to query git to checkout repositories from within cmake scripts. I'd like to check for the existence of a package with my Find(package).cmake If it doesn't exist i'd like to initiate a checkout and add the new directory to the cmake script as subdirectory. That way all my dependencies will get installed automatically. Does somebody know how to accomplish this idea? Thank you! Bye, Arthur
You're probably thinking about the ExternalProject module added in CMake 2.8. It's documented at http://www.cmake.org/cmake/help/cmake-2-8-docs.html#module:ExternalProject with an intro to it at page 14 of http://www.kitware.com/products/archive/kitware_quarterly1009.pdf. It allows you checkout/download a project and build it automatically.
2,236,699
2,236,792
Will `typedef enum {} t` allow scoped enum element identifiers in C++0x?
I believe the new C++ standard allows for an extra "scope" for enumerated types: enum E { e1, e2 }; E var = E::e1; Since I know lots of source files containing the old C-style enum typedef, I wondered if the new standard would allow using the typedef for these otherwise anonymous enumerated types: typedef enum { d1, d2 } D; D var = D::d1; // error?
The new standard will add a new type of strong enum, but the syntax will be slightly different, and old style enums will be compatible (valid code in C++03 will be valid C++0x code) so you will not need to do anything to keep legacy code valid (not the typedef, not anything else). enum class E { e1, e2 }; // new syntax, use E::e1 enum E2 { e1, e2 }; // old syntax, use e1 or E2::e1 (extension) There is a C++ FAQ here that deals with this particular issue.
2,236,924
2,236,963
C++ and Enum and class members
Following code is not compiling, can anybody please help what is wrong here class CTrapInfo { public: enum GenericType { ColdStart, WarmStart, LinkDown, LinkUp, AuthenticationFailure, EGPNeighborLoss, EnterpriseSpecific }; CTrapInfo(); CTrapInfo(const CTrapInfo&); ~CTrapInfo(); CTrapInfo &operator=(const CTrapInfo&); static GenericType toGenericType(const DOMString&); }; Compiler error is : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int MSDN says this is valid in c++ http://msdn.microsoft.com/en-us/library/2dzy4k6e%28VS.80%29.aspx
It compiles for me, in VS2005, if I forward declare class CAPTrapInfo and class DOMSTring.
2,237,100
2,237,515
Is there any way to specify a generic argument to a function with the restriction that it should implement a given interface
Example: I have a function that works with vectors: double interpolate2d(const vector<double> & xvals, const vector<double> & yvals, double xv, double yv, const vector<vector<double> > &fvals) { int xhi, xlo, yhi, ylo; double xphi, yphi; bracketval(xvals,xv,xhi,xlo,xphi); bracketval(yvals,yv,yhi,ylo,yphi); return (fvals[xhi][yhi]*xphi+fvals[xlo][yhi]*(1.-xphi))*yphi + (fvals[xhi][ylo]*xphi+fvals[xlo][ylo]*(1.-xphi))*(1.-yphi); } But now I want to call it with boost::array elements for the first 2 arguments (same with bracketval()), if std::vector and boost::array were self-implemented, I would be able to derive both from a common base class (interface-like) enforcing an implementation of operator[], since both are library-provided, is there any way to cast/specify such a restriction? I can always resort to plain c-arrays, but it's not very neat. Edit: FWIW, here is the original bracketval implementation: void bracketval(const vector<double> &vals, double v, int &hi, int &lo, double &prophi){ hi=vals.size()-1; lo=0; while(abs(hi-lo)>1) { int md = (hi+lo)/2; if(vals[md]>v) hi=md; else lo=md; } if(vals[hi]!=vals[lo]) prophi = (v-vals[lo])/(vals[hi]-vals[lo]); else prophi = 0.5; }
This works with std::vector, boost::array, built-in arrays an generally with anything that is indexable. I've also included a suggestion of how you should implement the bracketval function: template<class Vec> void bracketval(Vec const & xvals, double xv, int xhi, int xlo, double xphi) { } template <class Vec, class VecOfVecs> double interpolate2d(Vec const & xvals, Vec const & yvals, double xv, double yv, VecOfVecs const & fvals) { int xhi, xlo, yhi, ylo; double xphi, yphi; bracketval(xvals,xv,xhi,xlo,xphi); bracketval(yvals,yv,yhi,ylo,yphi); return (fvals[xhi][yhi]*xphi+fvals[xlo][yhi]*(1.-xphi)) *yphi + (fvals[xhi][ylo]*xphi+fvals[xlo][ylo] *(1.-xphi))*(1.-yphi); } int main() { { std::vector<double> v, w; std::vector<std::vector<double> > vv; interpolate2d(v, w, 1., 2., vv); } { boost::array<double, 4> v, w; boost::array<boost::array<double, 4>, 4> vv; interpolate2d(v, w, 1., 2., vv); } { double v[4], w[4]; double vv[4][4]; interpolate2d(v, w, 1., 2., vv); } } You can even add an extra template parameter if you envision the possibility that the second vector could be of a different type that the first (e.g., the first a vector and the second a boost::array): template <class VecX, class VecY, class VecOfVecs> double interpolate2d(VecX const & xvals, VecY const & yvals, double xv, double yv, VecOfVecs const & fvals)
2,237,582
2,237,701
Can someone tell me why my code generates a segmentation on SPOJ? and what is the segmentation fault error ?(FCTRL2)
#include<stdio.h> #include<iostream> #include<string> #include<string.h> using namespace std; char arr[200],res[200]; char table[150][200]; string multiply(char n[],int m) { int N=strlen(n),M,temp=0,x=0; for(int i=0;i<N;i++) arr[i]=n[N-1-i]; for(int i=0;i<N;i++) { x=m*(arr[i]-'0')+temp; x=m*(arr[i]-'0')+temp; arr[i]=(x%10)+'0'; temp=x/10; } while(temp>0) { arr[N]=(temp%10)+'0'; temp/=10; N++; } M=strlen(arr); for(int i=0;i<M;i++) res[i]=arr[M-1-i]; } void make_table() { table[0][0]='1'; for(int i=1;i<101;i++) { multiply(table[i-1],i); int u=strlen(res); for(int j=0;j<u;j++) { table[i][j]=res[j]; } } } int main() { int tc,n; scanf(" %d",&tc); make_table(); while(tc--) { scanf(" %d",&n); printf("%s\n",&table[n]); } return 0; } That's my code for this problem : http://www.spoj.pl/problems/FCTRL2/ It generates correct answers for me but when i submit it , it tells me Runtime error(segmentation fault) . Can anyone explain to me what is the segmentation fault? cause i read it on the spoj website and i didn't understand how to avoid it and how to upgrade my code?
If you replace the return type of the function multiply from string to void the segfault is gone. A segmentation fault happens when you try to read/write memory you don't have access to. For instance you can try writing on read only memory, or reading at address 0x00000000. A common way to achieve segfaults is by using an uninitialized pointer. A debugger is often a good help to find a segmentation fault, as it will stop and show you where is happened.
2,237,603
2,237,647
Questions about the static keyword with functions and data
I have a few questions about the static keyword in C++ (and probably with other languages as well.) What is the purpose of declaring a function as static? void static foo(int aNumber) { ... } How about a static inline function? void static inline foo(int aNumber) { ... } Is there any benefit to using the static keyword with a function, and do those benefits apply to class functions as well? I realize some datatypes like structs and arrays have to be static when compiling with an older compiler, but is there any point when using a new ANSI-C++ compiler (like MS VC++ 2008)? I know that using a static variable inside a loop saves time by keeping the data in memory and not reallocating memory every loop iteration, but how about when a variable is declared only once, like at the top of a header file or within a namespace?
Depends on Context: Like many things in C++, static means different things depending on its context. It's very common in C++ for the same word to mean different things depending on its context. For example: * is used for multiplication, dereferencing a pointer, and creating pointers. & is used to get the address of variables, to declare a reference, and as a bitwise AND operator. Global use of static: If you declare a function or variable as static outside of a class and in global scope, it is specific to only that file. If you try to use that variable or function in a different file (via a forward declaration) you will get a linking error. Example: a.cpp: static void fn() { cout<<"hello a!"<<endl; } b.cpp: void fn(); void gn() { fn();//causes linking error } This feature allows you to use a function that no other file will ever see, that way you don't cause possible linker errors of a symbol defined multiple times. The preferred method to do this is with anonymous namespaces though: a.cpp: namespace { void fn() // will be static to a.cpp { cout<<"hello a!"<<endl; } } Inside of a class use of static: If you declare a function or variable as static inside of a class (or struct), it is a class function or class variable. This means that there is only one for that whole class. A class function can only use class variables. A class variable is shared amongst all instances of that class. class C { public: static void fn() { y = 4;//<--- compiling error // can't access member variable within a static function. } int y; } This is a great feature to use if you have something that is specific to the class of your objects, but not specific to an instance. Inside a function use of static: If you declare a variable as static inside of a function, you can consider that the variable value will persist upon calls. It will only be initialized once. Example: //Will print 0, then 1, then 2, ... void persistentPrintX() { static int x = 0; cout << x << endl; x++; } I personally try to avoid this, and you probably should to. It is not good to have global state. It is better to have functions that given the same input guarantees the same output. Just like in the English language: The concept of context sensitive meaning is not specific to C++, you can even see it in the English language. I am going to screen a movie (Means showing the movie) The screen on the TV is broken (Means a part of the TV) Other meanings in other programming languages: Depending on the programming language there can be a different meaning, but the first thing most people think of when you say static is a class variable/function vs a member variable/function.
2,237,775
2,237,837
How to return different classes from one function?
I have a question, though it is not limited to C++. How to return totally different class from one function? f() { in case one: return A; in case two: return B; in case three: return C; } For example, I have two balls in the space, according to the position and the size, there are three situations for the two balls to intersect with each other, i.e, non-intersection, at point, a and circle. How can I return different class in one function? Thanks.
If you can afford Boost then this sounds like a perfect application for Boost.Variant. struct NoIntersection { // empty }; struct Point { // whatever }; struct Circle { // whatever }; typedef boost::variant<NoIntersection, Point, Circle> IntersectionResult; IntersectionResult intersection_test() { if(some_condition){ return NoIntersection(); } if(other_condition){ return Point(x, y); } if(another_condition){ return Circle(c, r); } throw std::runtime_error("unexpected"); } You then process your result with a static visitor: struct process_result_visitor : public boost::static_visitor<> { void operator()(NoIntersection) { std::cout << "there was no intersection\n"; } void operator()(Point const &pnt) { std::cout << "there was a point intersection\n"; } void operator()(Circle const &circle) { std::cout << "there was a circle intersection\n"; } }; IntersectionResult result = intersection_test(); boost::apply_visitor(process_result_visitor(), result); EDIT: The visitor class must derive from boost::static_visitor UPDATE: Prompted by some critical comments I've written a little benchmark program. Four approaches are compared: boost::variant union class hierarchy boost::any These are the results in my home computer, when I compile in release mode with default optimizations (VC08): test with boost::variant took 0.011 microseconds test with union took 0.012 microseconds test with hierarchy took 0.227 microseconds test with boost::any took 0.188 microseconds Using boost::variant is faster than a union and leads (IMO) to the most elegant code. I'd guess that the extremely poor performance of the class hierarchy approach is due to the need to use dynamic memory allocations and dynamic dispatch. boost::any is neither fast nor especially elegant so I wouldn't consider it for this task (it has other applications though)
2,237,980
2,237,998
How do I convert a char* to an int?
I need to convert a char* to an integer. For example: data.SetBytFldPos(*attribute->value()); The value in the attribute class is a char*. 'SetBytFldPos" takes an int.
Lots of ways. Simplest is to use the strtol() function.
2,238,166
2,238,463
What is the difference between asio::tcp::socket's async_read_some and async_receive?
What is the difference between: boost::asio::tcp::socket::async_read_some() boost::asio::tcp::socket::async_receive() As far as I can tell their documentation is identical. Which should I prefer?
Their specification in the networking TR2 proposal (5.7.10.2 basic_stream_socket members) is identical too: On async_receive: Effects: Calls this->service.async_receive(this->implementation, buffers, 0, handler). On async_read_some: Effects: Calls this->service.async_receive(this->implementation, buffers, 0, handler). So I guess this confirms Jerry's impression.
2,238,170
2,244,824
Forward declaration of nested enum
I have code similar to the following: class B { } class A { enum { EOne, ETwo } EMyEnum; B myB; } I want to declare a member of type EMyEnum in class B (which is declared before A). Is this possible? I realise the solution is to declare class B second, but for clarity I would prefer not to.
It's not possible... but it can be faked with inheritance abuse :) namespace detail { class A_EMyEnum { public: enum { EOne, ETwo } EMyEnum; protected: A_EMyEnum() {} A_EMyEnum(const A_EMyEnum&) {} A_EMyEnum& operator=(const A_EMyEnum&) { return *this; } ~A_EMyEnum() {} }; // class A_EMyEnum } // namespace detail class B { // use detail::A_EMyEnum }; class A: public detail::A_EMyEnum { B mB; }; On the other hand... why don't you simply forward declare B ? class B; class A { public: enum EMyEnum {}; A(); A(const A&); A& operator=(const A&); ~A(); void swap(A&); private: B* mB; }; class B { // use A::EMyEnum }; Sure you need to actually write all the normally "default generated" methods of A, but hey that does not cost so much!
2,238,224
2,239,157
String and character mapping question for the guru's out there
Here's a problem thats got me stumped (solution wise): Given a str S, apply character mappings Cm = {a=(m,o,p),d=(q,u),...} and print out all possible combinations using C or C++. The string can be any length, and the number of character mappings varies, and there won't be any mappings that map to another map (thus avoiding circular dependencies). As an example: string abba with mappings a=(e,o), d=(g,h), b=(i) would print: abba,ebba,obba,abbe,abbo,ebbe,ebbo,obbe,obbo,aiba,aiia,abia,eiba,eiia,......
Definitely possible, not really difficult... but this will generate lots of strings that's for sure. The first thing to remark is that you know how many strings it's going to generate beforehand, so it's easy to do some sanity check :) The second: it sounds like a recursive solution would be easy (like many traversal problems). class CharacterMapper { public: CharacterMapper(): mGenerated(), mMapped() { for (int i = -128, max = 128; i != max; ++i) mMapped[i].push_back(i); // 'a' is mapped to 'a' by default } void addMapped(char origin, char target) { std::string& m = mMapped[origin]; if (m.find(target) == std::string::npos) m.push_back(target); } // addMapped void addMapped(char origin, const std::string& target) { for (size_t i = 0, max = target.size(); i != max; ++i) this->addMapped(origin, target[i]); } // addMapped void execute(const std::string& original) { mGenerated.clear(); this->next(original, 0); this->sanityCheck(original); this->print(original); } private: void next(std::string original, size_t index) { if (index == original.size()) { mGenerated.push_back(original); } else { const std::string& m = mMapped[original[index]]; for (size_t i = 0, max = m.size(); i != max; ++i) this->next( original.substr(0, index) + m[i] + original.substr(index+1), index+1 ); } } // next void sanityCheck(const std::string& original) { size_t total = 1; for (size_t i = 0, max = original.size(); i != max; ++i) total *= mMapped[original[i]].size(); if (total != mGenerated.size()) std::cout << "Failure: should have found " << total << " words, found " << mGenerated.size() << std::endl; } void print(const std::string& original) const { typedef std::map<char, std::string>::const_iterator map_iterator; typedef std::vector<std::string>::const_iterator vector_iterator; std::cout << "Original: " << original << "\n"; std::cout << "Mapped: {"; for (map_iterator it = mMapped.begin(), end = mMapped.end(); it != end; ++it) if (it->second.size() > 1) std::cout << "'" << it->first << "': '" << it->second.substr(1) << "'"; std::cout << "}\n"; std::cout << "Generated:\n"; for (vector_iterator it = mGenerated.begin(), end = mGenerated.end(); it != end; ++it) std::cout << " " << *it << "\n"; } std::vector<std::string> mGenerated; std::map<char, std::string> mMapped; }; // class CharacterMapper int main(int argc, char* argv[]) { CharacterMapper mapper; mapper.addMapped('a', "eo"); mapper.addMapped('d', "gh"); mapper.addMapped('b', "i"); mapper.execute("abba"); } And here is the output: Original: abba Mapped: {'a': 'eo''b': 'i''d': 'gh'} Generated: abba abbe abbo abia abie abio aiba aibe aibo aiia aiie aiio ebba ebbe ebbo ebia ebie ebio eiba eibe eibo eiia eiie eiio obba obbe obbo obia obie obio oiba oibe oibo oiia oiie oiio Yeah, rather lengthy, but there's a lot that does not directly participate to the computation (initialization, checks, printing). The core methods is next which implements the recursion.
2,238,241
2,238,434
Is it possible to use COM visible .NET classes with registration free COM?
We're developing a ClickOnce application with a mixture of .NET components and legacy C++ COM components. Currently we're adding the C++ COM components to the user's machine using an MSI (this is a prerequisite to installing our ClickOnce app) which means we can register the COM objects on the user's machine beforehand. We can still push out updates to the rest of the application written in C# via ClickOnce, but updating the components installed by the MSI requires manual intervention. However, we are trying to figure out if it is possible to install the C++ COM components via registration free COM, i.e. they're all in the same directory, and each component has a manifest file specifying the clsid for each COM object and interface. This would mean we can get rid of the MSI entirely. This link has been a good introduction to the topic. I've been able to get a .NET component to load a C++ COM object, but not the other way around. Does anyone know if this is possible?
Yes, that's possible. You'll need to use the <clrClass> element in the manifest. There's a decent how-to located here. The SDK docs are otherwise pretty miserable, you'll need Junfeng Zhang's blog to get better background info.
2,238,456
2,238,533
How does C's "extern" work?
I have a C/C++ program that's a plugin to Firefox. Because it's a plugin, it has non-main entry points. Those entrypoints need to be compiled in C because otherwise they get name mangled.However, other functions are over-loaded, so they need to be C++. The solution is extern "C". That much I've already figured out. However, if I extern "C" around the .c file, I get link errors because the C++ files got name mangled, but the calls in the .c file didn't. At least I THINK that's what's happening. The solution APPEARS to be to put the extern "C" around the .h file. This SEEMS to mean that the names of the functions declared in the .h file aren't mangled, even when they're defined in the (presumably mangled) .c file. However, it doesn't really make any sense to me why this would work. Is this a kludge? Am I setting myself up for a hard to find bug later? or is this the right way to solve this?
Extern "C" should apply to function prototype, so if you have separate prototype and implementation, put extern declaration around prototypes. Implementation, provided prototype is visible, will be extern as well and not mangled. It is not a bug.
2,238,639
2,238,702
why does MS C++ add this code to assembly?
i have some code(inline assembly). void NativeLoop() { int m; __asm { PUSH ECX PUSH EDX MOV ECX, 100000000 NEXTLOOP: MOV EDX, ECX AND EDX, 0X7FFFFFFF MOV DWORD PTR m, EDX DEC ECX JNZ NEXTLOOP POP EDX POP ECX } } MS C++ Automagicaly adds these codes(marked with **) to my procedure. Why? how to avoid it? **push ebp **mov ebp,esp **push ecx push ecx push edx mov ecx,5F5E100h NEXTLOOP: mov edx,ecx and edx,7FFFFFFFh mov dword ptr m,edx dec ecx jnz NEXTLOOP pop edx pop ecx **mov esp,ebp **pop ebp **ret
It is the standard function entry and exit code. It establishes and tears down the stack frame. If you don't want it you can use __declspec(naked). Don't forget to include the RET if you do. However, your snippet relies on a valid stack frame, your "m" variable requires it. It is addressed at [ebp-10]. Without the preamble, the ebp register won't be set correctly and you'll corrupt the stack frame of the caller.
2,238,840
2,238,853
C++, #ifdef question
Not coding in C++ right now but a question came up when I have a question in C#. Hope experts here can easily give a anwser. Class A{ #ifdef AFlag public void methodA(){...} #endif } Class B{ ... A a; a.methodA(); ... } Class C { ... A a; a.methodA(); ... } If the AFlag is NOT defined anywhere, what will happen? A compile error or no error but the methodA AND those statements calling that method will not be compiled? thanks
There will be a compile error.
2,238,896
2,238,957
C++ templated typedef
I have a templated class template <T> class Example { ... }; inside which there are many methods of the following type: template <class U> <class V> method(....) Inside these I use tr1::shared_ptr to U or V or T. Its tedious typing tr1::shared_ptr<const U> or tr1::shared_ptr<const V>. The obvious thing to do: template <typename U> typedef tr1::shared_ptr<U> shptr<U>; does not work. What do you do in this situation? Anything that can reduce verbosity?
You can use an inner type: template <typename U> struct sptr { typedef tr1::shared_ptr<U> t; }; Then say sptr<U>::t, or unfortunately often typename sptr<U>::t. C++0x has template typedefs, you could check whether your compiler can be persuaded to accept them: template<typename U> using sptr = tr1::shared_ptr<U>; Then say sptr<U> And of course there's always #define sptr ::tr1::shared_ptr, for example if you're expecting C++0x in future and want to bridge the gap. Or if you're using it in a narrow enough context that a macro isn't scary.
2,239,380
2,239,401
what does the operator string() { some code } do?
I have the following code in a class: operator string() { return format("CN(%d)", _fd); } And wanted to know what this operator does. I am familiar with the usual string operators: bool operator==(const string& c1, const string& c2); bool operator!=(const string& c1, const string& c2); bool operator<(const string& c1, const string& c2); bool operator>(const string& c1, const string& c2); bool operator<=(const string& c1, const string& c2); bool operator>=(const string& c1, const string& c2); string operator+(const string& s1, const string& s2 ); string operator+(const Char* s, const string& s2 ); string operator+( Char c, const string& s2 ); string operator+( const string& s1, const Char* s ); string operator+( const string& s1, Char c ); string& operator+=(const string& append); string& operator+=(const Char* append); string& operator+=(const Char append); ostream& operator<<( ostream& os, const string& s ); istream& operator>>( istream& is, string& s ); string& operator=( const string& s ); string& operator=( const Char* s ); string& operator=( Char ch ); Char& operator[]( size_type index ); const Char& operator[]( size_type index ) const; ... but not this one?
operator Type() { ... } is the (implicit) conversion operator. For example, if class Animal implements operator string(), then the code Animal a; ... do_something_with ( (string)a ); will become something like do_something_with ( (Animal::operator string)(&a) ); See http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/cplr385.htm for some more examples.
2,239,389
2,239,649
How can I implement Google Maps-like tile scrolling in Qt?
I'm using Qt/C++ and trying to draw a large and complex QGraphicsScene. Once I add a lot of objects, panning and zooming become unpleasantly slow. (No surprise here, of course). I've played with device coordinate caching (helps with panning to a point) and minimal viewport updates and so on, but eventually there's just too many objects. What I'd like to do is draw the items asynchronously from controlling the UI somehow. In other words, just like Google Maps does, I want to pan and zoom and let drawing catch up as fast as it's able, but to be able to pan again before the items finish drawing. One method I'm trying is to create two QGraphicsScenes. One has the actual objects but is not attached to a QGraphicsView. The other QGraphicsScene is connected to the QGraphicsView, but it just has some tiled QPixmaps that are sized to cover the screen. The plan is to use spare CPU cycles to update any tile pixmap that needs it. This seems like it will give me the necessary control over rendering (so I don't have to block while re-rendering the entire visible scene). Thoughts? Has anyone implemented this?
Take a look here: Generating content in threads. It sounds like this is similar to what you are trying to do. Tile mechanisms are very common ways to load in large amounts of data. Other than the link posted, I have not seen a simple example using QGraphicsView. 40000 Chips also shows some things about managing large amounts of data.
2,239,519
2,239,571
Is there a way to specify how many characters of a string to print out using printf()?
Is there a way to specify how many characters of a string to print out (similar to decimal places in ints)? printf ("Here are the first 8 chars: %s\n", "A string that is more than 8 chars"); Would like it to print: Here are the first 8 chars: A string
The basic way is: printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars"); The other, often more useful, way is: printf ("Here are the first %d chars: %.*s\n", 8, 8, "A string that is more than 8 chars"); Here, you specify the length as an int argument to printf(), which treats the '*' in the format as a request to get the length from an argument. You can also use the notation: printf ("Here are the first 8 chars: %*.*s\n", 8, 8, "A string that is more than 8 chars"); This is also analogous to the "%8.8s" notation, but again allows you to specify the minimum and maximum lengths at runtime - more realistically in a scenario like: printf("Data: %*.*s Other info: %d\n", minlen, maxlen, string, info); The POSIX specification for printf() defines these mechanisms.
2,239,591
2,239,807
How to capture CTRL + CTRL key presses in my Win32 application?
How would I capture the user pressing Ctrl twice (Ctrl + Ctrl) globally. I want to be able to have my application window hidden and then make it visible when the user invokes it with the CtrlCtrl key presses similar to Google Quick Search Box. The user may have focus on a different window. I've looked at RegisterHotKey, but that seems to be for MODIFIERS + character key unless I'm mistaken.
To create such a hotkey, do this: ATOM hotkey = GlobalAddAtom("Your hotkey atom name"); if(hotkey) RegisterHotKey(hwnd, hotkey, MOD_CONTROL, VK_CONTROL); else { ...error... } And then handle the WM_HOTKEY message: case WM_HOTKEY: if(wParam == hotkey) { // CTRL pressed!!! } break; I guess you'll figure out yourself that you need to store whether the CTRL key was pressed before. For example, if it was pressed once in the last 500 ms, and the user presses it again, you have a CTRL+CTRL press.
2,239,607
2,239,770
Can a recursive function write to a file in C++?
I'm going to have two class functions. The first class function opens the file. Then it calls a second function that writes to the file and recursively calls itself. When the second function finishes, the original function closes the file. Is it possible to do this?
Sure, as long as you pass the file handle/object to the recursive function: void recursion(int data, int maxdepth, ostream &os) { // must eventually break out if (maxdepth == 0) return; // write data os << data << std::endl; // and call one deeper recursion(data + 1, maxdepth - 1, os); } void start(const char *filename) { std::ofstream os(filename); recursion(0, 100, os); }
2,239,730
2,239,787
Compiling C++ for MacOSX 10.5 and 10.6
I have a reasonably simple C++ program that I can successfully compile on OSX 10.6 using: g++ -O3 -funroll-loops -I /usr/local/include/boost-1_39/ myfile.cpp -o build/myfile However, a user on OSX 10.5 gets the error: dyld: unknown required load command A support forum post suggests adding -isysroot /Developer/SDKs/MacOSX10.5.sdk -mmacosx-version-min=10.5 However adding this seems to mess with my include paths and gives me tons of errors. Is there an easy way to compile a binary that will work on OSX 10.5 and 10.6?
This questions has been solved, I believe, using the suggested command.
2,239,872
2,239,945
How to get list of folders in this folder?
How to get list of folders in this folder?
If you can't use .NET & Managed code, you can go through the win32 api's Here is an example that you can modify to only get Folders. (Basically the following check:) ... TCHAR szDir = _T("c:\\"); // or wherever. HANDLE hFind = FindFirstFile(szDir, &ffd); ... do { if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { // your code on 'ffd' } } while (FindNextFile(hFind, &ffd) != 0);
2,239,952
2,247,090
VS2008 attaching a debugger (C++) to handle assert(...)
There are two scenarios that I'm interested to improve in my assert. 1) a debug build app is started regularly, if there is an assertion I'm getting "Debug assertion failed" dialog box with "Abort", "Retry", "Ignore". Abort and Ignore answers are working fine. The problem with Retry. If I hit retry I'm getting that useless "Application error, breakpoint has been reached" "OK" - to terminate, "Cancel" - to debug the program. Is it possible to avoid this dialog and go directly to the "Just in time debugger" dialog that shows choices for debuggers? I understand that the "Application error" dialog box is triggered by __debugbreak() or _asm int 3 on intel, so after "Retry" was pressed I need to attach debugger without using _asm int 3. Is this possible? I couldn't find any WinAPI that does this 2) A debug build app is started in VS debugger (using F5). If an assert is triggered I don't want to see any dialog, I want it to stop right on the assert. I managed to install crt debug runtime hooks and if IsDebuggerPresent then I __debugbreak() and it stops on the line of the assert. It works perfectly when I'm debugging windows mobile builds, but I'm still getting a dialog box for Win32 builds: "APP.exe has triggered a breakpoint", "Break", "Continue", and greyed out "Ignore". Any way to completely disable it?
Take a look at the registry entry HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug. I think that if you set Auto to 1, that the debugger is automatically started. And of course changing the assert implementation can also help you (take a look at the SuperAssert of John Robbins from his famous Debugging Windows Applications book).
2,240,083
2,240,105
versions of C++ standard library
What are difference between The GNU C++ Library (libstdc++), "C++ Standard Library", "Standard Template Library" and "SGI STL". When programming in Linux with compiler GCC and programming in Windos in MSVC (MicroSoft Visual C++), which the standard C++ libraries are using by default? Thanks!
C++ standard library - the generic definition of what functionality / behavior must be provided by the library (strings, pairs, iostream, containers, algorithms, etc. although the specifics vary depending on the version of the C++ standard). Standard Template Library (STL) - the part of the C++ standard library that has to do with containers and algorithms (and the iterators that bring those two together). The STL was not part of the original C++ library. libstdc++ - a specific implementation of the C++ standard library. SGI STL - a specific implementation of the STL part of the C++ standard library. I believe this was also one of the first versions of the STL. Before the STL became part of the C++ library, developers had to download the STL separately (the same way we currently do with Boost).
2,240,094
2,240,128
Initializing a Char*[]
Question is in the title, how do I initialize a char*[] and give values to it in C++, thank you.
Though you're probably aware, char*[] is an array of pointers to characters, and I would guess you want to store a number of strings. Initializing an array of such pointers is as simple as: char ** array = new char *[SIZE]; ...or if you're allocating memory on the stack: char * array[SIZE]; You would then probably want to fill the array with a loop such as: for(unsigned int i = 0; i < SIZE; i++){ // str is likely to be an array of characters array[i] = str; } As noted in the comments for this answer, if you're allocating the array with new (dynamic allocation) remember to delete your array with: delete[] array;
2,240,227
2,240,248
Detecting whether cookies are enabled through IWebBrowser2 Interface
Is it possible to detect whether cookies are enabled in Internet Explorer through the IWebBrowser2 Interface or through some other WebBrowser Control C/C++ interface? I can't see any obvious way to do it, but was wondering whether there is a subtle way.
You can pass the URL to InternetGetPerSiteCookieDecision() and it should tell you what the policy is for that site. It is a pretty terribly named API. :-/
2,240,269
2,240,965
Writing XML strips trailing spaces
I am trying to write an XML file using MSXML4. It works fine except when I have a data element with a trailing space which must be preserved. Given the following code to insert a new element: const _bstr_t k_Parent (ToBSTR("ParentNode")); const _bstr_t k_Child (ToBSTR("ChildNode")); const _bstr_t k_Data (ToBSTR("DataWithTrailingSpace ")); const _bstr_t k_Namespace (ToBSTR("TheNameSpace")); MSXML2::IXMLDOMDocument2Ptr m_pXmlDoc; m_pXmlDoc->async = VARIANT_FALSE; m_pXmlDoc->validateOnParse = VARIANT_FALSE; m_pXmlDoc->resolveExternals = VARIANT_FALSE; m_pXmlDoc->preserveWhiteSpace = VARIANT_TRUE; MSXML2::IXMLDOMNodePtr pElement = m_pXmlDoc->createNode(NODE_ELEMENT, k_Child, k_Namespace); MSXML2::IXMLDOMNodePtr pParent = m_pXmlDoc->selectSingleNode(k_Parent); pElement->put_text (k_Data); MSXML2::IXMLDOMNodePtr pNewChild = pParent->appendChild(pElement); If I check "pNewChild->text", the text still contains the trailing space. When I try writing it to a file: std::string xml (static_cast<std::string>(m_pXmlDoc->xml)); std::ofstream file("output.xml"); file << xml << std::endl; file.flush(); file.close(); The output is: <ParentNode> <ChildNode>DataWithTrailingSpace</ChildNode> </ParentNode> Instead of (note the extra space behind "DataWithTrailingSpace"): <ParentNode> <ChildNode>DataWithTrailingSpace </ChildNode> </ParentNode> I cannot figure out at what point the trailing space is getting stripped. Can someone please provide some insights in to where this may be occurring and how I can correct it?
Mystery solved. Don't preview your XML in Internet Explorer. It hides trailing spaces. Use notepad instead.
2,240,289
2,240,659
Need transparent overlay window to draw lines on top of window drawing video? ::MFC,C++,windows::
How do you create a transparent window that can be placed over another window that is actively having streaming video drawn to it. I want to create a window on top of the video window that I can draw on without video constantly drawing back over it. I can create a window from a transparent dialog resource and set its z-order using SetWindowPos(...) but it doesn't seem to have any effect. Having the dialog set as a WS_CHILD style or WS_POPUP also appears to have no effect. I'm using a media (video) framework another development group in my company developed and am providing a window handle to that code. That handle is being used by their rendering plugin in the pipeline that uses Direct3d for rendering the video on that window surface.
Video is rendered to a hardware overlay in the video adapter. You'll need to create your own to overlay that overlay. I think DirectX provides that capability, you can also get it by using the WS_EX_LAYERED window style and the SetLayeredWindowAttributes(). Which you'll need to set the transparency key. Not so sure that's a slam-dunk btw, I've seen this behave oddly.
2,240,405
2,240,457
byte array assignment
byte test[4]; memset(test,0x00,4); test[]={0xb4,0xaf,0x98,0x1a}; the above code is giving me an error expected primary-expression before ']' token. can anyone tell me whats wrong with this type of assignment?
What Ben and Chris are saying is. byte test[4]={0xb4,0xaf,0x98,0x1a}; If you want to do it at run time, you can use memcpy to do the job. byte startState[4]={0xb4,0xaf,0x98,0x1a}; byte test[4]; memcpy(test, startState, sizeof(test));
2,240,620
2,240,691
C++ Template class using STL container and a typedef
I have a class looking like this: #include <vector> #include "record.h" #include "sortcalls.h" template< typename T, template<typename , typename Allocator = std::allocator<T> > class Cont = std::vector> class Sort: public SortCall { This code is working and I'm calling it like this from other classes: Comparator c; // comparison functor Sort< Record, std::vector > s(c); Now I want to be able to switch the containers to another container, say a list. So I thought a typedef would be neat. It should be something like typedef std::vector<Record> container; // Default record container template< typename T, template< typename, typename container > // ??? class Sort: public SortCall {
Don't use template template parameters (Cont in your code), they are brittle and inflexible. Use a rebind mechanism if you need to (std::allocator is an example), but you don't in this case: template<class T, class Cont=std::vector<T> > struct Sort { typedef Cont container_type; // if you need to access it from outside the class // similar to std::vector::value_type (which you might want to add here too) }; typedef Sort<int, std::list<int> > IntListSort; Compare to std::queue and std::stack, which also follow this pattern.
2,240,669
2,241,001
Virtual inheritance bug in MSVC
It seems that my problem is a bug in MSVC. I'm using the Visual Studio 2008 with Service Pack 1, and my code works with GCC (as tested on codepad.org). Any official info on this bug? Any ideas how to work around it? Is the bug fixed in VS2010? All insights would be greatly appreciated. The code: struct Base { Base(int i = 0) : i(i) {} virtual ~Base() {} virtual Base *clone() const = 0; protected: int i; }; struct A : virtual public Base { A() {} virtual A *clone() const = 0; }; struct B : public A { B() {} B *clone() const { return new B(*this); } /// MSVC debugger shows that 'b' is for some reason missing the Base /// portion of it's object ("Error: expression cannot be evaluated") /// and trying to access 'b.i' causes an unhandled exception. /// /// Note: This only seems to occur with MSVC B(const B &b) : Base(b.i), A() {} }; void foo(const A &elem) { A *a = elem.clone(); if (a) delete a; } int main() { A *a = new B; foo(*a); delete a; }
It looks as though the compiler is not correctly adjusting the this pointer when calling through A::clone. If you remove the declaration of A::clone then everything works fine. Digging in deeper, when you have A::clone, the vtable looks like this: [0x0] 0x002f1136 [thunk]:B::`vector deleting destructor'`vtordisp{4294967292,0}' (unsigned int) void * [0x1] 0x002f11e0 [thunk]:B::clone`vtordisp{4294967292,0}' (void) void * [0x2] 0x002f12ad [thunk]:B::clone`vtordisp{4294967292,4}' (void) void * [0x3] 0x002f12a3 B::clone(void) void * And foo calls elem.__vfptr[2], offsetting this incorrectly by -4 bytes. Without A::clone, the vtable looks like this: [0x0] 0x00ee1136 [thunk]:B::`vector deleting destructor'`vtordisp{4294967292,0}' (unsigned int) void * [0x1] 0x00ee11e0 [thunk]:B::clone`vtordisp{4294967292,0}' (void) void * [0x2] 0x00ee12a3 B::clone(void) void * And foo calls elem.__vfptr[1]. That does not adjust this at all (and the code assumes that this will be equal to Base instead of B). So it looks like the compiler assumes that A::clone is a new virtual method and doesn't override Base::clone when determining whether A requires a new virtual table, but then some other code later determines that A does not need a virtual table. You can verify this by comparing sizeof(B) with or without a new virtual function: struct A : virtual public Base { A() {} virtual A *clone() const = 0; }; //sizeof(B)==16 struct A : virtual public Base { A() {} virtual A *clone() const = 0; virtual const A *clone2() const { return this; } }; //sizeof(B)==20 So it's a compiler bug.
2,240,773
2,240,780
Compiling error: Function Parameters using Object References are Confused by Constructed Objects
In the unit test of a class, I try to declare a class variable by calling explicitly the empty constructor and pass it to a function that excepts a reference to the interface of the type I'm declaring, but the compiler produces error. When I just declare it without any explicit constructor call the function accepts it. See the code below: //classundertest.h class IController; class CClassUnderTest { public: CClassUnderTest() {} virtual ~CClassUnderTest() {} unsigned int Run(IController & controller); }; //testclassundertest.h #include "UnitTest++.h" #include "classundertest.h" #include "icontroller.h" class CTestController : public IController { public: CTestController() : IController() {} virtual ~CTestController() {} virtual void Play(unsigned int i) {} }; struct CClassUnderTestFixture { CClassUnderTest classUnderTest; }; TEST_FIXTURE(CClassUnderTestFixture, RunTest) { CTestController controllerA; CHECK_EQUAL(classUnderTest.Run(controllerA), 105U); CTestController controllerB(); CHECK_EQUAL(classUnderTest.Run(controllerB), 105U); } The compiler believes controllerB is the reference of the constructor: error: no matching function for call to `CClassUnderTest::Run(CTestController (&)())' error: candidates are: unsigned int CClassUnderTest::Run(IController&) I'm confused by why the compiler won't allow me to call the constructor when instantiating controllerB, especially when the production code seems okay with this?
This line: CTestController controllerB(); is the declaration of a function that takes nothing and returns a CTestController. For default construction, you must simply leave off the parenthesis. This is related to something called the "most vexing parse". Consider: struct S {}; int main() { S s(S()); // copy construct a default-constructed S ...? } This doesn't work. This declares s as a function that takes a pointer to a function that takes nothing and returns an S, that returns an S. To fix this, you can use an extra set of parenthesis: struct S {}; int main() { S s((S())); // copy construct a default-constructed S :) }
2,240,947
2,241,095
Can i call shell command and output of this save to string on Windows?
In other words something like pipe in windows
The boilerplate code is in this MSDN Library article.
2,241,089
2,241,330
Alpha/texturing issues in an OpenGL wrapper
I'm in the process of writing a wrapper for some OpenGL functions. The goal is to wrap the context used by the game Neverwinter Nights, in order to apply post-processing shader effects. After learning OpenGL (this is my first attempt to use it) and much playing with DLLs and redirection, I have a somewhat working system. However, when the post-processing fullscreen quad is active, all texturing and transparency drawn by the game are lost. This shouldn't be possible, because all my functions take effect after the game has completely finished its own rendering. The code does not use renderbuffers or framebuffers (both refused to compile on my system in any way, with or with GLEW or GLee, despite being supported and usable by other programs). Eventually, I put together this code to handle copying the texture from the buffer and rendering a fullscreen quad: extern "C" SEND BOOL WINAPI hook_wglSwapLayerBuffers(HDC h, UINT v) { if ( frameCount > 250 ) { frameCount++; if ( frameCount == 750 ) frameCount = 0; if ( nwshader->thisframe == NULL ) { createTextures(); } glBindTexture(GL_TEXTURE_2D, nwshader->thisframe); glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 0, 0, nwshader->width, nwshader->height, 0); glClearColor(0.0f, 0.5f, 0.0f, 0.5f); glClear(GL_COLOR_BUFFER_BIT); glEnable(GL_TEXTURE_2D); glDisable(GL_DEPTH_TEST); glBlendFunc(GL_ONE, GL_ZERO); glEnable(GL_BLEND); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho( 0, nwshader->width , nwshader->height , 0, -1, 1 ); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glBegin(GL_POLYGON); glTexCoord2f(0.0f, 1.0f); glVertex2d(0, 0); glTexCoord2f(0.0f, 0.0f); glVertex2d(0, nwshader->height); glTexCoord2f(1.0f, 0.0f); glVertex2d(nwshader->width, nwshader->height); glTexCoord2f(1.0f, 1.0f); glVertex2d(nwshader->width, 0); glEnd(); glMatrixMode( GL_PROJECTION ); glPopMatrix(); glMatrixMode( GL_MODELVIEW ); glPopMatrix(); glEnable(GL_DEPTH_TEST); glDisable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); } else { frameCount++; } if ( h == grabbedDevice ) { Log->logline("Swapping buffer on cached device."); } return wglSwapLayerBuffers(h,v); } This code functions almost functions perfectly and has no notable slow-down. However, when it is active (I added the frameCount condition to turn it on and off every ~5 seconds), all alpha and texturing are completely ignored by the game renderer. I'm not turning off any kind of blending or texturing before this function (the only OpenGL calls are to create the nwshader->thisframe texture). I was able to catch a few screenshots of what's happening: Broken A: http://i4.photobucket.com/albums/y145/peachykeen000/outside_brokenA.png Broken B: http://i4.photobucket.com/albums/y145/peachykeen000/outside_brokenB.png (note, in B, the smoke in the back is not broken, it is correctly transparent. So is the HUD.) Broken Interior: http://i4.photobucket.com/albums/y145/peachykeen000/transparency_broken.png Correct Interior (for comparison): http://i4.photobucket.com/albums/y145/peachykeen000/transparency_proper.png The drawing of the quad also breaks menus, turning the whole thing into a black surface with a single white box. I suspect it is a problem with either depth or how the game is drawing certain objects, or a state that is not being reset properly. I've used GLintercept to dump a full log of all calls in a frame, and didn't see anything wrong (the call to wglSwapLayerBuffers is always last). Being brand new to working with OpenGL, I really have no clue what's going wrong (or how to fix it) and nothing I've tried has helped. What am I missing?
I don't quite understand how your code is supposed to integrate with the Neverwinter Nights code. However... It seems like you're most likely changing some setting that the existing code didn't expect to change. Based on the description of the problem, I'd try removing the following line: glDisable(GL_TEXTURE_2D); That line disables textures, which certainly sounds like the problem you're seeing.
2,241,166
2,241,320
C or C++ for OpenGL graphics
there is any drawback in choose C++ and an object oriented model (classes) to implement a simulation in OpenGL (or DirectX)? It's preferred to use C and a procedural programming paradigm ?
The most common drawback of object oriented programming in the context of high performance graphics (games etc.) is the memory bottleneck. OOP often (but not necessarily) leads to writing functions that operate on single elements and leveraging the standard library to generalize these to arrays. It might be preferable to operate on arrays in the first place, for example cull against all six frustum planes instead of calling the single plane culling routine six times. Check out the following resources for more details: Pitfalls of OOP The Latency Elephant Data-Oriented Design (Or Why You Might Be Shooting Yourself in The Foot With OOP) Memory Optimization C++ Programming is Bullshit Note that using C++ does not imply strict object oriented programming, you can use it for many paradigms. So if you code your engine in C++, you can still leverage all existing OOP style libraries such as Qt, while using any paradigm you like for the core. Although all of this is also possible in C, C++ might be a bit more comfortable.
2,241,327
2,241,444
How do I pass a C++11 random number generator to a function?
Do they all inherit from a base class? Do I have to use templates? (I am referring to these http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c15319/) I am doing this right now: typedef std::mt19937 RNG; and then class Chooser { public: Chooser(RNG& rng, uint n, uint min_choices, uint max_choices): In other words, I'm passing references to RNG. How would I pass in an arbitrary generator? Also, I realize this is maybe a different question, but how do I pass the generator to STL? std::random_shuffle(choices_.begin(), choices_.end(), rng); doesn't seem to work. solution to passing generator: typedef std::ranlux64_base_01 RNG; typedef std::mt19937 RNGInt; solution to passing to STL: struct STL_RNG { STL_RNG(RNGInt& rng): gen(rng) {} RNGInt& gen; int operator()(int n) { return std::uniform_int<int>(0, n)(gen); } };
They don't all inherit from a base (which is a little surprising), but it doesn't matter because that's not how C++ functors work. For arbitrary RNGs of a single given type, you got it right as (now) posted. If you mean, how do I define a function which accepts any random number generator as an argument. template< class RNG > // RNG may be a functor object of any type int random_even_number( RNG &gen ) { return (int) gen() * 2; } You don't need to use any more templates than this, because of type deduction. Defining one function to accept different RNG's is trickier because semantically that requires having a common base type. You need to define a base type. struct RNGBase { virtual int operator() = 0; virtual ~RNGBase() {}; }; template< class RNG > struct SmartRNG : RNGBase { RNG gen; virtual int operator() { return gen(); } }; int random_even_number( RNGBase &gen ) { // no template return (int) gen() * 2; // virtual dispatch }
2,241,475
2,241,778
Strange runtime error, seemly microsoft related
I am using the debug_new tool that come in the pack of tools NVWA made by Wu Yongwei. http://wyw.dcweb.cn/ I turned it off once to track a heisenbug, that now is fixed. But as I turned it on, my program throws a bizarre error: It loads, but before accepting any input it quits and writes on the console: "This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information Process returned 3 (0x3) execution time : 0.828s" How I debug that? I have no idea what on the code is throwing the error (since when using a debugger it still quits the same way, and the debugger reports no errors with exit of the debugger being 0) EDIT for those that don't read tags: I am using C++, compiling with MingW on Windows.
If you're running under the Visual Studio debugger, go to the Debug/Exceptions menu and check the box for the "C++ Exceptions" item - this will cause the debugger to break whenever an exception is thrown. You might need to fiddle with the various sub-options (std:exception, void, etc) for the exception types if your code throws a lot of exceptions that it catches and you're not interested in breaking into the debugger when they get thrown.
2,241,699
2,241,728
Is shallow copy sufficient for structures with char[]?
I have a structure containing character arrays with no any other member functions. I am doing assignment operation between two instances of these structures. If I'm not mistaken, it is doing shallow copy. Is shallow copy safe in this case? I've tried this in C++ and it worked but I would just like to confirm if this behavior is safe.
If by "shallow copy", you mean that after assignment of a struct containing an array, the array would point to the original struct's data, then: it can't. Each element of the array has to be copied over to the new struct. "Shallow copy" comes into the picture if your struct has pointers. If it doesn't, you can't do a shallow copy. When you assign a struct containing an array to some value, it cannot do a shallow copy, since that would mean assigning to an array, which is illegal. So the only copy you get is a deep copy. Consider: #include <stdio.h> struct data { char message[6]; }; int main(void) { struct data d1 = { "Hello" }; struct data d2 = d1; /* struct assignment, (almost) equivalent to memcpy(&d2, &d1, sizeof d2) */ /* Note that it's illegal to say d2.message = d1.message */ d2.message[0] = 'h'; printf("%s\n", d1.message); printf("%s\n", d2.message); return 0; } The above will print: Hello hello If, on the other hand, your struct had a pointer, struct assignment will only copy pointers, which is "shallow copy": #include <stdio.h> #include <stdlib.h> #include <string.h> struct data { char *message; }; int main(void) { struct data d1, d2; char *str = malloc(6); if (str == NULL) { return 1; } strcpy(str, "Hello"); d1.message = str; d2 = d1; d2.message[0] = 'h'; printf("%s\n", d1.message); printf("%s\n", d2.message); free(str); return 0; } The above will print: hello hello In general, given struct T d1, d2;, d2 = d1; is equivalent to memcpy(&d2, &d1, sizeof d2);, but if the struct has padding, that may or may not be copied. Edit: In C, you can't assign to arrays. Given: int data[10] = { 0 }; int data_copy[10]; data_copy = data; is illegal. So, as I said above, if you have an array in a struct, assigning to the struct has to copy the data element-wise in the array. You don't get shallow copy in this case: it doesn't make any sense to apply the term "shallow copy" to a case like this.
2,241,786
2,241,832
Is it safe to pass (synchronously) stack-allocated memory to other thread?
Recently I heard that memory in the stack is not shared with other thread and memory in the heap is shared with other threads. I normally do: HWND otherThreadHwnd; DWORD commandId; // initialize commandId and otherThreadHwnd struct MyData { int data1_; long data2_; void* chunk_; }; int abc() { MyData myData; // initialize myData SendMessage(otherThreadHwnd,commandId,&myData); // read myData } Is it alright to do this?
I think 2 different issues are being confused by whoever you "heard that memory in the stack is not shared with other thread": object lifetime - the data on the stack is only valid as long the thread doesn't leave the scope of the variable's name. In the example you giove, you're handling this by making the call to the other thread synchronously. memory address visibility - the addresses pspace for a process is shared among the various threads in that process. So variables addressable by one thread are addressable by other threads in that process. If you are passing the address to a thread in a different process, the situation is quite different and you'd need to use some other mechanism (which might be to ensure that the memory block is mapped into both processes - but that I don't think that can normally be done with stack memory).
2,241,808
2,241,818
Checking if a folder exists (and creating folders) in Qt, C++
In Qt, how do I check if a given folder exists in the current directory? If it doesn't exist, how do I then create an empty folder?
To check if a directory named "Folder" exists use: QDir("Folder").exists(); To create a new folder named "MyFolder" use: QDir().mkdir("MyFolder");
2,241,821
2,365,229
Qt 4.6 - How to drag and drop into a QGraphicsView in QtCreator?
I've been trying to figure out how to drag and drop an image into a QGraphicsView using Qt and the QtCreator IDE. I have read the documentation here: http://doc.trolltech.com/4.6/qgraphicsscene.html#dragEnterEvent This documentation is too general for me to understand. Can anyone give me an example that works? I also found a post about the same thing on StackOverflow here: Implementing drag and drop with QT 4.5 using QT Creator environment I figured out where this 'Promote' function is but I am still confused on how exactly I "promote" this QGraphicsView to drag and drop. Any help would be greatly appreciated. Thanks in advance!
DragAndDrop: DragEnterEvent is to be overridden (in code) on a QWidget of your choice. Look at some basic code examples in QtAssistant on how to drag and drop. QGraphicsView is a type-of QWidget. Promotions: Lets say you designed a class X that inherits from QGraphicsView. While you are in QtCreator, you can add a QGraphicsView to your widget/form, and then use the promote system to basically do this: "when you see a QGraphicsView here, replace it with the class I'm going to provide". When you look at Object Inspector view in QtCreator or QtDesigner, you should see your class instead of more generic QGraphicsView. (when you promote it) Hope this helps,
2,241,834
2,241,876
Why is my char* writable and sometimes read only in C++
I have had really big problems understand the char* lately. Let's say I made a recursive function to revert a char* but depending on how I initialize it I get some access violations, and in my C++ primer I didn't find anything giving me the right path to understand so I am seeking your help. CASE 1 First case where I got access violation when trying to swap letters around: char * bob = "hello"; CASE 2 Then I tried this to get it work char * bob = new char[5]; bob[0] = 'h'; bob[1] = 'e'; bob[2] = 'l'; bob[3] = 'l'; bob[4] = 'o'; CASE 3 But then when I did a cout I got some random crap at the end so I changed it for char * bob = new char[6]; bob[0] = 'h'; bob[1] = 'e'; bob[2] = 'l'; bob[3] = 'l'; bob[4] = 'o'; bob[5] = '\0'; CASE 4 That worked so I told myself why wouldn't this work then char * bob = new char[6]; bob = "hello\0"; CASE 5 and it failed, I have also read somewhere that you could do something like char* bob[]; Then add something to that. My question is why do some fail and other not, and what is the best way to do it?
The key is that some of these pointers are pointing at allocated memory (which is read/write) and some of them are pointing at string constants. String constants are stored in a different location than the allocated memory, and can't be changed. Well most of the time. Often vulnerabilities in systems are the result of code or constants being changed, but that is another story. In any case, the key is the use of the new keyword, this is allocating space in read/write memory and thus you can change that memory. This statement is wrong char * bob = new char[6]; bob = "hello\0"; because you are changing the pointer not copying the data. What you want is this: char * bob = new char[6]; strcpy(bob,"hello"); or strncpy(bob,"hello",6); You don't need the nul here because a string constant "hello" will have the null placed by the compiler.
2,241,835
2,241,884
C++ How come I can't assign a base class to a child class?
I have code like this: class Base { public: void operator = (const Base& base_) { } }; class Child : public Base { public: }; void func() { const Base base; Child child; child = base; } My question is: since Child derives from Base (hence it should inherit Base's operator= ), how come when the statement child = base; is executed, I get a compiler error like this: >.\main.cpp(78) : error C2679: binary '=' : no operator found which takes a right-hand operand of type 'const Base' (or there is no acceptable conversion) 1> .\main.cpp(69): could be 'Child &Child::operator =(const Child &)' 1> while trying to match the argument list '(Child, const Base)' The behavior that I want is for the Child class to recognize that it's being assigned a Base class, and just "automatically" call the its parent's operator=. Once I added this code to the Child class void operator = (const Base& base_) { Base::operator=(base_); } then everything compiled fine. Though I dont think this would be good because if I have like 5 different classes that inherit from Base, then I have to repeat the same code in every single derived class. NOTE: My intention for copying the Base to Child is to simply copying the members that are common to both Base and Child (which would be all the members of Base). Even after reading all of the answers below, I really don't see why C++ doesn't allow one to do this, especially if there's an explicit operator= defined in the Base class.
The standard provides the reason for your specific question in 12.8/10 "Copying class objects" (emphasis added): Because a copy assignment operator is implicitly declared for a class if not declared by the user, a base class copy assignment operator is always hidden by the copy assignment operator of a derived class (13.5.3). So since there's an implicitly declared operator=(const Child&) when the compiler is performing the name lookup/overload resolution for a Child::operator=(), the Base class's function signature is never even considered (it's hidden).
2,241,897
2,241,923
What does the C++ language standard say about how static_cast handles reducing the size of an integer?
I would like to know the rules specified by the C++ language standard for situations like: long x = 200; short y = static_cast<short>(x); Is y guaranteed to be 200, or does the standard leave this up to the implementation to decide? How well do various compilers adhere to the standard?
In this case the static_cast<> is an 'explicit type conversion. the standard has this to say about integral conversions in 4.7/3 "Integral conversions": If the destination type is signed, the value is unchanged if it can be represented in the destination type (and bit-field width); otherwise, the value is implementation-defined. Since short is guaranteed to be able to hold the value 200 (short must be at least 16 bits), then for your specific example the answer is yes. Various compilers adhere to this behavior quite well - it's been that way since the pre-ANSI days of C, and so much code depends on the behavior that compiler vendors seem reluctant to even issue warnings about the possibility of truncation.
2,241,944
2,241,987
'class X' has no member 'Y'
This error is inexplicably occurring. Here is the code and output: timer.cpp: #include "timer.h" #include "SDL.h" #include "SDL_timer.h" void cTimer::recordCurrentTime() { this->previous_t = this->current_t; this->current_t = SDL_GetTicks(); } timer.h: #include "SDL.h" #include "SDL_timer.h" class cTimer { private: int previous_t; int current_t; float delta_time; float accumulated_time; int frame_counter; public: void recordCurrentTime(); float getDelta(); void incrementAccumulator(); void decrementAccumulator(); bool isAccumulatorReady(); void incrementFrameCounter(); void resetFrameCounter(); int getFPS(); }; Compiler errors: make g++ -Wall -I/usr/local/include/SDL -c timer.cpp timer.cpp: In member function ‘void cTimer::recordCurrentTime()’: timer.cpp:6: error: ‘class cTimer’ has no member named ‘previous_t’ timer.cpp:6: error: ‘class cTimer’ has no member named ‘current_t’ timer.cpp:7: error: ‘class cTimer’ has no member named ‘current_t’ make: *** [timer.o] Error 1 Compiler errors after removing the #include "timer.h" g++ -Wall -I/usr/local/include/SDL -c ctimer.cpp ctimer.cpp:4: error: ‘cTimer’ has not been declared ctimer.cpp: In function ‘void recordCurrentTime()’: ctimer.cpp:5: error: invalid use of ‘this’ in non-member function ctimer.cpp:5: error: invalid use of ‘this’ in non-member function ctimer.cpp:6: error: invalid use of ‘this’ in non-member function make: *** [ctimer.o] Error 1
Works for me. Are you sure you've got the right timer.h? Try this: cat timer.h and verify that it's what you think it is. If so, try adding ^__^ at the beginning of your .h file and seeing if you get a syntax error. It should look something like this: [/tmp]> g++ -Wall -I/tmp/foo -c timer.cpp In file included from timer.cpp:1: timer.h:1: error: expected unqualified-id before ‘^’ token
2,241,949
2,241,963
Why does my C++ code fail to delete all nodes in my BST?
This is supposed to traverse a BST and delete every node, including the root node. However, at the end, I get the message "root still has a left node." Why aren't all nodes deleted? void deleteTree() { deleteNode(root); if(root->right) cout << "root still has a right node" << endl; if(root->left) cout << "root still has a left node" << endl; root = 0; } void deleteNode(node *p) { if(p->left) { deleteNode(p->left); p->left = 0; } if(p->right) { deleteNode(p->right); p->right = 0; } cout << "Deleting node containing " << p->data << endl; delete p; }
Your are deleting p at the end (root) and then trying to access its contents in deleteTree(), where root no longer points to allocated memory. The result is going to be undefined.
2,242,057
2,242,070
Using 'virtual' in derived class
I saw code in a derived class recently in which the programmer put virtual in front of the functions overridden. Is this common? I thought it was very odd and it kind of caught me off guard. Edit: I'm not asking what virtual does, I'm asking why someone would put virtual in a derived class that is already overriding virtual functions in its base class. EX: class B { public: virtual void foo(); .... }; class D : public B { public: virtual void foo(); // could have just put void foo(); ... };
virtual is needed for overrideable functions at the highest (least derived) level. It is optional, but harmless at lower (more derived) levels. It's good for self-documenting the code.
2,242,097
2,242,129
How to print out a BST in C++
My C++ program creates a binary search tree. I know how to print out the values in pre-order, post-order, and in-order. However, I want to do something a little more difficult. I want to print out the values the way they would look if someone drew the tree on paper. It would have the root at the center at the top, it's left child right under and to the left of it, and it's right child right under and to the right of it. The rest of the nodes would be drawn accordingly. How can I do that?
This article contains code for what you need, it seems: alt text http://www.cpp-programming.net/wp-content/uploads/2007/12/ascii_tree.jpg Edit: that site went offline Here's another one exploring some other options.
2,242,370
2,242,382
How to convert these lines of c code to c++
I'm trying to import some c code into my c++ program. There are three lines that don't import directly: The first: free(t); The second: new_node = (Tree *) malloc (sizeof (Tree)); The third: Tree * delete(int value, Tree * t) How can these be changed to work in C++?
The first two lines should be valid C++, assuming you've included stdlib.h, and have defined Tree as a class/struct/type somewhere. The third line will need to be changed, since 'delete' is a keyword in C++ and can't be used as a function name. Try doing a global replace in the C code and changing all instances of 'delete' with 'delete_from_tree' or something like that.
2,242,593
2,242,600
When comparing for equality is it okay to use `==`?
When comparing for equality is it okay to use ==? For example: int a = 3; int b = 4; If checking for equality should you use: if (a == b) { . . . } Would the situation change if floating point numbers were used?
'==' is perfectly good for integer values. You should not compare floats for equality; use an tolerance approach: if (fabs(a - b) < tolerance) { // a and b are equal to within tolerance }
2,242,619
2,242,694
Testing for Type Equality without RTTI
Say B and C are derived from A. I want to be able to test whether any two instances of classes derived from A are instances of the same class, that is, whether A* foo and A* bar both point to B instances, without using RTTI. My current solution is something like this: class A { protected: typedef uintptr_t Code; virtual Code code() const = 0; }; // class A class B : public A { protected: virtual Code code() const { return Code(&identity); } private: static int identity; }; // class B class C : public A { protected: virtual Code code() const { return Code(&identity); } private: static int identity; }; // class C Using this method, operator== can simply test first.code() == second.code(). I'd like to remove the literal identity from the derived classes and have the code found automatically by A, so that not all of the derived classes have to repeat this idiom. Again, I would strongly prefer not to use RTTI. Is there any way to do this? Note: I have seen recent questions [1] and [2], and this is not a duplicate. Those posters want to test the contents of their derived classes; I merely want to test the identities.
You should just use RTTI instead of reinventing the wheel. If you insist on not using RTTI, you could use CRTP and a function-local static variable to avoid having to write the function to every derived class. Adapt from this example code I wrote for Wikipedia: http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern#Polymorphic_copy_construction Another alternative is reading the vtable pointer (via this and pointer arithmetics), but that would depend on both the compiler and the platform, so it is not portable.
2,242,687
2,243,577
Help streaming over http in C++
I'm looking to use a web service that offers a streaming api. This api can typically be used by the java method java.net.URL.openStream(); Problem is I am trying to design my program in C++ and have no idea what libraries (I've heard the cUrl library is very good at this sort of thing) to use, or how to use them to do what I want. The idea is that after opening the file as a stream I can access continually updating data in realtime. Any help would be much appreciated.
Boost.Asio socket iostreams seem to be what you're after. Your code will look like this: ip::tcp::iostream stream("www.someserver.com", "http"); if (!stream) { // Can't connect. } // Use stream as a regular C++ input stream: std::string text; std::getline(stream, text); If you're new to C++ and have no experience with iostreams then this page is an excellent source of information. In particular, check the docs of the istream class to see what kind of operations your Boost.ASIO stream will support. You'll find that they're not so different from those in the Java IO API. EDIT: Eric is right, you'll have to send some requests to the server (using the same stream) so it's probably less similar to Java's openStream than I thought. The following example shows how to make those requests: http://blog.think-async.com/2007_01_01_archive.html
2,242,696
2,242,769
C structure and C++ structure
Could anybody please tell me what is the main difference between C & C++ structures.
In C++ struct and class are the exact same thing, except for that struct defaults to public visibility and class defaults to private visiblity. In C, struct names are in their own namespace, so if you have struct Foo {};, you need to write struct Foo foo; to create a variable of that type, while in C++ you can write just Foo foo;, albeit the C style is also permitted. C programmers usually use typedef struct {} Foo; to allow the C++ syntax for variable definitions. The C programming language also does not support visibility restrictions, member functions or inheritance.
2,242,774
2,242,778
converting c style string to c++ style string
Can anyone please tell me how to convert a C style string (i.e a char* ) to a c++ style string (i.e. std::string) in a C++ program? Thanks a lot.
std::string can take a char * as a constructor parameter, and via a number of operators. char * mystr = "asdf"; std::string mycppstr(mystr); or for the language lawyers const char * mystr = "asdf"; std::string mycppstr(mystr);
2,242,821
2,242,828
STL compilation error when defining iterator within template class
The code below gives the error: error: type ‘std::list<T,std::allocator<_Tp1> >’ is not derived from type ‘Foo<T>’ error: expected ‘;’ before ‘iter’ #include <list> template <class T> class Foo { public: std::list<T>::iterator iter; private: std::list<T> elements; }; Why and what should this be to be correct?
You need typename std::list<T>::iterator. This is because list depends on the template parameter, so the compiler cannot know what exactly is the name iterator within it going to be (well, technically it could know, but the C++ standard doesn't work that way). The keyword typename tells the compiler that what follows is a name of a type.
2,242,838
2,242,896
regarding file i/o in c++
I have a part of a code that does the following: It reads in sentences from a file in a particular format, puts them in a vector. To probe whether the strings in the vector are stored correctly, I put debugging cout statements. I found that the last string member member of the vector is "". Why is this so? The file I am reading from ends with the last floating point value (that is stored in weight in each iteration). There is no whitespace or \n after that. I am pasting that part of the code in the form of a separate program below. #include <iostream> #include <stdio.h> #include <string> #include <vector> using namespace std; int dist=0; void stringtolower(char *s) { int i=0; char c; while(s[i]!='\0') { c=s[i]; c=tolower(c); s[i]=c; i++; } } void cleanup(char *s) { int i=0; dist=0; while(*(s+i)=='\r' || *(s+i)=='\n' || *(s+i)=='\t') { dist++; i++; } while(*(s+i)!='\0'){ /*if(*(s+i)=='"' || *(s+i)=='`' || *(s+i)=='\'' || *(s+i)=='.') *(s+i)=' ';*/ if(*(s+i)==':' || *(s+i)=='\t' || *(s+i)=='\n' || *(s+i)=='\r' || *(s+i)=='"' || *(s+i)=='`' ){ *(s+i)='\0'; break; } i++; } return; } int isinlist(vector<string> sents, char *s){ for(int i=0;i<sents.size();i++){ if(!sents[i].compare(s)){ return 1; } } return 0; } int main() { char *s=NULL; FILE *fp; fp=fopen("1.txt","r"); size_t len=0; ssize_t read; vector<string> sents; float weight; while(!feof(fp)) { read=getdelim(&s,&len,':',fp); cleanup(s); s=s+dist; fscanf(fp,"%f",&weight); if(isinlist(sents,s)){ continue; } stringtolower(s); string str(s); //sentences.push(str); // Push sentence into FIFO queue for later processing sents.push_back(str); } for(int i=0;i<sents.size();i++) { cout<<sents[i]<<endl; } } Thanks a lot for your help.
Because you are not handling end of file (eof) correctly. You can only tell that you've reached the eof when you've tried to read beyond the end of the file. Consider the case of a 0 length file. When that happens, this will be the case. FILE *fp = fopen(..., "r"); assert(!feof(fp)); // guaranteed, even if the file is 0 length That is, even though there is no more data, feof will not return true until it actually tries to read the next byte. What you need to do is detect end of file during reading. For example: FILE *fp = fopen(..., "r"); char buffer[SIZE]; while (fgets(buffer, sizeof(buffer), fp) != NULL) { // got some data, do something with it. } // fgets returned NULL, now let's check if it was because // we got to the eof or had an error if (feof(fp)) // got to the end else // got an error If getdelim is written properly, it should return an indicator when it has reached end-of-file. There are two different ways it may be written: It only returns indicator provided it hasn't already read any data when it reaches EOF It always returns indicator when it reaches EOF. If the former, you want to structure your code like: while (getdelim(&s,&len,':',fp) != GET_DELIM_EOF_VALUE) If the latter, you will need something like: while ((getdelim(&s,&len,':',fp) != GET_DELIMI_EOF_VALUE) || (len != 0))