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
3,159,395
3,159,629
Why symbols of a shared library are not resolved at link time?
This is my 2nd post on this site in my effort to understand the compilation/linking process with gcc. When I try to make an executable, symbols need to be resolved at link time, but when I try to make a shared library, symbols are not resolved at link time of this library. They will perhaps be resolved when I am trying to make an executable using this shared library. Hands-on: bash$ cat printhello.c #include <stdio.h> //#include "look.h" void PrintHello() { look(); printf("Hello World\n"); } bash$ cat printbye.c #include <stdio.h> //#include "look.h" void PrintBye() { look(); printf("Bye bye\n"); } bash$ cat look.h void look(); bash$ cat look.c #include <stdio.h> void look() { printf("Looking\n"); } bash$ gcc printhello.c printbye.c /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../crt1.o: In function `_start': (.text+0x18): undefined reference to `main' /tmp/cck21S0u.o: In function `PrintHello': printhello.c:(.text+0x7): undefined reference to `look' /tmp/ccNWbCnd.o: In function `PrintBye': printbye.c:(.text+0x7): undefined reference to `look' collect2: ld returned 1 exit status bash$ gcc -Wall -shared -o libgreet printhello.c printbye.c printhello.c: In function 'PrintHello': printhello.c:6: warning: implicit declaration of function 'look' printbye.c: In function 'PrintBye': printbye.c:5: warning: implicit declaration of function 'look' So my question is why are symbols not resolved when I am linking a shared library. This work(Resolving symbols of its downstream) will need to be done when I will use this library to make an executable, but that means we need to know what this library depends on when using this library, but isn't it not undesirable? Thanks, Jagrati
Does adding -z defs when building the library do what you want? If not, check the ld man pages, there are quite a few options on the handling of undefined symbols.
3,159,396
3,159,539
is there a good way to combine stream manipulators?
If I wanted to output a fixed width hex number with 4 digits on a stream, I would need to do something like this: cout << "0x" << hex << setw(4) << setfill('0') << 0xABC; which seems a bit long winded. Using a macro helps: #define HEX(n) "0x" << hex << setw(n) << setfill('0') cout << HEX(4) << 0xABC; Is there a better way to combine the manipulators?
Avoid the macros when you can! They hide code, making things hard to debug, don't respect scope, etc. You can use a simple function as KenE provided. If you want to get all fancy and flexible, then you can write your own manipulator: #include <iostream> #include <iomanip> using namespace std; ostream& hex4(ostream& out) { return out << "0x" << hex << setw(4) << setfill('0'); } int main() { cout << hex4 << 123 << endl; } This makes it a little more general. The reason the function above can be used is because operator<< is already overloaded like this: ostream& operator<<(ostream&, ostream& (*funtion_ptr)(ostream&)). endl and some other manipulators are also implemented like this. If you want to allow the number of digits to be specified at runtime, we can use a class: #include <iostream> #include <iomanip> using namespace std; struct formatted_hex { unsigned int n; explicit formatted_hex(unsigned int in): n(in) {} }; ostream& operator<<(ostream& out, const formatted_hex& fh) { return out << "0x" << hex << setw(fh.n) << setfill('0'); } int main() { cout << formatted_hex(4) << 123 << endl; } If the size can be determined at compile-time, however, might as well just use a function template [thanks to Jon Purdy for this suggestion]: template <unsigned int N> ostream& formatted_hex(ostream& out) { return out << "0x" << hex << setw(N) << setfill('0'); } int main() { cout << formatted_hex<4> << 123 << endl; }
3,159,470
3,159,504
cin.get() is not getting out of loop
I am using the following code: #include <stdio.h> #include <iostream> using namespace std; int main () { char c ; c = cin.get() ; do { cout.put(c) ; c = cin.get() ; } while ( !cin.eof()) ; cout << "coming out!" << endl; return 0; } Problem with the above code is, its not getting out of loop, which means its not printing "coming out". Anybody can help why it is so? I am testing this program on mac and linux. Thanks
Standard in never hits EOF, unless you press Ctrl+Z. Therefore, cin.eof() is always false. To fix it, press Ctrl+Z to send an End-Of-File character. Alternatively, you could change the condition. (eg, while(c != '\n'))
3,159,754
3,159,784
Sort C++ Strings with multiple criteria
I need to sort a C++ std::vector<std::string> fileNames. The fileNames are labeled as such YYDDDTTTT_Z_SITE YY = Year (i.e 2009 = 09, 2010 = 10) DDD = Day of the year (i.e 1 January = 001, 31 December = 365) TTTT = Time of the day (i.e midnight = 0000, noon = 1200) ZONE = Will be either E or W SITE = Four letter site name (i.e HILL, SAMM) I need the strings to be sorted by the following order: ZONE, SITE, YY, DDD, TTTT
Use std::sort with a comparison function. (The link has a nice example)
3,159,936
3,159,961
Calculate Execution TIme using C++, rather than using <time.h>
I need to calculate the execution time of a C++ program. I am currently using the c-style head, <time.h> with the following code: clock_t tStart = clock(); ... printf("Execution Time: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC); Is there a c++ header I can use to calculate execution time? Please note this needs to be cross-platform compatible.
You can use the C++ versions of C headers. Add 'c' at the beginning, and remove '.h' So you need #include <ctime> The rest stays the same, as you can just use the C approach.
3,160,403
3,160,851
"pure virtual method called" when implementing a boost::thread wrapper interface
I have a small wrapper which centralize what's relative to threads : class Thread { protected: boost::thread *m_thread; virtual void work() = 0; void do_work() { work(); } public: Thread() : m_thread(NULL) {} virtual ~Thread() { catch_up(); delete m_thread; } inline void catch_up() { if(m_thread != NULL) { m_thread->join(); } } void run() { m_thread = new boost::thread(boost::bind(&Thread::do_work, boost::ref(*this))); } }; When I implement it, say with the following : class A : public Thread { void work() {} }; At : A a; a.run(); I got a runtime termination with a pretty "pure virtual method called" displayed. I think it's the boost::bind argument, but I don't know how to say "Use virtual pure implementation"... Thanks aforehand. Regards, Mister Mystère
Your crash happens only when your program exits immediately: it calls class A's destructor which finishes and calls Thread's destructor before the newly started thread had a chance to be scheduled. The thread then calls your virtual function, but class A no longer exists, so it attemps to call Thread's do_work(), which calls the pure virtual work(). Here's your program with extra outputs: run() started run() ended ~A() started ~A() ended ~Thread() started catch_up() started do_work() started pure virtual method called Standard-wise, I think this is undefined behavior because the object's lifetime has already ended (destructor call began) when a reference to it (boost::ref(*this)) was used to call do_work() from the thread. Solution: let your thread execute before you destruct your object: A a; a.run(); a.catch_up(); Or, as boost.thread documentation says, "the user of Boost.Thread must ensure that the referred-to object outlives the newly-created thread of execution."
3,160,483
3,160,494
"Bitwise And" and Left-Padding in C++
I have a macro that looks something like this: Foo(x) ((x - '!') & 070) If I call the following code: Foo('1') => 16 However, if I call the following code: (('1' - '!') & 70) => 0 So my question is, what's going on here? Why does x & 070 compute to x but x & 70 compute to 0? My guess is that the extra 0 on the left is forcing 60 to take 2 bytes instead of 1. In that case, wouldn't the bitwise & be as follows? 0000 0000 0001 0000 '16 0000 0000 0100 0110 & '70 ------------------- 0000 0000 0000 0000
In C++, a constant with a leading 0 is an octal constant, not a decimal constant. It is still an integer constant but 070 == 56. This is the cause of the difference in behaviour.
3,160,491
3,160,569
iPhone Radio program with VU Meter
I wrote an iPhone app that plays wma stream, using libmms and ffmpeg open source libraries. The app has already been approved by Apple and is available for download, free of charge. Now I'd like to have a VU meter on my app. I'm using the avTouch code sample, downloaded from Apple (https://developer.apple.com/iphone/library/samplecode/avTouch/Introduction/Intro.html). I just can't figure out how to mix cpp and objc. When I put the avTouchViewController and avTouchController in the Document (command+o) at Interface Builder, and simply try to build and run the program, it crashes just after the Default image. What am I missing? What should I do to correct this problem? Or, even better, does anyone have a code sample that I could use to have a VU meter on my app? Thanks for your attention!
To use Objective-C++ you will need to (the simplest way) ensure your source file name ends in ".mm" instead of ".m". If the latter, the compiler guesses it's just Objective-C, if the former it assumes Objective-C++. You can explicitly set the compiler flags in the build settings, but why when you can just rename the file? :) Once the compiler knows what's in the source file you're trying to compile, you should be well on your way.
3,160,584
3,160,626
Will GetPath() work for this?
I basically want to get the outline for a character. I was wondering how I could do this without drawing to the DC. Could I do something like this: (Psudocodeishly) BeginPath() TextOut("H") EndPath() GetPath() Will something like this work for GetPath? Will it return the glyph outline that I can then draw? Otherwise, how else could I do this (without freetype) Thanks
If you want to get a glyph outline, why not just use GetGlyphOutline? There's the theoretical limitation that this is limited to TrueType fonts, but given the percentage of other fonts typically used on Windows, that's rarely a concern... Edit: Yes, if you want to avoid using GetGlyphOutline, using a path instead will work (though only with TrueType fonts, not bitmapped fonts). The sample code included with the documentation for CDC::BeginPath shows how to do exactly what you seem to be after (though I'd strongly recommend using std::vector instead of new[] and delete[] as it does). One minor detail: that sample includes an implementation of PolyDraw. You'd only need (or want) this if you need to support ancient 16-bit versions of Windows -- all NT-based versions of Windows include it.
3,160,653
3,160,830
what could make 32 bit app incompatible with 64 bit linux OS?
It seems that most 32 bit applications will run on 64 bit linux assuming all the 32 bit libraries are present. But it seems to me there could be issues with architecture-dependent functions, and here I'm thinking of signals and setjmp/longjmp. I'm wondering if someone with greater experience could comment on what functions (if any) would cause a 32 bit app to be incompatible with a 64 bit OS.
Even setjmp and longjmp should work correctly. There are no particular issues, from a user space application, which would present any issues. The actual 32bit emulation is done by the processor. System calls are the interface back to the 64bit kernel, which Linux correctly handles. If the application was evil, and sent executable code to another 64bit process to execute, then various things would break.
3,160,882
3,160,962
This is illegal right?
For a personal project I have been implementing my own libstdc++. Bit by bit, I've been making some nice progress. Usually, I will use examples from http://www.cplusplus.com/reference/ for some basic test cases to make sure that I have the obvious functionality working as expected. Today I ran into an issue with std::basic_string::replace, specifically with the iterator based versions using the example copied verbatim from the site (http://www.cplusplus.com/reference/string/string/replace/) (I've added a comment to point out the lines in question): // replacing in a string #include <iostream> #include <string> using namespace std; int main () { string base="this is a test string."; string str2="n example"; string str3="sample phrase"; string str4="useful."; // function versions used in the same order as described above: // Using positions: 0123456789*123456789*12345 string str=base; // "this is a test string." str.replace(9,5,str2); // "this is an example string." str.replace(19,6,str3,7,6); // "this is an example phrase." str.replace(8,10,"just all",6); // "this is just a phrase." str.replace(8,6,"a short"); // "this is a short phrase." str.replace(22,1,3,'!'); // "this is a short phrase!!!" // Using iterators: 0123456789*123456789* string::iterator it = str.begin(); // ^ str.replace(it,str.end()-3,str3); // "sample phrase!!!" // *** this next line and most that follow are illegal right? *** str.replace(it,it+6,"replace it",7); // "replace phrase!!!" it+=8; // ^ str.replace(it,it+6,"is cool"); // "replace is cool!!!" str.replace(it+4,str.end()-4,4,'o'); // "replace is cooool!!!" it+=3; // ^ str.replace(it,str.end(),str4.begin(),str4.end()); // "replace is useful." cout << str << endl; return 0; } In my version of replace is implemented in terms of a temporary string which I create then swap with *this. This clearly invalidates any iterators. So am I correct that the example is invalid? because it stores iterators, does a replace and then uses the iterators again? My copy of the standard (ISO 14882:2003 - 21.3p5) says: References, pointers, and iterators referring to the elements of a basic_string sequence may be invalidated by the following uses of that basic_string object: - As an argument to non-member functions swap() (21.3.7.8), operator>>() (21.3.7.9), and getline() (21.3.7.9). - As an argument to basic_string::swap(). - Calling data() and c_str() member functions. - Calling non-const member functions, except operator[](), at(), begin(), rbegin(), end(), and rend(). - Subsequent to any of the above uses except the forms of insert() and erase() which return iterators, the first call to non-const member functions operator[](), at(), begin(), rbegin(), end(), or rend(). The entry about non-const member functions seems to cover this. So unless I am missing something, then this code is using invalidated iterators right? Of course this code works just fine with gcc's libstdc++, but we all know that proves nothing as far as standards compliance.
This will appear to work if replace operates in-place. I don't think it's required to be implemented that way though. So yes, I would say your code is technically illegal.
3,160,975
3,161,128
VS: Tooltip help for doxygen-style commented functions?
I am using Visual Studio and an external library that is commented in doxygen-style. Is there any way to display doxygen documentation in the editor tooltip like DocXML?
The VS plugin Visual Assist shows doxygen comments. From what I can see, it doesn't actually process them, but it shows doxygen comments (in their raw form) nevertheless. There's a trial at their website. Be warned, though. I have seen very few C++ programmers who tried it for a few days and were not begging their managers to buy it for them afterwards.
3,161,271
3,161,284
Why should I avoid using malloc in c++?
Possible Duplicates: What is the difference between new/delete and malloc/free? In what cases do I use malloc vs new? Why should I avoid using malloc in c++?
Because malloc does not call the constructor of newly allocated objects. Consider: class Foo { public: Foo() { /* some non-trivial construction process */ } void Bar() { /* does something on Foo's instance variables */ } }; // Creates an array big enough to hold 42 Foo instances, then calls the // constructor on each. Foo* foo = new Foo[42]; foo[0].Bar(); // This will work. // Creates an array big enough to hold 42 Foo instances, but does not call // the constructor for each instance. Foo* foo = (Foo*)malloc(42 * sizeof(Foo)); foo[0].Bar(); // This will not work!
3,161,342
3,161,374
serialize any data type as vector<uint8_t> - use reinterpret_cast?
I didnt find anything directly related in searching, so please forgive if this is a duplicate. What I am looking to do is serialize data across a network connection. My approach is to convert everything I need to transfer to a std::vector< uint8_t > and on the receiving side unpack the data into the appropriate variables. My approach looks like this: template <typename T> inline void pack (std::vector< uint8_t >& dst, T& data) { uint8_t * src = static_cast < uint8_t* >(static_cast < void * >(&data)); dst.insert (dst.end (), src, src + sizeof (T)); } template <typename T> inline void unpack (vector <uint8_t >& src, int index, T& data) { copy (&src[index], &src[index + sizeof (T)], &data); } Which I'm using like vector< uint8_t > buffer; uint32_t foo = 103, bar = 443; pack (buff, foo); pack (buff, bar); // And on the receive side uint32_t a = 0, b = 0; size_t offset = 0; unpack (buffer, offset, a); offset += sizeof (a); unpack (buffer, offset, b); My concern is the uint8_t * src = static_cast < uint8_t* >(static_cast < void * >(&data)); line (which I understand to do the same as reinterpret_cast). Is there a better way to accomplish this without the double cast? My naive approach was to just use static_cast< uint8_t* >(&data) which failed. I've been told in the past that reinterpret_cast is bad. So I'd like to avoid it (or the construct I have currently) if possible. Of course, there is always uint8_t * src = (uint8_t *)(&data). Suggestions?
My suggestion is to ignore all the people telling you that reinterpret_cast is bad. They tell you it is bad, because it's generally not a good practice to take the memory map of one type and pretend that it's another type. But in this case, that is exactly what you want to do, as your entire purpose is to transmit the memory map as a series of bytes. It is far better than using a double-static_cast, as it fully details the fact that you are taking one type and purposefully pretending that it is something else. This situation is exactly what reinterpret_cast is for, and dodging using it with a void pointer intermediary is simply obscuring your meaning with no benefit. Also, I'm sure that you're aware of this, but watch for pointers in T.
3,161,392
3,163,749
Different ways of observing data changes
In my application I have many classes. Most of these classes store quite some data, and it is important that other modules in my application are also 'updated' if the content of one of the data classes changes. The typical way to do this is like this: void MyDataClass::setMember(double d) { m_member = d; notifyAllObservers(); } This is a quite good method if the member is not often changed and the 'observing classes' need to be up-to-date as fast as possible. Another way of observing the changes is this: void MyDataClass::setMember(double d) { setDirty(); m_member = d; } This is a good method if the member is changed many times, and the 'observing classes' look at regular intervals at all 'dirty' instances. Unfortunately, I have a mix of both kinds of data members in my classes. Some are changed not that often (and I can live with normal observers), others are changed many many times (this is within complex mathematical algorithms) and calling the observers everytime the value changes will kill the performance of my application. Are there any other tricks of observing data changes, or patterns in which you can easily combine several different methods of observing data changes? Although this is a rather language-independent question (and I can try to understand examples in other languages), the final solution should work in C++.
The two methods you've described cover (conceptually) both aspects, however I think you haven't explained sufficiently their pros and cons. There is one item that you should be aware of, it's the population factor. Push method is great when there are many notifiers and few observers Pull method is great when there are few notifiers and many observers If you have many notifiers and your observer is supposed to iterate over every of them to discover the 2 or 3 that are dirty... it won't work. On the other hand, if you have many observers and at each update you need to notify all of them, then you're probably doomed because simply iterating through all of them is going to kill your performance. There is one possibility that you have not talked about however: combining the two approaches, with another level of indirection. Push every change to a GlobalObserver Have each observer check for the GlobalObserver when required It's not that easy though, because each observer need to remember when was the last time it checked, to be notified only on the changes it has not observed yet. The usual trick is to use epochs. Epoch 0 Epoch 1 Epoch 2 event1 event2 ... ... ... Each observer remembers the next epoch it needs to read (when an observer subscribes it is given the current epoch in return), and reads from this epoch up to the current one to know of all the events. Generally the current epoch cannot be accessed by a notifier, you can for example decide to switch epoch each time a read request arrives (if the current epoch is not empty). The difficulty here is to know when to discard epochs (when they are no longer needed). This requires reference counting of some sort. Remember that the GlobalObserver is the one returning the current epochs to objects. So we introduce a counter for each epoch, which simply counts how many observers have not observed this epoch (and the subsequent ones) yet. On subscribing, we return the epoch number and increment the counter of this epoch On polling, we decrement the counter of the epoch polled and return the current epoch number and increment its counter On unsubscribing, we decrement the counter of the epoch --> make sure that the destructor unsubscribes! It's also possible to combine this with a timeout, registering the last time we modified the epoch (ie creation of the next) and deciding that after a certain amount of time we can discard it (in which case we reclaim the counter and add it to the next epoch). Note that the scheme scales to multithread, since one epoch is accessible for writing (push operation on a stack) and the others are read-only (except for an atomic counter). It's possible to use lock-free operations to push on a stack at the condition that no memory need be allocated. It's perfectly sane to decide to switch epoch when the stack is complete.
3,161,407
3,161,444
Compare and swap library?
What is the best cross platform library to use for atomic compare and swap operations in c++? ...Or at least for amd64 on Linux and Windows?
It depends on the compiler compatibility you need. If you are using GCC on both platforms, you can just use GCC's atomic primitives, as they are tied to the hardware architecture, not the OS platform. Otherwise, as PeterK suggested, look at Boost. There is a Boost.Atomic candidate library; I don't know what its status on being incorporated is.
3,161,435
3,161,476
Communication with running Windows service
How can I communicate with running Windows service without stopping it using native C++? I need to pass integers and strings to service and get integers and to get back integers and strings. Currently I do it through registry, but I would like use another, faster way. Thank you in advance.
A few options: Communicate via ports Use RPC Use the file system
3,161,676
3,161,703
Why is it counting the last number twice?
My program is reading numbers from a file- and it reads the last number twice. What is wrong with my program and what can I do to fix it? int main() { ifstream inputFile; int number = 0; //the input for the numbers in the file double total = 0; //the total of the numbers double counter = 0;//number of numbers double average = 0;//average of the number inputFile.open("random.txt");//open file if (!inputFile)//test for file open errors { cout<<"Error \n"; } while (inputFile) { inputFile >> number ; total+=number; counter++; cout<<"The running total is: " <<total <<"\n"; } total=total*1.00; counter=counter*1.00; average = total/counter; cout<<"\nthe final total is: \t" <<total; cout<<"\nthe number of numbers is: \t"; cout<<counter; cout<<"\nthe average of the numbers is: \t"; cout<<setprecision(8)<< fixed<< average<<"\n"; inputFile.close(); return 0; } the contents of the file: 42 468 335 501 170 725 479 359 963 465 706 146 282 828 962 492 996 943 828 437 392 605 903 154 293 383 422 717 719 896 448 727 772 539 870 913 668 300 36 895 704 812 323 334 674 665 142 712 254 869 548 645 663 758 38 860 724 742 530 779 317 36 191 843 289 107 41 943 265 649 447 806 891 730 371 351 7 102 394 549 630 624 85 955 757 841 967 377 932 309 945 440 627 324 538 539 119 83 930 542 834 116 640 659 705 931 978 307 674 387 22 746 925 73 271 830 778 574 98 513 987 291 162 637 356 768 656 575 32 53 351 151 942 725 967 431 108 192 8 338 458 288 754 384 946 910 210 759 222 589 423 947 507 31 414 169 901 592 763 656 411 360 625 538 549 484 596 42 603 351 292 837 375 21 597 22 349 200 669 485 282 735 54 1000 419 939 901 789 128 468 729 894 649 484 808 422 311 618 814 515
Because the inputFile becomes false1 after an unsuccessful reading attempt has been done, and not when there's just no more data to read. So, when you've read successfully the last element you are inputFile still evaluates to true, and the next iteration of the while is started. Now, at inputFile>>number the failbit is set, but you're not checking it immediately, so your code goes on normally, "thinking" that another element has been read (when actually is just the old one which happened to remain in number). Quick solution: move the check after the read: for(;;) { inputFile >> number; if(!inputFile) break; total+=number; counter++; cout<<"The running total is: " <<total <<"\n"; } or (better): while(inputFile >> number) { total+=number; counter++; cout<<"The running total is: " <<total <<"\n"; } This works because operator>> returns the stream object, which is evaluated just after the read in the while condition section. 1. I know, I know that it's not actually false but it's operator(void*)... but don't overcomplicate things :)
3,161,757
3,161,851
A crash in injected / hooked target application
I have injected my DLL into a target application where I've hooked few WINAPI-functions as well. One of them is DrawTextExW. I'm trying to replace all 'l' letters to '!' before it prints it out. My solution works fine for a few seconds, but then the target application crashes. I really don't understand why. Here's the function: Edit - Working solution: int WINAPI DetouredDrawTextExW(__in HDC hdc, __inout LPWSTR lpchText, __in int cchText, __inout LPRECT lprc, __in UINT dwDTFormat, __in LPDRAWTEXTPARAMS lpDTParams) { std::wstring s_wc(lpchText, cchText); std::replace(s_wc.begin(), s_wc.end(), L'l', L'!'); return ::DrawTextExW(hdc, const_cast<wchar_t *>(s_wc.c_str()), s_wc.length(), lprc, dwDTFormat, lpDTParams); } So, can somebody point it out to me what I'm doing wrong?
I see that you ignore cchText, could you be receiving an non-NULL-terminated string with a positive value for cchText, resulting in reading past the end of the string into invalid memory? That error would present as a Win32 exception in the constructor of s_wc, though. Also, you aren't checking for DT_MODIFYSTRING in the dwDTFormat parameter. If that flag is present, then ::DrawTextExW() could be overwriting invalid memory. That would present as a Win32 exception in ::DrawTextExW() or perhaps as a C++ exception in the s_wc destructor. edit Here's uncompiled, untested code that I believe obeys the contract of ::DrawTextExW() int WINAPI DetouredDrawTextExW(__in HDC hdc, __inout LPWSTR lpchText, __in int cchText, __inout LPRECT lprc, __in UINT dwDTFormat, __in LPDRAWTEXTPARAMS lpDTParams) { std::vector<wchar_t> v_wc; int strSize = cchText == -1 ? wcslen(lpchText) : cchText; v_wc.resize(strSize + 4); std::copy(lpchText, lpchText + strSize, &v_wc.front()); std::replace(v_wc.begin(), v_wc.end() - 4, L'l', L'!'); int result = ::DrawTextExW(hdc, &v_wc.front(), strSize, lprc, dwDTFormat, lpDTParams); if (dwDTFormat & DT_MODIFYSTRING) { std::copy(&v_wc.front(), &v_wc.front() + v_wc.size(), lpchText); } }
3,161,846
3,161,981
Best practice for a Qt application with multiple UIs in C++
The case is as follows: You have a main window (ui1) that is to contain two other UIs (ui2 and ui3). Neither ui2 nor ui3 care about any other uis. They only have slots to react to, and they might emit signals as well. See drawing below. +----------------------------+ | +------+ +------+ | | | | | | | | | | | | | | | | | | | | | ui2| | ui3| | | +------+ +------+ | | | | ui1 | +----------------------------+ ui1 is loaded by AppWindow class and is used like this: ... int main(int argc, char *argv[]) { CustomApp app(argc,argv); AppWindow w; w.show(); return app.exec(); } What is a recommended way of creating the AppWindow class? Any simple example? Thanks
When creating ui1, drag two basic widgets (i.e. QWidget) into the UI. Then, in designer, you can right click and choose Promote To .... Within that dialog specify the "Promoted class name" and the "Header file" that correspond to ui2 and ui3. You won't be able to see a live preview using this method, but when the header and class name are specified correctly it will compile and work correctly.
3,162,030
3,162,067
Difference between angle bracket < > and double quotes " " while including header files in C++?
Possible Duplicate: What is the difference between #include <filename> and #include “filename”? What is the difference between angle bracket < > and double quotes " " while including header files in C++? I mean which files are supposed to be included using eg: #include <QPushButton> and which files are to be included using eg: #include "MyFile.h"???
It's compiler dependent. That said, in general using " prioritizes headers in the current working directory over system headers. <> usually is used for system headers. From to the specification (Section 6.10.2): A preprocessing directive of the form # include <h-char-sequence> new-line searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined. A preprocessing directive of the form # include "q-char-sequence" new-line causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read # include <h-char-sequence> new-line with the identical contained sequence (including > characters, if any) from the original directive. So on most compilers, using the "" first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <> starts the search with system headers.
3,162,149
3,162,161
Assuring proper maintenance of Clone() in C++
In C++, I find it very useful to add a "Clone()" method to classes that are part of hierarchies requiring (especially polymorphic) duplication with a signature like this: class Foo { public: virtual Foo* Clone() const; }; This may look pretty, but it is very prone to bugs introduced by class maintenance. Whenever anyone adds a data member to this class, they've got to remember to update the Clone() method. Failing to results in often subtle errors. Unit tests won't find the error unless they are updated or the class has an equality comparison method and that is both unit tested and was updated to compare the new member. Maintainers won't get a compiler error. The Clone() method looks generic and is easy to overlook. Does anyone else have a problem with Clone() for this reason? I tend to put a comment in the class's header file reminding maintainers to update Clone if they add data members. Is there a better idea out there? Would it be silly/pedantic to insert a #if/etc. directives to look for a change to the class size and report a warning/error?
Why not just use the copy constructor? virtual Foo* Clone() const { return new Foo(*this); } Edit: Oh wait, is Foo the BASE class, rather than the DERIVED class? Same principle. virtual Foo* Clone() const { return new MyFavouriteDerived(*this); } Just ensure that all derived classes implement clone in this way, and you won't have a problem. Private copy constructor is no problem, because the method is a member and thus can access it.
3,162,181
3,162,186
Would making 'this' a reference rather than a pointer be better in retrospect?
Possible Duplicate: Why ‘this’ is a pointer and not a reference? Is there any reason for this in C++ to be a pointer rather than a reference other than historical language decision? It feels a tad strange given that e.g. copy constructor or assignment operators both accept reference to "that", not a pointer. [I honestly couldn't find this question, though it does feel like a possible duplicate]
References didn't exist in the language when this was created.
3,162,227
3,162,240
Link lists in C++ (pt. 2)
How come void del_begin() crashes when there's only one node left (I have other functions to add nodes)? #include <iostream> using namesspace std; node *start_ptr = NULL; node *current; int option = 0; void del_end() { node *temp, *temp2; temp = start_ptr; if (start_ptr == NULL) cout << "There are no nodes" << endl; else { while (temp->nxt != NULL) { temp2 = temp; temp = temp->nxt; } delete temp; temp2->nxt = NULL; } } void display() { node *temp; temp = start_ptr; cout << endl; if (temp == NULL) cout << "There are no nodes to display" << endl; else { while(temp != NULL) { cout << temp->name << ", " << temp->profession << ", " << temp->age; if (temp == current) cout << "***"; cout << endl; temp = temp->nxt; } cout << endl; } } int main() { start_ptr = NULL; int option; do { display(); cout << "0 for EXIT" << endl; cout << "1 to ADD TO END" << endl; cout << "2 to ADD TO BEGINNING" << endl; cout << "3 to DELETE LAST" << endl; cout << "4 to DELETE BEGINNING" << endl; cout << ">>"; cin >> option; switch (option) { case 1 : add_end(); break; case 2 : add_begin(); break; case 3 : del_end(); break; case 4 : del_begin(); break; } } while (option != 0); return 0; }
You didn't show us the code for del_begin(), but your del_end() has a bug in the case you're mentioning (single node list). If you have only one node, your while loop will never execute, and temp2 will be uninitialized when you get to the line: temp2->nxt = NULL; Crash!
3,162,291
3,162,304
Mediator pattern vs Publish/Subscribe
Can someone point out the main differences between the two? It seems that, at least conceptually, the two are very closely related. If I were to hazard a guess, I would say that the publish/subscribe method is a subset of the mediator pattern (since the mediator need not necessarily be used in the publish/subscribe manner, but the latter seems to require a sort of mediator object). Is that anywhere near close to it?
How I would describe the difference is that in mediator you probably care if the end application receives the message. So you use this to guarantee who is receiving the message. Whereas with pub/sub you just publish your message. If there are any subscribers they will get it but you don't care.
3,162,430
3,162,441
iads.h / VS2005 / W2003 SP2 - which SDK and what are the side-effects?
I'm trying to compile someone elses C++ program using VS2005 on Windows 2003 (SP2). The compile fails because it can't find iads.h Which SDK should I install to get this header ? When I install the SDK is there a danger I might break something already in use ? As far as I can tell the W2003 has no SDK's installed but if it did would installing a different one cause problems ?
You need to the windows sdk. The SDK doesn't install like a regular application. Just because you "installed" it it doesn't change any settings in your compiler. You will still have to add the directories to header files and libraries in the vs settings page. You can have multiple version of the windows sdk, you just need to update the directories in the vs options page.
3,162,502
3,162,534
Is realloc guaranteed to be in-place when the buffer is shrinking?
Are there any guarantees that realloc() will always shrink a buffer in-place?? So that the following: new_ptr = (data_type *) realloc(old_ptr, new_size * sizeof(data_type)); will always give new_ptr == old_ptr if new_size < old_size (except of course when new_size == 0). It seems sensible (to me) that it would work this way, but was curious whether the standard enforced it. I'm looking at the reallocation of arrays of non-POD data types, and if the above behaviour was guaranteed was thinking that the following strategy might at least allow efficient "shrinking": if (new_size > old_size) { // malloc() a new buffer // use placement copy constructor to copy old objects over // free() old buffer } else if (new_size < old_size) { // explicit destruction of unneeded objects // realloc() buffer } I"m expecting that an in-place "shrink" would be robust even if the data type had self references/pointers or whatever...
No. That's it. None of this "it may work in some architectures" or "it should, based on experience". The standard states clearly that the address may change so rely on that and nothing more. In any case, you asked if it was guaranteed - the answer that is a definite no(a). In terms of coding to the standard: do, or do not. There is no "try" :-) From c99: The realloc function deallocates the old object pointed to by ptr and returns a pointer to a new object that has the size specified by size. The contents of the new object shall be the same as that of the old object prior to deallocation, up to the lesser of the new and old sizes. Any bytes in the new object beyond the size of the old object have indeterminate values. If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size. Otherwise, if ptr does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to the free or realloc function, the behavior is undefined. If memory for the new object cannot be allocated, the old object is not deallocated and its value is unchanged. The realloc function returns a pointer to the new object (which may have the same value as a pointer to the old object), or a null pointer if the new object could not be allocated. (a) If you're wondering why you wouldn't just split up a buffer into two smaller buffers (keeping one and returning the other to the free list) for efficiency, there is at least one possibility that springs to mind. If you have different pools for allocations of different sizes (which may use different allocation strategies, for example), it might make sense to move the data over to the pool for smaller allocations. The efficiency gains you get from separate pools may outweigh the gains of leaving memory in place. But that's just an example, I have no idea whether any implementation does that. As stated, you should rely on what the standard mandates, which is that the memory may move even when shrinking.
3,162,506
3,162,514
C++: How to declare an array at the top of the method?
I'd like to declare an array at the top of my method, but it's not compiling: Foo Bar() { int arr[]; // C2133 // … // C2059, C2143, C2143 arr[] = {1, 2, 3}; } What am I doing wrong here? UPDATE I know that C++ doesn't force me to do it this way, but the project's convention wants all variables declared at the top of their method.
When you declare an array in C/C++, you need to specify the size. If you do not specify the size, then you need to define the array elements in the same declaration statement, like this: int arr[] = {1, 2, 3};
3,162,510
3,164,874
How to make GCC search for headers in a directory before the current source file's directory?
I am using GCC precompiled headers in my project with multi-architecture build, but things break down when I try to place it in a directory different from current source's directory. The file is included with double quotes, and it works if I change it to angle brackets, but the problem is that I have a lot of other projects that use the same precompiled header name, so changing all of them to angle brackets is not desirable as it may create ambiguity about which header to include in Visual Studio build of the same files. GCC searches current directory for double-quote includes before its search path. I can work around it using -I- option (e.g. -Ipch_dir.i686 -I-), so that precompiled headers directory is searched before the current directory, but this option is deprecated. GCC suggests I use -iquote, but it does not have the same effect as -I-. So the question is how do I make it work without changing all precompiled headers include directives to angle brackets and using a deprecated GCC switch?
I have found a workaround. Build a precompiled header under a different name. For example is the header is a.h, original precompiled header is pchdir.i686/a.h.gch, build it as gcc a.h -o pchdir.i686/a-precompiled.h.gch Use GCC's -include switch to make sure the renamed header is included before anything else (even before the original a.h), e.g. gcc -Ipchdir.i686 -include a-precompiled.h <other arguments> <source> Final inclusion order in the source file will be: a-precompiled.h.gch, a.h, which I've checked with -H. Original header is included, but is not actually processed because precompiled header has identical include guards (verified as well by inserting an #error in the original header after building the precompiled one).
3,162,533
3,162,557
using BOOST_TYPEOF in expression
Can the following be done in a single line? typedef BOOST_TYPEOF(generator) G; typename G::value_type next; typename BOOST_TYPEOF(generator)::value_type next; //does not compile thank you
Try to use mpl::identity typename mpl::identity<BOOST_TYPEOF(generator)>::type::value_type next; The macro is probably expanding to some compiler intrinsics like __typeof__(...) which aren't necessarily eligible to appear as nested name specifier. Even the C++0x proposed decltype(...) initially wasn't allowed before a ::, but is in the FCD.
3,162,643
3,162,731
Proper Trigonometry For Rotating A Point Around The Origin
Do either of the below approaches use the correct mathematics for rotating a point? If so, which one is correct? POINT rotate_point(float cx,float cy,float angle,POINT p) { float s = sin(angle); float c = cos(angle); // translate point back to origin: p.x -= cx; p.y -= cy; // Which One Is Correct: // This? float xnew = p.x * c - p.y * s; float ynew = p.x * s + p.y * c; // Or This? float xnew = p.x * c + p.y * s; float ynew = -p.x * s + p.y * c; // translate point back: p.x = xnew + cx; p.y = ynew + cy; }
It depends on how you define angle. If it is measured counterclockwise (which is the mathematical convention) then the correct rotation is your first one: // This? float xnew = p.x * c - p.y * s; float ynew = p.x * s + p.y * c; But if it is measured clockwise, then the second is correct: // Or This? float xnew = p.x * c + p.y * s; float ynew = -p.x * s + p.y * c;
3,162,814
3,163,025
Does GetPath() return cubic or quadratic bezier control points?
Microsoft's docs say: Specifies that the corresponding point in lpPoints is a control point or ending point for a Bèzier curve. PT_BEZIERTO values always occur in sets of three. The point in the path immediately preceding them defines the starting point for the Bèzier curve. The first two PT_BEZIERTO points are the control points, and the third PT_BEZIERTO point is the ending (if hard-coded) point. http://msdn.microsoft.com/en-us/library/dd144908%28v=VS.85%29.aspx does this mean it returns cubic or quadratic curves? Thanks
It's a cubic with shared endpoints. p[0], p[1], p[2], p[3] make up the first segment; p[3], p[4], p[5], and p[6] make up the second segment. And so forth.
3,162,826
3,162,847
Fastest timing resolution system
What is the fastest timing system a C/C++ programmer can use? For example: time() will give the seconds since Jan 01 1970 00:00. GetTickCount() on Windows will give the time, in milliseconds, since the system's start-up time, but is limited to 49.7 days (after that it simply wraps back to zero). I want to get the current time, or ticks since system/app start-up time, in milliseconds. The biggest concern is the method's overhead - I need the lightest one, because I'm about to call it many many times per second. My case is that I have a worker thread, and to that worker thread I post pending jobs. Each job has an "execution time". So, I don't care if the time is the current "real" time or the time since the system's uptime - it just must be linear and light. Edit: unsigned __int64 GetTickCountEx() { static DWORD dwWraps = 0; static DWORD dwLast = 0; DWORD dwCurrent = 0; timeMutex.lock(); dwCurrent = GetTickCount(); if(dwLast > dwCurrent) dwWraps++; dwLast = dwCurrent; unsigned __int64 timeResult = ((unsigned __int64)0xFFFFFFFF * dwWraps) + dwCurrent; timeMutex.unlock(); return timeResult; }
For timing, the current Microsoft recommendation is to use QueryPerformanceCounter & QueryPerformanceFrequency. This will give you better-than-millisecond timing. If the system doesn't support a high-resolution timer, then it will default to milliseconds (the same as GetTickCount). Here is a short Microsoft article with examples of why you should use it :)
3,162,876
3,162,900
Can't catch atan2 domain error
I am using a thirdparty library eg. Lib::ValueType value. I then do a call to a member function, value.theta() which performs some mathematical operations including a call to atan2 from <cmath>. Sometimes the theta component is empty and an "atan2: domain error" is thrown. However, I can't catch the exception even by wrapping try{}catch(...) around the suspect code. I am using C++ Builder 2009, any idea as to how the exception is being thrown and not being caught by the IDE, or my code. The error pops straight up to the screen as a dialog. I have selected all the options in the IDE to handle everytype of exception.
The C standard library isn't aware of C++ exception handling, so try-catch won't work. You might want to look at the matherr function - according to the documentation, you can redefine this function in your program in order to handle math exceptions by yourself.
3,163,017
3,163,019
Intentional compiler warnings for Visual C++ that appear in Error List?
How can you create a compiler warning (in the model of #error, except as a warning) on purpose in Visual C++ that will show up on the Error List with the correct file and line number? GCC and other compilers offer #warning, but the MSVC compiler does not. The "solution" at http://support.microsoft.com/kb/155196 does not parse in the Visual Studio error list.
Just add this to your common include file (ex, stdafx.h): #define __STR2__(x) #x #define __STR1__(x) __STR2__(x) #define __LOC__ __FILE__ "("__STR1__(__LINE__)") : warning W0000: #pragma VSWARNING: " #define VSWARNING(x) message(__LOC__ x) Use this like: #pragma VSWARNING("Is this correct?!?!") The compiler will output: c:\dir\file.h(11) : warning W0000: #pragma VSWARNING: Is this correct?!?! And the Error List tab will show the warning nicely in the table: Type Num Description File Line [Warning] 13 warning W0000: #pragma VSWARNING: Is this correct?!?! file.h 11 exactly like a normal Visual Studio compiler warning.
3,163,055
3,163,060
TestFixtureSetUp-like method in CppUnit
In NUnit, the TestFixtureSetup attribute can be used to mark a method which should be executed once before any tests in the fixture. Is there an analogous concept in CppUnit? If not, is there a C++ unit testing framework that supports this concept? Based on the answer below, here is an example which accomplishes this (following the advice of the answers to this question): // Only one instance of this class is created. class ExpensiveObjectCreator { public: const ExpensiveObject& get_expensive_object() const { return expensive; } private: ExpensiveObject expensive; }; class TestFoo: public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(TestFoo); CPPUNIT_TEST(FooShouldDoBar); CPPUNIT_TEST(FooShouldDoFoo); CPPUNIT_TEST_SUITE_END(); public: TestFoo() { // This is called once for each test } void setUp() { // This is called once for each test } void FooShouldDoBar() { ExpensiveObject expensive = get_expensive_object(); } void FooShouldDoFoo() { ExpensiveObject expensive = get_expensive_object(); } private: const ExpensiveObject& get_expensive_object() { static ExpensiveObjectCreator expensive_object_creator; return expensive_object_creator.get_expensive_object(); } };
Since you cannot use the fixture constructor this implies that CPPUnit is using instance per test. I think you''ll have to have a method and a static boolean flag that is read many times and written only the first time. Then call this in the constructor.
3,163,241
3,233,984
CDialog doesnt show in task bar
Im trying to get a CDialog that has no border or frame to show in the task bar. It is created in the InitInstance of CWinApp (used to update the app) and i have tried setting the WS_EX_APPWINDOW flag but it still doesnt show in the task bar. Any ideas? Edit: As defined in the resource: IDD_UPDATEFORM_DIALOG DIALOGEX 0, 0, 246, 124 STYLE WS_POPUP EXSTYLE WS_EX_APPWINDOW FONT 8, "MS Shell Dlg", 400, 0, 0x1 BEGIN END As used: UpdateForm *dlg = new UpdateForm(UPDATE_FILES, CWnd::GetDesktopWindow()); INT_PTR nResponse = dlg->DoModal(); UpdateForm::UpdateForm(int updateType, CWnd* pParent) : CDialog(IDD_UPDATEFORM_DIALOG, pParent) { m_bInit = false; m_hIcon = AfxGetApp()->LoadIcon(IDI_ICON); m_Progress = new DesuraProgress(); m_updateType = updateType; } Still Shows up like so: http://update.goldeneyesource.net/lodle/noicon.jpg http://update.goldeneyesource.net/lodle/noicon.jpg
I figured out a hack to get this to work. Instead of disabling the toolbar/caption bar styles to get no border, i used SetWindowRgn to clip the frame and title bar. Same affect, less issues. RECT rect; GetWindowRect(&rect); int w = rect.right - rect.left; int h = rect.bottom - rect.top; HRGN region = CreateRoundRectRgn(5, 30, w-5, h-5-30, 5, 5); SetWindowRgn(region, true);
3,163,281
3,163,296
Reading a text document character by character
I am reading a text file character by character using ifstream infile.get() in an infinite while loop. This sits inside an infinite while loop, and should break out of it once the end of file condition is reached. (EOF). The while loop itself sits within a function of type void. Here is the pseudo-code: void function (...) { while(true) { ... if ( (ch = infile.get()) == EOF) {return;} ... } } When I "cout" characters on the screen, it goes through all the character and then keeps running outputting what appears as blank space, i.e. it never breaks. I have no idea why. Any ideas?
In C++, you don't compare the return value with EOF. Instead, you can use a stream function such as good() to check if more data can be read. Something like this: while (infile.good()) { ch = infile.get(); // ... }
3,163,364
3,626,967
Excluding certain functions from gcov/lcov coverage results
Is it possible to exclude certain functions or lines of code from the gcov coverage analysis. My code contains certain functions that are used for debugging, and are not exercised as part of my test suite. Such functions reduce the coverage percentage reported by gcov. I would like to exclude these functions from the results. If it is not possible via gcov, perhaps it is possible via lcov, but I was not able to figure it out. Your help is appreciated.
I filter out certain source files by running the output of lcov --capture through a simple awk script. The output of lcov --capture has a very simple format and the awk script below filters out source files matching file_pattern. I think it is possible to adapt the script to make it filter functions instead of file names. BEGIN { record="" } /^SF/ { if ( match ($0, "file_pattern" ) ) { doprint = 0 } else { doprint = 1 } } /^end_of_record$/ { if ( doprint ) { print record $0 } record = "" next } { record=record $0 "\n" }
3,163,424
3,163,460
About "GUI in C# and code in C++"
First of all, until now, all my programming education, has been targeted to console applications, just like everyone who starts learning C and C++. (the 2 languages i know) Now, i want to jump to the nice graphical World. So, I am exploring Windows Forms, i have already got many headaches trying to understand the language that it uses (quite diferent from native C++), but i managed to do a couple of things like using textbox and buttons. Well, the thing is, i have read in many places that, in order to avoid headaches trying to code winforms in C++, i'd better "Build the GUI in C#, because it's way easier, and the logic, and code in C++". And that is my question, i don't understand that statement, at all. What is that supposed to mean? Also, it's C# THAT similar to C++, as to affirm that statement? Cause, if C# was too diferent to C++, i would have to learn the whole C# language hope you understand my doubt. PD : Sry about my bad english.
Joan, while it is certainly possible to develop an applications Front End in C# and the logic in C++ I believe it to be a huge waste of effort to do it this way since you only complicate yourself for no real benefit since you can code both things in the same language. C# has many advantages over C++ and I personally use mostly C#, but I can clearly see many programmers who love C++. Now going into your question regarding the similarities between C++ and C# the answer is yes and no. Yes in the sense that C#'s syntax is clearly derived from C++. Many things like ifs and for loops are written exactly the same, so if you know how to write an if in C++ you can write it in C#. The difference (and a critical one that is) lies in the way the languages work. C++ is an strictly compiled language (it goes from C++ code to machine code). C# is an interpreted language (it goes from c# to MSIL and during runtime to machine code). In C# you can't use pointer arithmetic without explicitly allowing, in C++ you can (and will) use pointer arithmetic. C# has garbage collection, C++ does not. In the end, as I said in the first paragraph you can use both languages to build an application, but it would be highly complicated. My advise to you is to learn a bit of C# and then decide which language you would prefer to build your GUI application. But don't believe even for a second that C++ can't be used to build a front-end since there are a myriad of frameworks for that. One I remember from the top of my head is Qt. Another option for you is to use "C++/CLI" which is a flavor of C++ which can use the .NET Framework (the same framework C# uses) EDIT: Thanks Jerry for pointing out that Managed C++ is obsolete and that C++/CLI is the one!
3,163,489
3,163,507
why default constructor is not available by default in some case
class foo { public: int a; int b; foo(int a_, int b_) : a(a_), b(b_) {} }; int main() { foo f; } when I try to compile the above code snippet, I got error message as below: foo.cc: In function 'int main()' foo.cc:12: error: no matching function for call to 'main()::foo::foo()' foo.cc:10: note: candidates are: main()::foo::foo(int, int) foo.cc:6: note: main()::foo::foo(const main()::foo&) but if I comment the file of explicit constructor with two integer prarmeters, then the code can be compiled. I guess the rule behind the magic is that when you explicite declare constructor with parameters, c++ compilor will not atuomatically generate a default constructor with no parameters for you. Am I right? If am right, why does c++ has such behaviour? thanks in advance.
Compiler generates default constructor only if there're no user defined constructors. C++ Standard 12.1/5: A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a default constructor is implicitly declared.
3,163,569
3,163,616
C++0x - lambda expression does look same as Java's anonymous inner class?
Is my interpretation of lambda expression in the context of c++ and Java is correct?
They are not quite as same. Both create unnamed classes, but their similarity ends at that point. In C++ you create a closure catching your local variables, optionally by reference. In Java, you just get a snapshot of the current local variable's values (and those variables need to be "final"). The purpose of anonymous inner classes is to extend another class or implement another interface ad-hoc. For that reason, anonymous inner classes can simulate the job of lambda expressions to some extend, for example by implementing the Runnable interface. Lambda expressions are specifically designed to be called and possibly modify the local variables in their environment.
3,163,684
3,164,165
checking if time is in specific interval in C++?
I need to generate values according to time of the day, is there a neat way to accomplish that ? from 9-12 value should be between x - y from 6-9 value should be between a - b is there any other way than getting timeinfo struct and extracting hour out of it?
You should take a look at boost::posix_time. using namespace boost::posix_time; using namespace boost::gregorian; ptime now = second_clock::local_time(); // You can compare now with other ptime values ptime nine_o_clock = day_clock::local_day() + hours(9); ptime twelve_o_clock = day_clock::local_day() + hours(12); if ((now >= nine_o_clock) && (now < twelve_o_clock)) { // Do what you want. }
3,163,757
3,163,801
C++ factory function with boost::noncopyable
Suppose I need to implement factory function which returns object O which inherits/has members inheriting from boost::noncopyable. struct O : boost::noncopyable {}; O factory() { return O(); } Obviously returning value fails to compile. What method do you know or use to implement such factory methods? I really like to avoid overriding copy constructor if it is possible and to return value rather than reference or pointer. after some tinkering and link from codeka I managed this (no idea how portable does this, seems to work with g++): template<class E> struct threads_parallel_for_generator : for_generator<E, threads_parallel_for_generator<E> > { typedef for_generator<E, threads_parallel_for_generator> base_type; struct factory_constructor { explicit factory_constructor(const E &expression) : expression_(expression) {} operator const E&() const { return expression_; } private: E expression_; }; threads_parallel_for_generator(const factory_constructor & constructor) : base_type(constructor, *this) {} private: boost::mutex mutex_; }; template<class E> static threads_parallel_for_generator<E> parallel_for(const E &expression) { typedef threads_parallel_for_generator<E> generator; return typename generator::factory_constructor(expression); }
Boost does have support for this in the form of BOOST_MOVABLE_BUT_NOT_COPYABLE, but in my opinion it's far more trouble than it's worth to implement (without C++11) and just returning a (smart) pointer is far easier...
3,163,901
3,164,000
Asynchronous distributed file transfers
I need to build a system where we have a set of machines produce unique files, lets call them PRODUCERS and a set of machines receive these files which we call CONSUMERS. Any machine from the PRODUCERS can send files to one or more of the CONSUMERS[ based on some hash mechanism]. I need to build a mechanism which ensures that the file delivery happens in a guaranteed mannner. i.e. Producers or consumers may crash/reboot and be able to continue from where they left off. Is there any fool proof scalable way to implement this, it seems to be quite a common need in any fault tolerant system? The number of producers and consumers are expected to increase/decrease on the fly.
What you describe is probably most easily implemented using some form of message passing. You might want to take a look at http://www.zeromq.org; I've worked with this library myself and can whole-heartedly recommend it. On a side-note: if you don't need to use C++, picking up some Erlang might be interesting in your case.
3,163,916
3,163,997
how a variable can be access in all dialogs of a project using MFC?
i have made a file open dialog, it contains an edit control whose variable is "path" that contains the file name. what i want is to use this variable's value in other dialogs but it gives the error that "path" is an undeclard identifier. i declare path by right click on edit control, add a variable of CString type. path variable gets its value by this code class CAboutDlg : public CDialog { public: CAboutDlg(); static CString imgname; in the same class, i used it like this CString image=CAboutDlg::imgname; CString szFilename(image); and passing value of path by this code path=dlg.GetPathName(); UpdateData(FALSE); CAboutDlg::imgname=path; but it still gives error that CAboutDlg and imgname are undeclared identifier in the above code in which i m passing value of path. i did the same which i learned from the site now what's wrong with that? plz tell rwong
Before the dialog closes, pass this "path" back to the CWinApp (by implementing Get/Set functions in the CWinApp) Your main class, which is derived from CWinApp, is in effect the "global" class (static class, or singleton). Anything you wish to put into global variables, can be put into your CWinApp-derived class instead. Variables can be protected by mutex, and Listeners, Subscribers etc can be implemented by using this class as the central ground.
3,164,034
3,170,433
Sort, pack and remap array of indexed values to minimize overlapping
Sitation: overview: I have something like this: std::vector<SomeType> values; std::vector<int> indexes; struct Range{ int firstElement;//first element to be used in indexes array int numElements;//number of element to be used from indexed array int minIndex;/*minimum index encountered between firstElement and firstElements+numElements*/ int maxIndex;/*maximum index encountered between firstElement and firstElements+numElements*/ Range() :firstElement(0), numElements(0), minIndex(0), maxIndex(0){ } } std::vector<Range> ranges; I need to sort values, remap indexes, and recalculate ranges to minimize maxValueIndex-minValueIndex for each range. details: values is an array(okay, "vector") of some type (irrelevant which one). elements in values may be unique, but this is not guaranteed. indexes is an vector of ints. each element in "indexes" is an indexes that correspond to some element in values. Elements in indexes are not unique, one value may repeat multiple types. And indexes.size() >= values.size(). Now, ranges correspond to a "chunk" of data from indexes. firstElement is an index of element to be used from indexes (i.e. used like this: indexes[range.firstElement]), numElements is (obviously) number of elements to be used, minIndex is mininum in (indexes[firstElement]...indexes[firstElement+numElements-1]) a,d maxIndex is maximum in (indexes[firstElement]...indexes[firstElement+numElements-1]). Ranges never overlap. I.e. for every two ranges a, b ((a.firstElement >= b.firstElement) && (a.firstElement < (b.firstElement+b.numElements)) == false Obviously, when I do any operation on values (swap to elements, etc), I need to update indexes (so they keep pointing on the same value), and recalculate corresponding range, so range's minIndex and maxIndex are correct. Now, I need to rearrange values in the way that will minimize Range.maxIndex - Range.minIndex. I do not need the "best" result after packing, having "probably the best" or "good" packing will be enough. problem: Remapping indexes and recalculating ranges is easy. The problem is that I'm not sure how to sort elements in values, because same index may be encountered in multiple ranges. Any ideas about how to proceed? restrictions: Changing container type is not allowed. Containers should be array-like. No maps, not lists. But you're free to use whatever container you want during the sorting. Also, no boost or external libraries - pure C++/STL, I really neeed only an algorithm. additional info: There is no greater/less comparison defined for SomeType - only equality/non-equality. But there should be no need to ever compare two values, only indexes. The goal of algorithm is to make sure that output of for (int i = 0; i < indexes.size; i++){ print(values[indexes[i]]); //hypothetical print function } Will be identical before and after sorting, while also making sure that for each range Range.maxIndex-Range.minIndex (after sorting) is as small as possible to achieve with reasonable effort. I'm not looking for a "perfect" or "most optimal" solution, having a "probably perfect" or "probably most optimal" solution should be enough. P.S. This is NOT a homework.
Okay, it looks like there is only one way to reliably solve this problem: Make sure that no index is ever used by two ranges at once by duplicating values. I.e scan entire array of indexes, and when you find index (of value) that is being used in more than one range, you add copy of that value for each range - each with unique index. After that problem becomes trivial - you simply sort values in the way that will make sure that values array first contains values used only by first range, then values for 2nd range, and so on. I.e. this will get maximum packing. Because in my app it is more important to minimize sum(ranges[i].maxIndex-ranges[i].minIndex) that to minimize number of values, this approach works for me. I do not think that there is other reliable way to solve the problem - it is quite easy to get situation when there are indexes used by every range, and in this case it will not be possible to "pack" data no matter what you do. Even allowing index to be used by two ranges at once will lead to problems - you can get ranges a, b and c where a and b, b and c, a and c will have common indexes. In this case it also won't be possible to pack the data.
3,164,234
3,298,482
How do I read stdout/stderr output of a child process correctly?
I have written a program a.exe which launches another program I wrote, b.exe, using the CreateProcess function. The caller creates two pipes and passes the writing ends of both pipes to the CreateProcess as the stdout/stderr handles to use for the child process. This is virtually the same as the Creating a Child Process with Redirected Input and Output sample on the MSDN does. Since it doesn't seem to be able to use one synchronization call which waits for the process to exit or data on either stdout or stderr to be available (the WaitForMultipleObjects function doesn't work on pipes), the caller has two threads running which both perform (blocking) ReadFile calls on the reading ends of the stdout/stderr pipes; here's the exact code of the 'read thread procedure' which is used for stdout/stderr (I didn't write this code myself, I assume some colleague did): DWORD __stdcall ReadDataProc( void *handle ) { char buf[ 1024 ]; DWORD nread; while ( ReadFile( (HANDLE)handle, buf, sizeof( buf ), &nread, NULL ) && GetLastError() != ERROR_BROKEN_PIPE ) { if ( nread > 0 ) { fwrite( buf, nread, 1, stdout ); } } fflush( stdout ); return 0; } a.exe then uses a simple WaitForSingleObject call to wait until b.exe terminates. Once that call returns, the two reading threads terminate (because the pipes are broken) and the reading ends of both pipes are closed using CloseHandle. Now, the problem I hit is this: b.exe might (depending on user input) launch external processes which live longer than b.exe itself, daemon processes basically. What happens in that case is that the writing ends of the stdout/stderr pipes are inherited to that daemon process, so the pipe is never broken. This means that the WaitForSingleObject call in a.exe returns (because b.exe finished) but the CloseHandle call on either of the pipes blocks because both reading threads are still sitting in their (blocking!) ReadFile call. How can I solve this without terminating both reading threads with brute force (TerminateThread) after b.exe returned? If possible, I'd like to avoid any solutions which involve polling of the pipes and/or the process, too. UPDATE: Here's what I tried so far: Not having b.exe inherit a.exe; this doesn't work. the MSDN specifically says that the handles passed to CreateProcess must be inheritable. Clearing the inheritable flag on stdout/stderr inside b.exe: doesn't seem to have any effect (it would have surprised me if it did). Having the ReadDataProc procedure (which reads on both pipes) consider whether b.exe is actually running in addition to checking for ERROR_BROKEN_PIPE. This didn't work of course (but I only realized afterwards) because the thread is blocked in the ReadFile call.
Is seems that on Windows versions prior to Windows Vista (where you can use the CancelSynchronousIO function, there is no way around terminating the reading threads using TerminateThread. A suitable alternative (suggested by adf88) might be to use asynchronous ReadFile calls, but that's not possible in my case (too many changes to the existing code required).
3,164,237
3,164,289
Problem with QMap return as reference?
Greetings all, I have a code snippet as follows : class AppCtx { private: QMap<QString,IRzPlugin*> pluginsMap; public : void addPlugin(IRzPlugin *plugin) { pluginsMap.insert(plugin->getPluginUID(),plugin); } QMap<QString,IRzPlugin*> & getPlugins() { return pluginsMap; } } In my client code I access the QMap as follows.But the application breaks where it access the 'plugins.size()' class MainWindow . . { void registerPlugins(AppCtx *appctx) { QMap<QString,IRzPlugin*> plugins=appctx->getPlugins(); qDebug("Num of plugins %d",plugins.size()); //Breaks here QList<IRzPlugin*> listPlugins=plugins.values(); for(int i=0;i<listPlugins.size();i++) { } } Debug info is given below : Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 0x7fff057a16f0 (LWP 9069)] 0x0000000000406ba1 in QMap<QString, IRzPlugin*>::size (this=0x405c2b) at /opt/qtsdk-2010.02/qt/include/QtCore/qmap.h:178 178 inline int size() const { return d->size; } (gdb) back #0 0x0000000000406ba1 in QMap<QString, IRzPlugin*>::size (this=0x405c2b) at /opt/qtsdk-2010.02/qt/include/QtCore/qmap.h:178 #1 0x0000000000406736 in MainWindow::registerPlugins (this=0x7fff0d7c98f0) at /work/svn-checkout/osaka3d/osaka3d/tags/iter07/prototype/osaka3d/rinzo/ui/mainwindow.cpp:23 } any tips? Thanks in advance, umanga
I notice you are copying the QMap with QMap<QString,IRzPlugin*> plugins=appctx->getPlugins(); I assume you want to take a reference to it i.e. QMap<QString,IRzPlugin*>& plugins=appctx->getPlugins(); If you only need a reference-to-const then the docs say that it is implicitly shared so it's not such a big deal. If this helps your problem then it must be something to do with copying the QMap. Edit Since this didn't help your problem I think you need to check the pointer appctx that gets passed into registerPlugins and check if it points to a valid object.
3,164,602
3,184,440
GOF State Pattern State Transition Implementation Issues
Firstly, can anyone explain how a state object can be shared when the state object has no instance variables ? This text is taken from GOF, page 308, item 3 (consequences section): The state object can be shared. If state objects have no instance variabkes - that is, the state they represent is encoded entirely in their type - then contexts can share a state object. When states are shared in this way, they are essentially flyweight. Can anyone explain this text ? Secondly, what are the approaches to the state transition decision? I mean the decision of which next state to propagate? Please help. Thanks.
In the state pattern you have an represent the state of an object by using state-objects. These state-objects represent a certain state, but they do not have any mutable state of their own. This means they never change. Therefore, any number of objects can use the same state-object at the same time (even from different threads). If the state-object had mutable state, other objects would have to worry about their state-object being changed from elsewhere. The using of one object instance by many others can be seen as an instance of the flyweight-pattern. As for the second part of your question, here is an example: class SomeStateMachine; class AbstractState { // abstract baseclass for all state-classes void input(const std::string & data, SomeStateMachine & caller) = 0; } class FinalState : public AbstractState { FinalState * getInstance(); // always returns same instance } class InitialState : public AbstractState { public: InitialState * getInstance(); // always returns same instance void input(const std::string & data, SomeStateMachine & caller) { std::cout << data << std::endl; caller.m_State = FinalState::getInstance(); } } class SomeStateMachine { public: SomeStateMachine() : m_State(InitialState::getInstance()) void input(const std::string & data) { m_State->input(data, *this); } private: friend class InitialState; AbstractState * m_State; }; So you basically pass a reference to the calling object to every method of your state-object. This way, the state-object is able to change the state of the caller when needed. This example might not be very beautiful, but I hope you get the idea.
3,164,792
3,164,828
whats an example usage of c++ pointers?
i'm self-teaching c++ and i get how pointers work. but the doc i'm using is quite literal and the examples don't really go into why or when pointers would be used. a couple of real world examples would help me retain the knowledge.
You use pointers when you want your objects to exist longer than the current stack. You can also use them to avoid copying objects into containers. // TODO: Remember to call DeleteObjects() when you're done here!! std::vector<MyObject*> Objects; void Test() { MyObject *const pObject = new MyObject(); Objects.push_back(pObject); } void DeleteObjects() { std::vector<MyObject*>::iterator it = Objects.begin(), itEnd = Objects.end(); for (; it != itEnd; ++it) { delete *it; } Objects.clear(); }
3,165,080
3,169,833
How to call Matlab from C++ code?
I am trying to call Matlab functions from C++ code. With Matlab it comes an example of such code at /extern/examples/eng_mat/engdemo.cpp, however I found no way to build that source code. Here is the makefile I use: CFLAGS = -Wall -O3 INCLUDES = -I/opt/Matlab-2009a/extern/include LIBRARIES = -Wl,-R/opt/Matlab-2009a/bin/glnx86 -L/opt/Matlab-2009a/bin/glnx86 -lmx -lmat -leng out : engdemo.cpp g++ $(CFLAGS) $(INCLUDES) -static $^ $(LIBRARIES) -o out clean : rm -f out (Here /opt/Matlab-2009a is my Matlab root.) I am getting a linker error like this: /usr/bin/ld: cannot find -lmx collect2: ld returned 1 exit status make: *** [out] Error 1 And the question is: how can I make g++ to compile engdemo.cpp ? Note, that the shared library exists: $ locate libmx.so /opt/Matlab-2009a/bin/glnx86/libmx.so /opt/Matlab-2009a/bin/glnx86/libmx.so.csf and $ ldd /opt/Matlab-2009a/bin/glnx86/libmx.so linux-gate.so.1 => (0x004b4000) libut.so => /opt/Matlab-2009a/bin/glnx86/../../bin/glnx86/libut.so (0x0078f000) libmwfl.so => /opt/Matlab-2009a/bin/glnx86/../../bin/glnx86/libmwfl.so (0x00110000) libicudata.so.38 => /opt/Matlab-2009a/bin/glnx86/../../bin/glnx86/libicudata.so.38 (0xb7f82000) libicuuc.so.38 => /opt/Matlab-2009a/bin/glnx86/../../bin/glnx86/libicuuc.so.38 (0x00bee000) libicui18n.so.38 => /opt/Matlab-2009a/bin/glnx86/../../bin/glnx86/libicui18n.so.38 (0x001f7000) libicuio.so.38 => /opt/Matlab-2009a/bin/glnx86/../../bin/glnx86/libicuio.so.38 (0x00e1c000) libz.so.1 => /usr/lib/libz.so.1 (0x0098e000) libstdc++.so.6 => /opt/Matlab-2009a/bin/glnx86/../../sys/os/glnx86/libstdc++.so.6 (0x00531000) libm.so.6 => /lib/libm.so.6 (0x00194000) libgcc_s.so.1 => /opt/Matlab-2009a/bin/glnx86/../../sys/os/glnx86/libgcc_s.so.1 (0x00eaa000) libpthread.so.0 => /lib/libpthread.so.0 (0x00900000) libc.so.6 => /lib/libc.so.6 (0x00345000) librt.so.1 => /lib/librt.so.1 (0x00964000) libdl.so.2 => /lib/libdl.so.2 (0x0014e000) libexpat.so.1 => /opt/Matlab-2009a/bin/glnx86/../../bin/glnx86/../../bin/glnx86/libexpat.so.1 (0x00152000) libboost_thread-gcc42-mt-1_36.so.1.36.0 => /opt/Matlab-2009a/bin/glnx86/../../bin/glnx86/../../bin/glnx86/libboost_thread-gcc42-mt-1_36.so.1.36.0 (0x00fc2000) libboost_signals-gcc42-mt-1_36.so.1.36.0 => /opt/Matlab-2009a/bin/glnx86/../../bin/glnx86/../../bin/glnx86/libboost_signals-gcc42-mt-1_36.so.1.36.0 (0x0017d000) libboost_system-gcc42-mt-1_36.so.1.36.0 => /opt/Matlab-2009a/bin/glnx86/../../bin/glnx86/../../bin/glnx86/libboost_system-gcc42-mt-1_36.so.1.36.0 (0x00a06000) /lib/ld-linux.so.2 (0x001db000) So, how can I make g++ to compile engdemo.cpp ?
Assuming $MATLABROOT is the path to MATLAB: $MATLABROOT/bin/mex -f $MATLABROOT/bin/engopts.sh engdemo.cpp If you add the -v switch, the verbose output will show you what commands are being used to compile the engine application.
3,165,289
3,165,378
C++ desktop applications framework
I am not new to c++,but i have not found a c++ desktop applications framework.I have found one and it seems to complex.Are there other frameworks available for c++ out there?.
There are various choices when it comes to c++ Desktop app frameworks, it mainy depends on your skills and on the plattform you want the app to run. Two Opensource Frameworks that are plattform independent, I have used so far are The QT-Framework from trolltech now nokia and wxWidgets if you need something in the multimedia area have a look at openframeworks
3,165,400
3,166,094
To use or not to use C++0x features
Possible Duplicate: How are you using C++0x today? I'm working with a team on a fairly new system. We're talking about migrating to MSVC 2010 and we've already migrated to GCC 4.5. These are the only compilers we're using and we have no plans to port our code to different compilers any time soon. I suggested that after we do it, we start taking advantage of some of the C++0x features already provided like auto. My co-worker suggested against this, proposing to wait "until C++0x actually becomes standard." I have to disagree, but I can see the appeal in the way he worded it. Nevertheless, I can't help but think that this counter-argument comes more out of fear and trepidation of learning C++0x than a genuine concern for standardization. Given the new state of the system, I want for us to take advantage of the new technology available. Just auto, for instance, would make our daily lives easier (just writing iterator-based for loops until range-based loops come along, e.g.). Am I wrong to think this? It is not as though I'm proposing we radically change our budding codebase, but just start making use of C++0x features where convenient. We know what compilers we're using and have no immediate plans to port (if we ever port the code base, by then surely compilers will be available with C++0x features as well for the target platform). Otherwise it seems to me like avoiding the use of iostreams in 1997 just because the ISO C++ standard was not published yet in spite of the fact that all compilers already provided them in a portable fashion. If you all agree, could you provide me arguments I could use to strengthen my position? If not, could I get a bit more details on this "until the C++0x is standard" idea? BTW, anyone know when that's going to be?
I'd make the decision on a per-feature basis. Remember that the standard is really close to completion. All that is left is voting, bugfixing and more voting. So a simple feature like auto is not going to go away, or have its semantics changed. So why not use it. Lambdas are complex enough that they might have their wording changed and the semantics in a few corner cases fixed up a bit, but on the whole, they're going to behave the way they do today (although VS2010 has a few bugs about the scope of captured variables, MS has stated that they are bugs, and as such may be fixed outside of a major product release). If you want to play it safe, stay away from lambdas. Otherwise, use them where they're convenient, but avoid the super tricky cases, or just be ready to inspect your lambda usage when the standard is finalized. Most features can be categorized like this, they're either so simple and stable that their implementation in GCC/MSVC are exactly how they're going to work in the final standard, or they're tricky enough that they might get a few bugfixes applied, and so they can be used today, but you run the risk of running into a few rough edges in certain border cases. It does sound silly to avoid C++0x feature solely because they're not formalized yet. Avoid the features that you don't trust to be complete, bug-free and stable, but use the rest.
3,165,563
3,165,672
Flexible logger class using standard streams in C++
i would like to create a flexible logger class. I want it to be able to output data to a file or to standard output. Also, i want to use streams. The class should look something like: class Logger { private: std::ostream m_out; // or ofstream, iostream? i don't know public: void useFile( std::string fname); void useStdOut(); void log( symbol_id si, int val ); void log( symbol_id si, std::string str ); //etc.. }; The symbol_id is an enum and defines the formatting. What i want to achieve is to be able to easily switch from standart output to a file and vice versa (this is the purpose of the use* methods). Preferably by just using m_out and simply writing m_out << "something"; without any checks whether i want to write to a file or stdout. I know there are many ways how to get around this (using if's to test if i want to write to a file or stdout, the "C way" (using FILE* and fprintf)) and so on, but i'm sure there must be a way how to achieve this with C++ streams in a nice way. But i can't seem to find the way how to do it. Can somebody help me please?
The way I've attacked this problem before is to make Logger an abstract base class and create separate FileLogger and OutStreamLogger classes. Then create a CompositeLogger object that implements the Logger interface, which just outputs all loggers: CompositeLogger compLogger; compLogger.Add(new FileLogger("output.txt")); compLogger.Add(new StreamLogger(std::cout)); ... compLogger.log(...); If you don't need this level of flexibility and want to keep all this in a single class you could make the m_Out variable a pointer to std::ostream and add an extra flag to keep track of whether you need to delete it on cleanup: private: std::ostream* m_out; bool m_OwnsStream; Logger() { m_Out=&std::cout; // defaults to stdout m_OwnsStream=false; } void useFile(std::string filename) { m_Out=new std::ofstream(filename); m_OwnsStream=true; } ~Logger() { if (m_OwnStream) delete m_Out; } Obviously you'd need some more checks in useFile and useStdOut to prevent memory leaks.
3,165,964
3,166,016
Multiple animation at a time
I'm making a Asteroids game but I can not get to play more than one explosion at a time. Just get to do one at a time ... This is my code I call in the main loop: for(i = 0; i < MAX_SHOTS; i++) { for(j = 0; j < MAX_ASTEROIDS; j++) { if(shot[i].CheckCollision(asteroide[j])) { shot[i].SetPos(-100, 0); explosionSnd.Play(); numAst = j; explosion[numExp++].Enable(true); if(numExp == MAX_EXPLOSIONS-1) { numExp = 1; } } } } for(i = 1; i < MAX_EXPLOSIONS; i++) { if(explosion[i].Enable()) { explosion[i].SetPos(asteroide[numAst].GetX(), asteroide[numAst].GetY()); explosion[i].Draw(); if(explosion[i].GetFrame() == 5) { explosion[i].Enable(false); } } } If I shot to an asteroid and after I shot to another, the animation is cut and goes to the new asteroid. Any help? Thank you.
Inside your second loop, you're moving each explosion to the location of the asteroid asteroide[numAst] - you're playing all the explosions, just all at the same place! You should only position the explosion once after you Enable(true) it, when it's created in the first loop, not each time you draw it. Hope that helps.
3,166,201
3,166,277
c++ STL queues, references and segmentation fault
Newbie to C++ learning by converting a java program to c++. The following code results in a segmentation fault (SIGSEGV) when executed. //add web page reference to pages queue (STL) void CrawlerQueue::addWebPage(WebPage & webpage) { pagesBuffer.push(webpage); } //remove and return web page reference from pages queue WebPage & CrawlerQueue::getWebPage() { if (pagesBuffer.size() > 0) { WebPage & page = pagesBuffer.front(); pagesBuffer.pop(); return page; } else throw "Web pages queue is empty!"; } //code that results in segmentation fault when called void PageParser::extractLinks(){ try { WebPage & page = crawlerqueue.getWebPage(); }catch (const char * error) { return; } } The changes to the above code that fix the segmentation fault issue are highlighted(<====): //return a const WebPage object instead of a WebPage reference const WebPage CrawlerQueue::getWebPage() { <==== if (pagesBuffer.size() > 0) { WebPage page = pagesBuffer.front(); <==== pagesBuffer.pop(); return page; } else throw "Web pages queue is empty!"; } //no segmentation fault thrown with modifications void PageParser::extractLinks(){ try { WebPage page = crawlerqueue.getWebPage(); <==== }catch (const char * error) { return; } } What gives? I'm still trying to understand references and pointers
pagesBuffer.pop(); This line invalidate your reference. Remember that standard container works with values, not "references", so when you add an object using a reference to it, in fact you add a copy of the object in the container. Then using pop(), you destroy this object, making any reference or pointer pointing to it invalid. Maybe you should store (shared) pointers instead of the objects.
3,166,319
3,166,391
Is it worth learning Eclipse for C++ development
As far as I know it is hard to learn using Eclipse from scratch. But I will get such benefits as fast source code browsing, call graphs, static code analysis. What other benefits will I get from using Eclipse for C++ (CDT)?
I used Eclipse with C++ only for a short time, and rather I could use Eclipse with Java for some months. Now that I'm not using it, I feel that some important features are missing. Eclipse is pretty heavy, but has some great features that I can't find easily somewhere else. I can live without code analysis and project management (for small projects), but some features about source code navigation and refactoring are really unique and I really miss them. IMHO, Eclipse is worth learning, even if it won't become your default IDE.
3,166,395
3,166,460
Win7 Drag&Drop: Possible to find out if COleDataObject contains shell library?
I have an application with a file and folder list control which supports Drag&Drop operations. Now I would like to make it possible for the user to be able to drop a Windows 7 Library (e.g. Music, Pictures and so on) into this control. In my drop handler I have a COleDataObject and now I'm trying to find out, if a library has been dropped into the control. Since the object does not seem to contain a standard format (e.g. CF_HDROP), I'm using COleDataObject::BeginEnumFormats and COleDataObject::GetNextFormat to enumerate the formats in the data object. I get a total of 5 different FORMATETC structures. Here's a list of the FORMATETC.cfFormat and FORMATETC.tymed members of the individual structures: cfFormat = 0xc0a5, tymed = 0x1 cfFormat = 0xc418, tymed = 0x1 cfFormat = 0xc410, tymed = 0x1 cfFormat = 0xc0fd, tymed = 0x4 cfFormat = 0xc0fc, tymed = 0x1 Can anyone tell me if one of them is pointing to a shell library and if so, how I would be able to e.g. determine the parsing name of this library? Are these cfFormat values perhaps documented somewhere? Best regards, humbagumba
These MSDN pages might help: http://msdn.microsoft.com/en-us/library/bb776902%28VS.85%29.aspx http://msdn.microsoft.com/en-us/library/ff729168%28VS.85%29.aspx They don't have the exact format values you've given, but it should be a start.
3,166,510
3,166,556
c++: Call derrived function from base constructor?
Possible Duplicate: Calling virtual functions inside constructors class Base { virtual void method() { cout << "Run by the base."; }; public: Base() { method(); }; }; class Derived: public Base { void method() { cout << "Run by the derived."; }; }; void main() { Derived(); } Output: Run by the base. How can one have the derived method run instead, without making a derived constructor?
You can't do this without adding extra code. A common way to achieve this is to use a private constructor and a create function that first calls the constructor (via new) and then a second finish_init method on the newly created object. This does prevent you from creating instances of the object on the stack though.
3,166,541
3,166,640
Tips on creating a C++ DLL to be used from .NET
Hey guys, I'm creating a DLL in C++ and I want it to be usable from .NET apps (both C# and VB.NET). I've been scouring the internet for tips and what I've found so far suggests: Declaring my C++ functions as extern C and using __stdcall Using basic C types for parameters and return types instead of STL containers (e.g. char* instead of std::string) Using pointers for input parameters that need to be modified instead of references Assuming typedef unsigned char byte; It's a compression function. The inputs it expects are the input data (passed as byte*), the size of the input data (passed as int), a pointer to the variable in which to store the compressed size (passed as int*), and a string in which error messages can be stored if needed (passed as char*). The function malloc's the output buffer, writes the output, and returns a byte*, and the calling code is expected to free the buffer when it's done using it. In case an error occurs the error message is strcpy'd into the error string and a NULL pointer is returned. Is my current set-up all right or do I need to make some other modifications for it to be callable from .NET?
The managed code cannot free the memory, it doesn't have access to the allocator built into the CRT. You could use CoTaskMemAlloc() to allocate the buffer instead, the managed code can call Marshal.FreeCoTaskMem(). You'd have to declare the buffer pointer argument as "ref IntPtr" or declare the return type of the function as IntPtr. Which gives the managed code the hassle of converting it to a managed byte array. This is not pretty, these problems disappear when you write the code in C++/CLI or write a COM server.
3,166,569
3,166,664
What's the best way to move on to advanced C++?
And what's your suggestion to move to the next level of C++ programming for someone who may be called, well, an intermediate C++ programmer? Intermediate Programmer: Understands ISO C++ reasonably well, can read and modify other's code with some luck, good with data structures and algorithms but not great Learn C++0x Learn what kind of assembly code gets generated for different construct types, maybe for x86 Forget language nuances and get the fundamentals -- automata theory from somewhere like Sipser or Papadimitriou If you know OOP or at least think you do, consider how to incorporate functional programming skills with C++ Work on something on the lines of a compiler and open-source like LLVM or GNU Toolchain The whole idea is busted -- the next level means more sophisticated data structures. So if you know AVL, consider learning left leaning red black trees et al Now obviously nobody can do everything in this list without prioritizing, so we need some suggestion on what might be the best way forward. NOTE: Thank you all for the very helpful responses.
To answer your specific questions: Learn C++0x You definitely need to do this. So possibly you have your answer right there... Learn what kind of assembly code gets generated for different construct types, maybe for x86 I would say learn how to understand the assembly language the compiler generates, in outline if not in detail. You certainly should not be trying to predict what the compiler will do, however. Forget language nuances and get the fundamentals -- automata theory from somewhere like Sipser or Papadimitriou If it turns you on, I suppose... If you know OOP or at least think you do, consider how to incorporate functional programming skills with C++ Of all of the paradigms C++ supports, functional programming is probably the worst supported - if you want to learn FP, learn Haskell (or whatever), not C++. Work on something on the lines of a compiler and open-source like LLVM or GNU Toolchain GNU is written in C, so it's not likely to boost your C++ skills - I know little about LLVM. The whole idea is busted -- the next level means more sophisticated data structures. So if you know AVL, consider learning left leaning red black trees et al RB trees are not much more sophisticated than AVL trees - same basic concept. If you understand the basic structures covered in a data structures textbook, I don't see the need to dig further, unless the subject particularly interests you.
3,167,045
3,167,077
Do I need to specify virtual on the sub-classes methods as well?
This has probably been asked before on SO, but I was unable to find a similar question. Consider the following class hierarchy: class BritneySpears { public: virtual ~BritneySpears(); }; class Daughter1 : public BritneySpears { public: virtual ~Daughter1(); // Virtual specifier }; class Daughter2 : public BritneySpears { public: ~Daughter2(); // No virtual specifier }; Is there a difference between Daughter1 and Daughter2 classes ? What are the consequences of specifying/not specifying virtual on a sub-class destructor/method ?
No you technically do not need to specify virtual. If the base method is virtual then C++ will automatically make the matching override method virtual. However you should be marking them virtual. The method is virtual after all and it makes your code much clearer and easier to follow by other developers.
3,167,183
3,167,503
System.TypeLoadException when using a vector as argument in a method
I have a class Param.cpp which is a set of parameters for the main class Model.cpp. I create an instance of Param.cpp in a C# file using a graphic interface. It works great, I can see in debug that the param has a PropList containing one element - in my example. My Model class has a function BuildModel(Param param) which set the model parameters. When I call this method in the C# file, at this very moment, the PropList disappears, and I got System.TypeLoadException on all its parameters when I open the PropList tree in locals parameters. Nothing is being done except calling it in a method. I hope someone understand this, that would be great!
Look at the exception's InnerException property. That tells you what really went wrong. If that doesn't help, update your question with its message and stacktrace.
3,167,188
3,167,255
Is casting could lead to a issue?
In one RTOS, i'm debugging one issue which is, program is crashing one point always when it send a 8-bit value (Lets call it 'Int8 rogue_int')to a function (lets call it 'Infected( Int16 )' ) whose definition is taking that variable as 16-bit variable. Before entering to that last function Infected(..), value for 'rogue_int' is proper but as soon as it enters to Infected(..) fn it is having some junk value and it hits a assert. normally my thinking is casting 8-bit to 16-bit variable should not result any issue but there could not be any other problem i can not find in between that could corrupt the static memory. i have given it much thought and i came up some theory that since this is hitting assert after some time (lets say 2-3 hrs of execution) so initially static memory is nice and clean and not much grown towards heap but as it grows then during casting 8 bit to 16 bit, it takes 8 bits from real no (which is rogue_int here) but it takes additional 8-bits of memory chunk that was just assigned to this variable to make it 16-bit. this newly added 8-bit could be corrupted and that could make complete no as invalid. My question here is that, does my 2nd para above make any sense to C++ experts?? Does casting 8 to 16 is always safe (I was thinking it is always safe that is why i'm not submitted my thoughts to higher up)?? if you think i'm wrong then please suggest alternative that could lead to this prob. (assert always seen hit ONLY at one point in function 'Infected(..)'... not any any other place)
I'm not a C++ expert, but what you've described does not make any sense. Casting from an 8-bit type to a 16-bit type cannot result in uninitialized memory being incorporated into to the value--upcasts of this type have narrow, strictly-specified semantics, and the compiler can't just grab an extra adjacent byte and add it to your value. What you're describing sounds like a buffer overflow from some other part of the program. I suggest using a validation tool like valgrind (Linux) or AppVerifier (Windows) to check your memory accesses and find the buffer overflow at its source.
3,167,272
3,167,372
How does c++ std::vector work?
How does adding and removing elements "rescale" the data? How is the size of the vector calculated (I believe it is kept track of)? Any other additional resources to learn about vectors would be appreciated.
In terms of sizing, there are two values of interest for a std::vector: size, and capacity (accessed via .size() and .capacity()). .size() is the number of elements that are contained in the vector, whereas .capacity() is the number of elements that can be added to the vector, before memory will be re-allocated. If you .push_back() an element, size will increase by one, up until you hit the capacity. Once the capacity is reached, most (all?) implementations, re-allocate memory, doubling the capacity. You can reserve a capacity using .reserve(). For example: std::vector<int> A; A.reserve(1); // A: size:0, capacity:1 {[],x} A.push_back(0); // A: size:1, capacity:1 {[0]} A.push_back(1); // A: size:2, capacity:2 {[0,1]} A.push_back(2); // A: size:3, capacity:4 {[0,1,2],x} A.push_back(3); // A: size:4, capacity:4 {[0,1,2,3]} A.push_back(4); // A: size:5, capacity:8 {[0,1,2,3,4],x,x,x} Reallocations of memory would occur at lines 4, 5, and 7.
3,167,280
3,167,310
strtok problem in visual c++
I am trying the strtok in visual c++, but it seems not working. This not my first time using strtok, but i just counldnt figure out what is wrong with it. the code is quite simple. in main cout<<getLevels("/'Group'/'Channel1'")<<endl; in getLevels() int getLevels(char * fullPath){ int level=0; char *nextToken; char * pch=strtok_s(fullPath, "/", &nextToken);// broken at here while(pch!=NULL){ level++; cout<<level<<":"<<pch<<endl; pch=strtok_s(NULL, "/",&nextToken); } return level; } it breaks at line char * pch=strtok_s(fullPath, "/", &nextToken); with error: Unhandled exception at 0x10273de8 (msvcr100d.dll) in tdmsTest.exe: 0xC0000005: Access violation writing location 0x0041c840. and the cursor is pointing to this line in strtok_s.ini for ( ; *str != 0 ; str++ ) { if (map[*str >> 3] & (1 << (*str & 7))) { *str++ = 0; // pointing here break; } } i tried it in strtok() instead of strtok_s() before, but it has the same problem. can any one tell me what is wrong with my code?
Strtok is trying to split the string by inserting nulls in place of the tokens. I'd guess that the literal "/'Group'/'Channel1'" is stored as a constant and can't be modified. Try removing the "Enable String Pooling (/GF)" flag from the compiler options.
3,167,477
3,167,528
Taking the Address of a Temporary, with a Twist
I have a function address_of, which returns a Pointer (encapsulating a shared_ptr) to its argument. address_of needs to work on both lvalues and rvalues, so there are two versions of address_of: one accepting a reference and the other accepting an rvalue reference. Since taking the address of a temporary is a Bad Thing™, the rvalue version of address_of needs to perform a move-construct in order for the Pointer to actually own something. The implementation is straightforward: template<class T> inline Pointer address_of(T& value) { return Pointer(&value); } template<class T> inline Pointer address_of(T&& value) { return Pointer(new T(std::move(value))); } And taking the address of a temporary works as expected: Pointer p = address_of(Derived()); But when I test with the following code: Base* object = new Derived(); Pointer p = address_of(*object); GCC complains that the call to address_of is ambiguous: error: call of overloaded ‘address_of(Base&)’ is ambiguous note: candidates are: Pointer address_of(T&) [with T = Base] note: Pointer address_of(T&&) [with T = Base&] I was under the impression that unary * always returns an lvalue, in which case the rvalue version shouldn't even be considered. What exactly is going on here?
The problem is caused by reference decay: (correct term is "reference collapse") template < typename T > void f(T && t) { .... } int x; f(x); // what is f()? The answer to the question in the code is that f() is: void f(T& && t) { .... } Which because of reference decay turns into this: void f(T& t) { .... } As you can expect, this will of course be ambiguous with anything defined as: template < typename T > void f(T & t) { .... } This might work (fixed version): #include <type_traits> #include <utility> template < typename T > struct pointer { pointer(T& t) {} pointer(T&& t) {} }; template < typename T > pointer<typename std::remove_reference<T>::type> address_of(T && t) { return pointer<typename std::remove_reference<T>::type>(std::forward<T>(t)); } int main() { int x = 5; pointer<int> o = address_of(x); pointer<int> p = address_of(5); } The reason being that this reference decay stuff only happens in functions that are templated on T. In this case your pointer class is, but the constructors are not actually templates themselves and so T& is never a valid T for the T&& version. The first version still had the same problem as your code since address_of was just using T as the template parameter for pointer. We actually need the raw type.
3,167,554
3,177,752
Global symbol not in symtab
I'm getting the following error when trying to output a stack trace through GDB: global symbol 'object' found in a.cpp psymtab but not in symtab What does this error mean exactly, and is it caused by my code or is it a GDB issue?
I think it's gdb issue. Try gdb 7.0 or 7.1
3,167,560
3,167,600
Passing std::string in a library API
We are currently building an API for a certain library. Part of the interface requires the library to get and return to the user classes such as vector and string. When trying to simulate use of the library in a simple scenario, in debug mode the system crush when delivering a string as an input. I believe there is a different representation of the string class in debug or release mode. Then our library assumes to receive a certain representation, read a data member incorrectly and crush along the way. So what is the best way method to transferring STL objects in an API. The target OS is windows XP compiled with MSVC 8, although the library user will use windows their compiler might (and probably will) be different Ideas we had so far: Change string to char* - But then developers might be baffled with the responsibility of releasing the memory. Use our own version of String – I don't want to develop another private implementation of string. Release to the user debug version and release version. Ask people on Stack overflow for some option we miss or don’t understand, or just hear from their experience - done.
You should avoid passing STL objects between different binary modules. For string, you have to rely on const char* for read only parameter and char*, <buffer size> for input parameters... For vectors, it could be a bit more difficult especially if you have to change the content of the vector... About your ideas: You are right, but the convention usually is that you can't store the passed pointer (you have to do your local copy). At the end you would have the same issue unless you have the same binary representation on debug and release version of your implementation. This may be harmful if you use different versions/implementation of STL in the two binary modules (unless you are sure that the library user will use the same STL).
3,167,565
3,167,726
Declaring "friend" functions fails under Visual Studio 2008
I am trying to declare a global function as a "friend" of a class: namespace first { namespace second { namespace first { class Second { template <typename T> friend T ::first::FirstMethod(); }; } } } When I compile this code under Visual C++ 2008 I get: error C3254: 'first::second::first::Second' : class contains explicit override 'FirstMethod' but does not derive from an interface that contains the function declaration error C2838: 'FirstMethod' : illegal qualified name in member declaration If I use template <typename T> friend T first::FirstMethod(); instead I get: error C2039: 'FirstMethod' : is not a member of 'first::second::first' What is the appropriate way of declaring friend functions?
You have hit my quiz by accident - the sequence T ::first:: ... is interpreted as a single name. You need to put some token in between the colons and T. Solution is presented in the linked question too. Notice that in any case you first have to declare the function designated by a qualified name in its respective namespace, too. Edit: There are different solutions for the syntax problem template <typename T> friend T (::first::FirstMethod)(); template <typename T> T friend ::first::FirstMethod(); If you often need to refer to the outer namespace and have problems with this syntax, you can introduce a namespace alias namespace first { namespace outer_first = ::first; class Second { template <typename T> friend T outer_first::FirstMethod(); }; }
3,167,661
3,167,835
Picking a front-end/interpreter for a scientific code
The simulation tool I have developed over the past couple of years, is written in C++ and currently has a tcl interpreted front-end. It was written such that it can be run either in an interactive shell, or by passing an input file. Either way, the input file is written in tcl (with many additional simulation-specific commands I have added). This allows for quite powerful input files (e.g.- when running monte-carlo sims, random distributions can be programmed as tcl procedures directly in the input file). Unfortunately, I am finding that the tcl interpreter is becoming somewhat limited compared to what more modern interpreted languages have to offer, and its syntax seems a bit arcane. Since the computational engine was written as a library with a c-compatible API, it should be straightforward to write alternative front-ends, and I am thinking of moving to a new interpreter, however I am having a bit of a time choosing (mostly because I don't have significant experience with many interpreted languages). The options I have begun to explore are as follows: Remaining with tcl: Pros: - No need to change the existing code. - Existing input files stay the same. (though I'd probably keep the tcl front end as an option) - Mature language with lots of community support. Cons: - Feeling limited by the language syntax. - Getting complaints from users as to the difficulty of learning tcl. Python: Pros: - Modern interpreter, known to be quite efficient. - Large, active community. - Well known scientific and mathematical modules, such as scipy. - Commonly used in the academic Scientific/engineering community (typical users of my code) Cons: - I've never used it and thus would take time to learn the language (this is also a pro, as I've been meaning to learn python for quite some time) - Strict formatting of the input files (indentation, etc..) Matlab: Pros: - Very power and widely used mathematical tool - Powerful built-in visualization/plotting. - Extensible, through community submitted code, as well as commercial toolboxes. - Many in science/engineering academia is familiar with and comfortable with matlab. Cons: - Can not distribute as an executable- would need to be an add-on/toolbox. - Would require (?) the matlab compiler (which is pricy). - Requires Matlab, which is also pricy. These pros and cons are what I've been able to come up with, though I have very little experience with interpreted languages in general. I'd love to hear any thoughts on both the interpreters I've proposed here, if these pros/cons listed are legitimate, and any other interpreters I haven't thought of (e.g.- would php be appropriate for something like this? lua?). First hand experience with embedding an interpreter in your code is definitely a plus!
I was a strong Tcl/Tk proponent from pre-release, until I did a largish project with it and found how unmaintainable it is. Unfortunately, since prototypes are so easy in Tcl, you wind up with "one-off" scripts taking on lives of their own. Having adopted Python in the last few months, I'm finding it to be all that Tcl promised and a whole lot more. As many a Python veteran can tell you, source indentation is a bother for the first hour at most and then it seems not a hindrance but affirmatively helpful. Incidentally Tcl's author, John Ousterhout was alternately praised and panned for writing a language that forced the One True Brace Style on Tcl coders (I was 1TBS so it was fine by me). The only Tcl constructs that aren't handled well by Python are arbitrary eval "${prefix}${command} arg" constructs that shouldn't be used in Tcl anyway but are and the uplevel type statements (which were a nice idea but made for some hairy code). Indeed, Python feels a little antagonistic to dynamic eval but I think that is a Good Thing. Unfortunately, I've yet to come along with a language that embraced its GUI as well as Tcl/Tk; Tkinter does the job in Python but it hurts. I cannot speak to Matlab at all. With a few months of Python under my belt, I'd almost certainly port any Tcl program that is in ongoing development to Python for purposes of sanity.
3,167,796
3,167,816
Transfering code to a sub function
I have some code within one function that I want to separate into its own function. I want to do this with as little modification to the original code as possible. Below I have written a noddy example where the code segment is simply "x += y". I want to take out that code and put it in its own function. With C I have to do this by changing y in to a pointer and then working with that. But I remember reading somewhere (now forgotten) that there is some trick in C++ where I can pass the variable in a way that the code can remain as "x += y". FYI: I want to do this process (and perhaps reverse it later) as I am doing some callgraph profiling. void main() { int x = 2; int y = 5; #if KEEP_IN_BIG_FUNC x += y; #else // put in sub function sub_function(y,&x); #endif printf("x = %d\n",x); // hopefully will print "7" } void sub_function(int y,int *x) { *x += y; }
I believe what you're looking for is a reference. In your example, the function sub_function would then look like this: void sub_function(int y, int& x) { x += y; } and you'd call it this way: sub_function(y, x);
3,168,056
3,168,092
va_arg returning the wrong argument
With the following code va_arg is returning garbage for the second and third pass through vProcessType. // va_list_test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <tchar.h> #include <cstdarg> #include <windows.h> void processList(LPTSTR str, ...); void vProcessList(LPTSTR str, va_list args); void vProcessType(va_list args, int type); int _tmain(int argc, _TCHAR* argv[]) { LPTSTR a = TEXT("foobar"); int b = 1234; LPTSTR c = TEXT("hello world"); processList(TEXT("foobar"), a, b, c); return 0; } void processList(LPTSTR str, ...) { va_list args; va_start(args, str); vProcessList(str, args); va_end(args); } void vProcessList(LPTSTR str, va_list args) { vProcessType(args, 1); vProcessType(args, 2); vProcessType(args, 1); } void vProcessType(va_list args, int type) { switch(type) { case 1: { LPTSTR str = va_arg(args, LPTSTR); printf("%s", str); } break; case 2: { int num = va_arg(args, int); printf("%d", num); } break; default: break; } } Is passing a va_list thing not allowed in this way? The first call to va_arg inside vProcessType returns the expected string. The second and third time through this function it returns a pointer to the start of the first string, instead of the values expected. If I hoist the va_arg call to vProcessList, everything seems to work fine. It only seems when I pass a va_list through a function that I'm getting this behaviour.
You're passing the same va_list each time to vProcessType() - in each call to vProcessType() you're acting on the first va_arg in the list. So you're always dealing with the TEXT("foobar") parameter when calling vProcessType(). Also note that the standard has this to say about passing a va_list to another function: The object ap [of type va_list] may be passed as an argument to another function; if that function invokes the va_arg macro with parameter ap, the value of ap in the calling function is indeterminate and shall be passed to the va_end macro prior to any further reference to ap. A foot note in the standard indicate that it's perfect OK to pass a pointer to a va_list, so what you might want to do is have vProcessType() take a pointer to the va_list: void vProcessType(va_list* pargs, int type);
3,168,076
3,168,191
Will a class recall its constructor when pushed in a std::vector?
if for example I do: FOO foo; foovect.push_back(foo); where FOO is a class with a default constructor. Will the constructor be called only when foo is put on the stack, or is it called again when pushed into the std::vector? Thanks I'm doing: OGLSHAPE::OGLSHAPE(void) { glGenBuffersARB(GL_ARRAY_BUFFER_ARB,&ObjectVBOInt); }
FOO foo; would call the constructor. foovect.push_back(foo); would call the copy constructor. #include <iostream> #include <vector> class FOO { public: FOO() { std::cout << "Constructor" << std::endl; } FOO(const FOO& _f) { std::cout << "Copy Constructor" << std::endl; } }; int main() { FOO foo; std::vector<FOO> foovect; foovect.push_back(foo); } Output for this: Constructor Copy Constructor
3,168,158
3,168,236
strange file reading problem in c++: fread()
I have a very strange problem when reading a binary file. void metaDataProcess(FILE *f){ unsigned __int32 obLength; unsigned __int32 numProp; char* objPath; unsigned __int32 rawDataIndex; int level; fread(&obLength,sizeof(obLength),1,f); objPath=new char[obLength]; cout<<"i am at"<<ftell(f)<<endl; fread(&objPath,sizeof( char),obLength,f); objPath[obLength]='\0'; cout<<"i am at"<<ftell(f)<<" the object path is "<<objPath<<endl; level=getOrCreateNode(objPath); fread(&rawDataIndex,sizeof(rawDataIndex),1,f); the "objPath" didnt get what is expected in that location. In 010 editor, for that location it is '/', but i read it as '>'. it is quite strange, since from the print out value of ftell, it is the correct position and the value read before and after that are got expected value(obLength=1; and next value rawDataIndex==4294967295). how come i got '>' when i expceted '/'. i tried fread(&objPath,sizeof(unsigned char),obLength,f); fread(&objPath,1, obLength,f); they are all '>'; can anyone help me with it? thanks
objPath=new char[obLength + 1]; cout<<"i am at"<<ftell(f)<<endl; fread(objPath,sizeof( char),obLength,f); objPath[obLength]='\0';
3,168,238
3,168,263
const reference must be initialized in constructor base/member initializer list
I am trying to block access to the default constructor of a class I am writing. The constructor I want others to use requires a const reference to another object. I have made the default constructor private to prevent others from using it. I am getting a compiler error for the default constructor because the const reference member variable is not initialized properly. What can I do to make this compile? class CFoo { public: CFoo(); ~CFoo(); }; class CBar { public: CBar(const CFoo& foo) : fooReference(foo) { } ~CBar(); private: const CFoo& fooReference; CBar() // I am getting a compiler error because I don't know what to do with fooReference here... { } };
don`t declare default constructor. It is not available anyway (automatically that it's) if you declare your own constructor. class CBar { public: CBar(const CFoo& foo) : fooReference(foo) { } private: const CFoo& fooReference; }; fairly comprehensive explanation of constructors can be found here: http://www.parashift.com/c++-faq-lite/ctors.html
3,168,299
3,168,531
non-resizeable vector/array of non-reassignable but mutable members?
Is there a way to make a non-resizeable vector/array of non-reassignable but mutable members? The closest thing I can imagine is using a vector<T *> const copy constructed from a temporary, but since I know at initialization how many of and exactly what I want, I'd much rather have a block of objects than pointers. Is anything like what is shown below possible with std::vector or some more obscure boost, etc., template? // Struct making vec<A> that cannot be resized or have contents reassigned. struct B { vector<A> va_; // <-- unknown modifiers or different template needed here vector<A> va2_; // All vector contents initialized on construction. Foo(size_t n_foo) : va_(n_foo), va2_(5) { } // Things I'd like allowed: altering contents, const_iterator and read access. good_actions(size_t idx, int val) { va_[idx].set(val); cout << "vector<A> info - " << " size: " << va_.size() << ", max: " << va_.max_size() << ", capacity: " << va_.capacity() << ", empty?: " << va_.empty() << endl; if (!va_.empty()) { cout << "First (old): " << va_[0].get() << ", resetting ..." << endl; va_[0].set(0); } int max = 0; for (vector<A>::const_iterator i = va_.begin(); i != va_.end(); ++i) { int n = i->get(); if (n > max) { max = n; } if (n < 0) { i->set(0); } } cout << "Max : " << max << "." << endl; } // Everything here should fail at compile. bad_actions(size_t idx, int val) { va_[0] = va2_[0]; va_.at(1) = va2_.at(3); va_.swap(va2_); va_.erase(va_.begin()); va_.insert(va_.end(), va2_[0]); va_.resize(1); va_.clear(); // also: assign, reserve, push, pop, .. } };
What you're asking is not really possible. The only way to prevent something from being assigned is to define the operator = for that type as private. (As an extension of this, since const operator = methods don't make much sense (and are thus uncommon) you can come close to this by only allowing access to const references from your container. But the user can still define a const operator =, and you want mutable objects anyways.) If you think about it, std::vector::operator [] returns a reference to the value it contains. Using the assignment operator will call operator = for the value. std::vector is completely bypassed here (except for the operator[] call used to get the reference in the first place) so there is no possibility for it (std::vector) to in any way to override the call to the operator = function. Anything you do to directly access the members of an object in the container is going to have to return a reference to the object, which can then be used to call the object's operator =. So, there is no way a container can prevent objects inside of it from being assigned unless the container implements a proxy for the objects it contains which has a private assignment operator that does nothing and forwards other calls to the "real" object, but does not allow direct access to the real object (though if it made sense to do so, you could return copies of the real object).
3,168,607
3,168,740
C++ boost template parameter traits
I believe I had seen macro in boost that recovers template template parameters, for example: template<class> struct parameters; #define parameters(T) template<class A> \ struct parameters<T<A> > { typedef A type1; }; is there one like this, or am I wrong? Thank you
delctype support in C++0x makes this fairly trivial to implement: template<template <typename> class Parent, typename Param1> Param1 get_type(Parent<Param1> const &input) { return Param1(); } SomeTpl<int> some_obj; delctype(get_type(some_obj)) x; (Though you need a separate get_type definition for templates with 2, 3, 4, etc parameters.) Unfortunately, I don't think there is a way to do this without decltype, because to do so required automatic the type-deduction provided by function templates (which is not available for class templates) and so there's no way to make a typedef that way. I don't know off-hand if boost has anything like this already, but if they do it will still require your compiler to support decltype, but since decltype is so new there is not a lot of stuff in boost that uses it yet (though there is some).
3,168,675
3,181,523
DOS-reported error: Bad file number
I have a batch file that tries to compile a static library using Borland C++ Builder 6.0 It is called from Borland make (makefile created with bpr2mak) which is called from a .bat file (used to compile the whole project with Visual Studio and some Borland C++ Builder legacy projects), which is called from a bash shell script running inside Cygwin. When I run the .bat file directly from a Cygwin shell, it runs OK, but when its being run from a Program calling cygwin with Boost::Process::launcher I'm getting this error: C:\ARQUIV~1\Borland\CBUILD~1\Bin\..\BIN\TLib /u bclibs.lib @MAKE0000.@@@ DOS-reported error: Bad file number TLIB 4.5 Copyright (c) 1987, 1999 Inprise Corporation opening 'MAKE0000.@@@' ** error 1 ** deleting bclibs.lib It's a complicated scenario, but this Program which calls cygwin is run whenever we need to build our software package which needs to be build for various Linux distos and Windows 32 and 64-bit. Note: It's the only Borland Project failing, the other compile just fine (it's the only static library using borland also, so it can be some problem with the TLib tool.
The problem was that TLib does not like to have his output redirected (seen here) without having an input pipe as well. Solved by creating an input pipe to in the Boost::Process::launcher using set_stdin_behavior
3,168,720
3,168,745
Portable way to use shared_ptr in GCC
GCC 4.1 uses the <tr1/memory> header and GCC 4.3 uses <memory> header, I need a portable way to use shared_ptr with GCC 4.3.2 and with GCC 4.2.1, is there any way to do that without checking GCC version macros or using external libraries like Boost ?
<tr1/memory> will still work with gcc 4.3. If you wan to support both versions, just use the tr1 name.
3,169,015
3,169,076
How exactly should I implement a shuffle or random-number algorithm for an array to display quotes in random order?
I already know there's answers for this kind of thing, but I don't really know how to implement them in my code. Also, I would like to refrain from using any more functions unless neccessary. Here's my code: int main() { unsigned seed; seed = 1; srand(seed); std::string starFox[8]; int x[8]; starFox[0] = "Do a barrel roll!"; starFox[1] = "Try a somersault!"; starFox[2] = "Use bombs wisely!"; starFox[3] = "Something is wrong with the G-diffuser"; starFox[4] = "Can't let you do that, Star Fox"; starFox[5] = "Hey Einstein, I'm on your side"; starFox[6] = "Whoa! help me!"; starFox[7] = "Daddy screamed REAL good before he died!"; for(int i=0; i<8; i++) { int y = 0 + rand() % 8; x[i] = y; if (x[i-1]!=y || x[i-2]!=y || x[i-3]!=y || x[i-4]!=y || x[i-5]!=y || x[i-6]!=y || x[i-7]!=y) {//now I need to make a statement that makes sure each number appears once. std::cout << starFox[y] << "\n";} } std::cout << '\n'; return 0; } So, what should I alter about this code to make it generate random numbers each time the program executes?
You're seeding the same value every time you run, so you'll always get the same pseudo-random sequence. Try this: srand(time(0));
3,169,221
3,170,479
Qt C++, Eclipse (on Win 7) - project build failed with "unresolved reference to _Unwind_Resume" error
I've got Windows 7 64-bit and I just installed Qt (open-source, version 2010.04) and integrated it into Eclipse (CDT, version Helios). Everything seemed to went fine, I added paths to both Qt and mingw32 compiler and configured Qt by running configure.exe. The integration with Eclipse works fine too. However, I've problem with the first simple project. If I create the "Qt Gui Project" and try to immediately build it, the build fails with following errors: mingw32-make: *** [release] Error 2 mingw32-make[1]: *** [release\pokus.exe] Error 1 undefined reference to `__gxx_personality_v0' undefined reference to `_Unwind_Resume' I tried to use also Debug configuration, but the build failed too, with the same errors. However I don't expect Debug configuration to work since I haven't built debug libraries. (in fact I'm not sure how to do this - when I installed Qt few years ago, there was a batch file to do it, but now I couldn't find it.) As I said before, I have paths to both mingw32 and Qt correctly added to environment path, but don't know what else to check or do... Thanks for all suggestions... Edit: I found that these errors can be caused by accidentaly using gcc instead of g++. I don't think this is the case, if I look at Project Properties -> C/C++ Make Project -> Environment tab, I can see that value of "QMAKESPEC" variable is "win32-g++", so I hope it means g++ is used for the project.
Solved - problem was with the bad version of MinGW, I had the current version (5.1.6.) installed. I uninstalled it and replaced with version 4.4.0, downloaded from Qt website (http://get.qt.nokia.com/misc/MinGW-gcc440_1.zip) and everything is fine now.
3,169,392
3,173,210
How to optimize this algorithm
I need help with making this bit of code faster: UnitBase* Formation::operator[](ushort offset) { UnitBase* unit = 0; if (offset < itsNumFightingUnits) { ushort j = 0; for (ushort i = 0; i < itsNumUnits; ++i) { if (unitSetup[i] == UNIT_ON_FRONT) { if (j == offset) unit = unitFormation[i]; ++j; } } } else throw NotFound(); return unit; } So, to give some background, I have this class Formation which contains an array of pointers to UnitBase objects, called UnitFormation. The UnitBase* array has an equally sized array of numbers that indicate the status of each corresponding UnitBase object, called UnitSetup. I have overloaded the [] operator so as to return only pointers to those UnitBase objects that have a certain status, so if I ask for itsFormation[5], the function does not necessarily return UnitFormation[5], but the 5th element of UnitFormation that has the status UNIT_ON_FRONT. I have tried using the code above, but according to my profiler, it is taking way too much time. Which makes sense, since the algorithm has to count all the elements before returning the requested pointer. Do I need to rethink the whole problem completely, or can this be made somehow faster? Thanks in advance.
I have redesigned the solution completely, using two vectors, one for units on the front, and one for other units, and changed all algorithms such that a unit with a changed status is immediately moved from one vector to another. Thus I eliminated the counting in the [] operator which was the main bottleneck. Before using the profiler I was getting computation times of around 5500 to 7000 ms. After looking at the answers here, 1) I changed the loop variables from ushort to int or uint, which reduced duration by ~10%, 2) I did another modification in a secondary algorithm to reduce the duration by a further 30% or so, 3) I implemented the two vectors as explained above. This helped reduce the computation time from ~3300 ms to ~700 ms, another 40%! In all that's a reduction of 85 - 90%! Thanks to SO and the profiler. Next I'm going to implement a mediator pattern and only call the updating function when required, perhaps oozing out a few more ms. :) New code that corresponds to the old snippet (the functionality is completely different now): UnitBase* Formation::operator[](ushort offset) { if (offset < numFightingUnits) return unitFormation[offset]->getUnit(); else return NULL; } Much shorter and more to the point. Of course, there were many other heavy modifications, most important being that unitFormation is now a std::vector<UnitFormationElement*> rather than simply a UnitBase**. The UnitFormationElement* contains the UnitBase* along with some other vital data that was hanging around in the Formation class before.
3,169,709
3,169,743
C++ project reference in a C# project in visual studio 2008
Is is possible to reference a C++ project in a C# Project? I've tried adding a reference in the c# project to that C++ one but I get an error saying "A reference to could not be added"
If your C++ project is a native (standard C++) project, then no. If it's a managed project, you can add a reference to it. For native code, you'll need to use P/Invoke to access functions within the C++ DLL.
3,169,895
3,169,899
C++ inheritance public and private?
Is it possible to inherit both or all parts of a class (other than private) in C++? class A { } clas B : ...? { }
If you're asking whether you can make private members visible to derived classes, the answer is no - that's why they are private. Use protected members in the base class if you want derived classes to be able to access them.
3,169,905
3,169,976
How can I do this for cubic beziers?
Right now i'm creating polygons with bezier handles. It's working well, except right now I always do something like this: for(float i = 0; i < 1; i += 0.04) { interpolate A, a.handle to B.handle, B at time i } The problem is no matter how short the distance or long the distance between point A and B, it always produces the same amount of points. How could I do it so it always looks good but only interpolates as much as it has to. Ex: if Distance(A,B) is 40, then it may only subdivide like 15 times but then if Distance(A,B) is 20 it may only subdivide 7 times etc. How could I do this as a function of quality ex: float GetThreshold(float distance, float quality) { } Or something like that. Thanks
What you probably want to investigate is an adaptive stepping algorithm. The basic concept is that you want more points where the radius of curvature is small (i.e.- sharp bends), and fewer points where the radius of curvature is large (i.e.- more straight). There is a great article here, that shows a good adaptive stepping algorithm. I used it a couple of years ago for some bezier curve work I was doing.
3,170,093
3,182,197
Palm OS 5.4 (Garnet) IR programming (Use CIR on IrDa port)
I would like to create an open source alternative to Palm OS programs like Noviiremote and Omniremote. I need to access the IR port of my Tungsten E2 and use it to transmit remote control type signals (I assume NEC and/or RC-5). Are there any libraries out there I could use? If not, how do I go about transmitting raw codes via the IrDa port? I am new to Palm OS programming, but I am fairly familiar with C++/C#. I read the programming companion and reference, and they did not seem to cover this. Any help would be great. Thanks in advance.
Okay, I think I am asking the wrong question, so I am going to mark this answered and ask a new one. What I really need is a way to translate RC-5 to serial bits, which I think is possible, since I can use raw IR. New question is here: https://stackoverflow.com/questions/3182235/sending-rc-5-ir-signals-serially-using-raw-ir-on-garnet
3,170,236
3,170,248
How can I "double overload" an operator?
If I have a database-like class, and I want to do something like this: object[1] == otherObject; How do I "double overload" operator[] and operator==?
object[1] returns an object of someType. You need to overload operator== on that someType.
3,170,295
3,170,303
Where can I find the implementation for std::string
I am looking for the code for the c++ string class. What header is it implemented in?
There is no single implementation for std::string. But you can find your particular implementation in the <string> header. On my system it can be found here: /usr/lib/gcc/x86_64-pc-linux-gnu/4.5.0/include/g++-v4/bits/basic_string.h and /usr/lib/gcc/x86_64-pc-linux-gnu/4.5.0/include/g++-v4/bits/basic_string.tcc On a Debian-based system: ~$ locate basic_string.tcc /usr/include/c++/4.5/bits/basic_string.tcc /usr/include/c++/4.6/bits/basic_string.tcc ~$ locate basic_string.h /usr/include/c++/4.5/bits/basic_string.h /usr/include/c++/4.6/bits/basic_string.h ~$ Generally, you are going to be looking for the basic_string template, since std::string is just a specialization of that.
3,170,319
6,438,608
boost::asio fails to close TCP connection cleanly
I am trying to implement a simple HTTP server. I am able to send the HTTP response to clients but the issue is that on Firefox I get "Connection Reset" error. IE too fails, while Chrome works perfectly and displays the HTML I sent in the response. If I telnet to my server then I get "Connection Lost" message, just after the response. So, from this I concluded that connection is not getting closed properly. Below are important snippets from the code. class TCPServer - This initiates the acceptor (boost::asio::ip::tcp::acceptor) object. void TCPServer::startAccept() { TCPConnection::pointer clientConnection = TCPConnection::create(acceptor.io_service()); acceptor.async_accept(clientConnection->getSocket(), boost::bind(&TCPServer::handleAccept, this, clientConnection, boost::asio::placeholders::error)); } void TCPServer::handleAccept(TCPConnection::pointer clientConnection, const boost::system::error_code& error) { std::cout << "Connected with a remote client." << std::endl; if (!error) { clientConnection->start(); startAccept(); } } class TCPConnection - Represents a TCP connection to client. This extends - public boost::enable_shared_from_this<TCPConnection> TCPConnection::TCPConnection(boost::asio::io_service& ioService) : socket(ioService) { } TCPConnection::~TCPConnection(void) { std::cout << "TCPConnection destructor called." << std::endl; } TCPConnection::pointer TCPConnection::create(boost::asio::io_service& ioService) { return pointer(new TCPConnection(ioService)); } tcp::socket& TCPConnection::getSocket() { return socket; } void TCPConnection::start() { //ASSUME outBuf has some data.. It is initialized elsewhere. boost::asio::async_write(socket, boost::asio::buffer(*outBuf), boost::bind(&TCPConnection::handleWrite, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); std::cout << "Transferring " << outBuf->size() << " bytes." << std::endl; } void TCPConnection::handleWrite(const boost::system::error_code& err, size_t bytesTransferred) { std::cout << "Sent " << bytesTransferred << " bytes. Error:: " << err << std::endl; socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both); socket.close(); std::cout << "TCP connection closed." << std::endl; } One important point that I should mention is that since objects of TCPConnection are pointed to by 'smart pointers' so when execution of TCPConnection::handleWrite finishes then there are no pointers left to point at this TCPConnection object. So immediately after handleWrite finishes, the TCPConnection's destructor is called.
The server should not close the socket. If the server closes the socket and the client sends more data or there is data in the receive queue then the client will receive a RST causing this error. See http://cs.baylor.edu/~donahoo/practical/CSockets/TCPRST.pdf The HTTP server should read the entire client request or in the case of HTTP/1.1 the entire sequence of client requests. In this example it does not read any of the client request so there is data in the receive queue, so that the client receives a reset. Drain the socket with a sequences of async_reads before closing - probably in the future you will want to actually parse the client request ;-)
3,170,440
3,170,450
Cross platform recursive file list using C++?
What is the most efficient way to recursively list files in a specific directory and its subdirectories? Should I use the standard library, or use some third party? I want this because I use v8 as a JavaScript engine, and I want to execute all scripts in some directory (and its subdirectories). If there's any built-in way to do that in v8, great :) It should support Windows, Linux and OS X. Thanks.
For a generic cross-platform C++ solution, check out boost::filesystem
3,170,623
3,170,784
Secure data transfer over http with custom server
I am pretty new to security aspect of application. I have a C++ window service (server) that listens to a particular port for http requests. The http requests can be made via ajax or C# client. Due to some scope change now we have to secure this communication between the clients and custom server written in C++. Therefore i am looking for options to secure this communication. Can someone help me out with the possible approaches i can take to achieve this. Thanks Dpak
Given that you have an existing HTTP server (non-IIS) and you want to implement HTTPS (which is easy to screw up and hard to get right), you have a couple of options: Rewrite your server as a COM object, and then put together an IIS webservice that calls your COM object to implement the webservice. With this done, you can then configure IIS to provide your webservice via HTTP and HTTPS. Install a proxy server (Internet Security and Acceleration Server or Apache with mod_proxy) on the same host as your existing server and setup the proxy server to listen via HTTPS and then reverse proxy the requests to your service. The second option requires little to no changes to your application; the first option is the better long-term architectural move.
3,171,241
3,172,258
What do I call a "normal" variable?
int* p; int& r; int i; double* p2; double& r2; double d; p and p2 are pointers, r and r2 are references, but what are i and d? (No, I am not looking for the answer "an int and a double") I am looking for a name to use for "normal" variables, setting them apart from pointers and references. I don't believe that such a name doesn't exist (after all, I can't be the first one who wants to distinguish them from pointers and references. I do have the feeling that it's something really easy and I'm just missing it here. Who knows what to call "normal" variables? Additional info I am looking for a name that can refer to anything but references and pointers, so including classes. The whole same story could be held when the following was included as well: MyClass* p3; MyClass& r3; MyClass c; I am not looking for a way to refer to i, a way to refer to d and a way to c. I am looking for a way to refer to the group (of non-references, non-pointers) which i, d and c are part of.
Value types (value variables) was my first thought, but it seems to make some people uncomfortable, so nonreferential types (nonreferential variables) works just as well: pointers and references are both "referential types" in the sense that they refer to another location, while ordinary value types do not.
3,171,418
3,184,000
V8 FunctionTemplate Class Instance
I have the following class: class PluginManager { public: Handle<Value> Register(const Arguments& args); Handle<ObjectTemplate> GetObjectTemplate(); }; I want the Register method to be accessible from JavaScript. I add it to the global object like this: PluginManager pluginManagerInstance; global->Set(String::New("register"), FunctionTemplate::New(pluginManagerInstance.Register)); It throws the following error: 'PluginManager::Register': function call missing argument list; use '&PluginManager::Register' to create a pointer to member I tried to do that, but it doesn't work either. And it's not correct, because I want it to call the Register method of the pluginManagerInstance. Except for making the Register method static or global, any ideas? Thanks.
You're trying to bind two things at once: the instance and the method to invoke on it, and have it look like a function pointer. That unfortunately doesn't work in C++. You can only bind a pointer to a plain function or a static method. So image you add a static "RegisterCB" method and register it as the callback: static Handle<Value> RegisterCB(const Arguments& args); ...FunctionTemplate::New(&PluginManager::RegisterCB)... Now where do you get the pluginManagerInstance from? For this purpose, most callback-registration apis in V8 have an additional "data" parameter that will get passed back to the callback. So does FunctionTemplate::New. So you actually want to bind it like this: ...FunctionTemplate::New(&PluginManager::RegisterCB, External::Wrap(pluginManagerInstance))... The data is then available through args.Data() and you can delegate to the actual method: return ((PluginManager*)External::Unwrap(args.Data())->Register(args); This can surely be made a little easier with some macro.
3,171,535
3,171,567
Standard C++ libraries headers on gnu gcc site
I want to browse the source code of gnu implementation of C++ standard libraries -- header files as well as the implementation. I have landed myself into: http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.4/index.html My first step was to look header file at: http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.4/a01376.html My question is that as per my understanding the typedeffed string sth like: typedef basic_string string; should have been present in string header, but I don't see one here. Questions: --in which file is the definition of string symbol? --I see that string header file includes lot many headers and if the typedeffed sring symbol is defined in one of these internal headers, is there a search bar something on this site thru which I can reach to the definition of a symbol straightway. (in case someone has already browsed stuff from this site before) Thanks, Jagrati
A lot of libstdc++ is implemented using only headers, but some parts of the STL, like std::basic_string, have compiled implementations. The declaration of template std::basic_string is located in /usr/include/c++/4.4.4/bits/basic_string.h (replace '4.4.4' with g++ -dumpversion) and the implementation is in /usr/include/c++/4.4.4/bits/basic_string.tcc. The actual typedef of std::string, std::wstring, etc. is in .../bits/stringfwd.h. If you needed to instantiate std::basic_string with other template parameters, for example, then you do something like: #include <bits/basic_string.tcc> template class std::basic_string<long>; The way that libstdc++ implements sets and maps (header-only) is kind of interesting, but also very complex because it uses a custom red-black tree implementation (_Rb_tree). The libstdc++ implementation of std::vector (also header-only) is more self-contained, so it's worth a glance in /usr/include/c++/4.4.4/bits/stl_vector.h to give you an idea of the internals of libstdc++. Another interesting file is .../bits/stl_algo.h, which contains the definitions of STL algorithms. Note: On Windows with MinGW, you'll find the libstdc++ headers in lib\gcc\mingw32\4.4.0\include\c++\bits of your MinGW installation, replacing '4.4.0' with g++ -dumpversion.
3,171,540
3,171,557
Long constructor initialization lists
How do you deal with them? I have some classes (usually classes that hold stats etc.) with some 20+ variable members, and the initialization lists end up very long, extending beyond the page width if I don't manually wrap around. Do you try and break down such classes or do you deal with this in some other way? It doesn't look very tidy, but sometimes I write the variables in the list on top of each other like so: myConstructor(var1, var2, var3, ..., varN) : member1(var1), member2(var2), member3(var3), ... memberN(varN)
extending beyond the page width Well, first off, you should probably decide on a page width and stick to it. Use auto line wrapping from your editor, if you want. Reading code that's greater than your window size is really difficult, especially for your coworkers using vi or emacs from terminals. Pick a page width and stick to it- this means wrapping these initializer lists onto multiple (possibly many) lines. Do you try and break down such classes? 20 is a lot of parameters, it probably deserves to be broken up. "God classes" are generally a code smell and indicate a refactoring is necessary. It doesn't automatically mean you should break things up, there are always exceptions to guidelines. But, definitely consider it as an option. When you declare them in the header file, do you (or could you) group them with comments? For example: // These next few parameters are for file IO and // These next parameters are for the widget, that will provide you a good template for which objects are looking to be abstracted. Overall really large classes indicate a lot of complicated state, and complicated state tends to cause bugs. You should, like with functions, prefer to keep them small and focused. {Your example code} I think is quite readable and "tidy", although it will probably be pretty long list. As I mentioned, to combat this, I'd consider breaking it up into smaller classes.
3,171,545
3,171,571
Creating different instances in a loop
I'll be writing a validator for a specific file format (the format itself is unimportant). There's a large set of documents that specify what every section of the format needs to look like, how the different parts relate and so on. Lots and lots of MUST's, SHALL's, SHOULD's, MAY's etc. The architecture I envision is as follows: load the document into memory/separate files on disk, and then run numerous validation "passes" on the document: every pass would check for the adherence to one and only one rule specified in the standard, and if the pass fails, an error message is printed to stdout. Every pass would be a separate class implementing a common interface and an instance of each pass would be created on the stack, run on the document and the Result collected (containing error ID, message, line/column number etc). The Results would then be looped over and messages printed out. A unit test could then be easily created for every pass. Now, I expect to eventually have hundreds of these "pass" classes. And every one of these would need to be instantiated once, run over the document, and the Result collected. Do you see where I'm going with this? How do I create all these different instances without having a 500 line function that creates each and every one, line by line? I'd like some sort of loop. I'd also like the new pass classes to somehow be "discovered" when created, so I don't have to manually add lines that instantiate those new classes. Thinking about it now, all this seems to remind me of unit testing frameworks...
C++ is a static language that lacks reflection, hence you will have to enumerate your classes one way or another, be it a map of class names to factory functions, an explicit function that creates them all, or cppunit-style "registration" (same as putting them in a static map). With that said, go with the simplest possible way that's easiest to change, and does not introduce too much needless work and boilerplate code: creating a list of them in a function. You are saying you will have hundreds of them "eventually", not now. By the time you have hundreds of them, your design will have changed completely. If instantiation of all of them is localised in one function, it will make it easier to change your (uniform) design to add validators that depends on the state of previous validators, add arguments to validator constructors, or replace a simple list of validators with some composite structure, like conditional validators (e.g. run X only if Y had certain result, or run Z if X and Y are enabled). Simple code like that is also easier to throw away if it is no longer fit for the task, as you only tend to get invested in a complicated designs and add kludges to it instead of throwing it away. :) When your codebase matures, you will know exactly what kind of arrangement you need, but for now, do the simplest thing that can possibly work. PS Use a file-local macro, if typing some_ptr<Foo> foo = new Foo() bothers you, macros aren't that dirty :) E. g. #define NEW_V(cls, ...) do {\ std::tr1::shared_ptr<Validator> v(new cls(__VA_ARGS__));\ lst.push_back(v);\ } while(0) ... std::list< std::tr1::shared_ptr<Validator> > CreateValidators() { std::list< std::tr1::shared_ptr<Validator> > lst; CREATE_V(Foo); CREATE_V(Bar); CREATE_V(Baz, "baz"); return lst; }
3,171,579
3,171,797
OpenGL: How much memory anisotropic filtered textures will use?
I'm curious, does the anisotropic texture filtering increase the memory usage? And how to calculate it?
AFAIK it doesn't, but it requires mipmaps, which increase the texture memory usage by 33%.
3,171,821
3,171,902
Using Autotools for a new shared library
What I want to do is to create a new shared library called libxxx that links against another shared library called libzzz, this shared library has an independent "pkg-config"-like tool, let's say it's called "zzz-config" which gives the cflags needed by the compilation phase when using the libzzz. What I want to do is: Create configure/makefile, etc.. using autotools like automake, autoconf, etc; It must use the zzz-config script cited above; It must generate automatic dependencies for sources; It must have a mode for building debug (with no optimization) and release (with optimizations) builds; The sources are in C++; It must target for a shared library; It must read sources for a src directory and put compiled files in another directory I've read almost all available tutorials for autotools but I was not able to figure a way to do that, if you can point some example would be very kindly. Thank you !
My suggestion is to use CMake instead of autotools. It's much easier to work with and it will also create platform-dependent projects to work with (i.e. Makefile-based projects, Visual Studio projects, Eclipse CDT projects, etc.). It will also create debug or release projects, depending on the CMAKE_BUILD_TYPE variable value. Creating the libxxx library is as simple as: add_library(libxxx SHARED ${LIBXXX_SOURCES}) where LIBXXX_SOURCES is a variable that holds the sources. Linking the two libraries is just as easy (see target_link_libraries): target_link_libraries(libxxx libzzz) To get the compilation flags from the zzz-config script you would use the execute_process command like so: execute_process(COMMAND ./zzz-config WORKING_DIRECTORY "<your_working_directory>" OUTPUT_VARIABLE ZZZ_FLAGS) Then you can set the CMAKE_C_FLAGS or the CMAKE_CXX_FLAGS variable to setup the required compilation flags.