question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,125,669
2,125,685
Use of unique on STL vector with a structure
In a programming task, I'm trying to ensure a particular vector contains only unique items. With primitive types, the operation is as simple as: vector<int> lala; lala.push_back(1); lala.push_back(99); lala.push_back(3); lala.push_back(99); sort(lala.begin(), lala.end()); // lala: 1, 3, 99, 99 lala.erase(unique(lala.begin(), lala.end()), lala.end()); // lala: 1, 3, 99 However, the problem is I'm not using int. But: typedef struct { int x; int y; int maxX; int maxY; int width; int height; int id; } Rect; bool SameRect(Rect first, Rect second) { return first.x == second.x && first.y == second.y && first.width == second.width && first.height == second.height && first.maxX == second.maxX && first.maxY == second.maxY; } //... vector<Rect> lala; //... sort(lala.begin(), lala.end()); lala.erase(unique(lala.begin(), lala.end(), SameRect), lala.end()); //... Doesn't really work. What did I done wrong? EDIT: With sth's advice, I implemented two sorting predicate for std::sort(): bool SortRect(const Rect &first, const Rect &second) { if (first.x < second.x) return true; if (first.x > second.x) return false; if (first.y < second.y) return true; if (first.y > second.y) return false; if (first.maxX < second.maxX) return true; if (first.maxX > second.maxX) return false; if (first.maxY < second.maxY) return true; if (first.maxY > second.maxY) return false; if (first.width < second.width) return true; if (first.width > second.width) return false; if (first.height < second.height) return true; if (first.height > second.height) return false; if (first.id < second.id) return true; if (first.id > second.id) return false; return false; } But I found that it has the same effect as: bool SortRect(const Rect &first, const Rect &second) { return first.x < second.x; } if SGI's documentation is anything to come by. The shorter, simple sorting predicate should work as well. My test has confirmed this (Although I have not try all possible combinations).
You also have to define a comparison function that should be used by sort() to sort the Rects. This comparison function should implement a strict weak ordering so that equal elements end up next to each other in the vector. If the vector is not sorted, unique() will not find the unsorted duplicate elements.
2,125,750
2,125,800
Must -read articles for C++ memory mangement
After reading "C++ Memory Management: From Fear to Triumph" series, I think they are must-read articles for memory management. I'd like to know what else must-read articles I shouldn't miss. Thanks!
Read and learn well about RAII idiom, Resource Acquisition Is Initialization from articles like the two below: Memory and Resource Management by Stephen C. Dewhurst Resource Acquisition is Initialization - Modern C++ Style - A Conversation with Bjarne Stroustrup, Part II
2,125,803
2,125,838
How do game events work?
I'v always wondered how this works. Does having more slow down the game? for example how would one represent checking if a car has flipped. It could be seen as: if (player.car.angle.y == 180) { do something } The parts that puzzle me is, when would the game check for it? The way I see it, every thing that can happen in the game seems to evolve an if. I'm just wondering how these are handled. Also, since the game runs through a loop, what if the car is flipped for more than 1 frame, would a Boolean really be used to check if the event has been fired Thanks
In most general terms, any object in an engine has a state - if it changes state (e.g. not flipped to flipped), that is a transition. From a transition you can fire an event or not, but as the transition does only occur when changing state the event won't be fired more then once. As for the conditions that trigger the transitions, they have to be coded somewhere of course. Sometimes they are more explicitly coded, but mostly they are parameterized so that scripts or some sort of configuration can change them easily. How it is implemented in the end differs broadly, it depends on the libraries that are used as well the engine design itself.
2,125,808
2,125,858
c++ overloaded method in derived class
I have the following question: Assume base class A with method: A& operator+(A& a) {...} I also have a derived class B which overloads (or at least it should so) this method: A& operator+(B& b) {...} The problem is that if i want to call something like: b + a (where b is of type B and a of type A) i get a compile error. (error C2679: binary '+' : no operator found which takes a right-hand operand of type 'A' (or there is no acceptable conversion)). Shouldnt that call the base class method? (it looks like it overrides the method..) If not, why? Is there a way to fix this (dont tell me to overload the method in B with A&) Sorry i dont give examples in formated text, but i dont know how to format it. Thanks in advance! PS Im using Visual studio 2010 beta.
No, it won't call the base class function. Class B has an operator+, it doesn't take the correct parameter, end of story. You can define operator+ as a free function, not in any class. Perhaps a friend, if it needs to access private data: A operator+(const A &lhs, const A &rhs) { ... } B operator+(const B &lhs, const B &rhs) { ... } Then b + a will call the first operator, as will a + b. b + b will call the second. Alternatively, you could "un-hide" the base class implementation, by putting this in class B: using A::operator+; it's probably best not to, though. Most operators work better as free functions, because then you get automatic conversions on both operands. C++ never performs conversions on the LHS of a member function call. Btw, operator+ almost certainly should return by value, not by reference, since an automatic (stack) variable no longer exists once the function returns. So the caller needs to be passed a copy of the result, not a reference to it. For this reason operator+ and inheritance aren't a great mix, although it can probably work as long as the caller knows what they're doing.
2,125,862
2,132,479
Virtual functions table offset
I would like to ask you on what does the offset of the table of virtual functions for a class depend? I mean, from what I've read it at least depends on compiler, but does it varies from class to class? Edit: by offset I mean the position of the table relative to the address of the owner object. Edit: example code: void **vtable = *((void***)(((char*)object)+offset)); int **ivtable=(int **)vtable; void* firstFunction = (void*) ivtable[0];
There is certainly a dependency on the exact class. Remember that C++ has multiple inheritance (MI). The consequence of MI is that a single object may have multiple base subobjects. Those of course cannot be at the same address. This also means that some base subobjects don't actually start at relative offset 0. Now, this MI introduces quite a bit of complexity with vtables: you inherit functions from multiple bases, at different offsets. For that reason it's quite common to use different vtable layouts for MI classes. On a related note, MI also means that not every pointer to an object is actually a pointer to the start of that object. It is quite likely that a SecondBase* pointer to a Derived object is offset by sizeof(FirstBase), i.e. points somewhere in the middle of the Derived object.
2,125,880
2,125,888
Convert float to std::string in C++
I have a float value that needs to be put into a std::string. How do I convert from float to string? float val = 2.5; std::string my_val = val; // error here
Unless you're worried about performance, use string streams: #include <sstream> //.. std::ostringstream ss; ss << myFloat; std::string s(ss.str()); If you're okay with Boost, lexical_cast<> is a convenient alternative: std::string s = boost::lexical_cast<std::string>(myFloat); Efficient alternatives are e.g. FastFormat or simply the C-style functions.
2,125,937
2,125,948
Equivalent of InterlockedIncrement in Linux/gcc
It would be a very simple question (could be duplicated), but I was unable to find it. Win32 API provides a very handy set of atomic operations (as intrinsics) such as InterlockedIncrement which emits lock add x86 code. Also, InterlockedCompareExchange is mapped to lock cmpxchg. But, I want to do that in Linux with gcc. Since I'm working 64-bit, it's impossible to use inline assembly. Are there intrinsics for gcc?
GCC Atomic Built-ins
2,126,068
2,126,074
Is it possible to automatically serialize a C++ object?
Is there something similar to Java/.NET serialization for C++?
Boost contains a serialization library. I haven't used it myself, but usually the boost libraries work quite well.
2,126,209
2,126,259
How to refrain from CS2512 correctly
Please help me with the following problem: I have the following classes: class ChemicalElement { private: std::string _name; void Init(const std::string& name); public: ChemicalElement(const std::string& name); ChemicalElement(const ChemicalElement& ce); }; class CombinationRule { private: ChemicalElement _ce1; ChemicalElement _ce2; void Init(const ChemicalElement& ce1, const ChemicalElement& ce2); public: CombinationRule(const ChemicalElement& ce1, const ChemicalElement& ce2); CombinationRule(const CombinationRule& rule); }; The implementation is obvious. I intended to initialize the CombinationRule using the Init method to minimize code duplication. Alas, if I do not use "member initialization list" in each constructor the compiler complains with "error C2512: 'ChemicalElement' : no appropriate default constructor available". Is there an elegant way to solve this error instead of using a default constructor or member initialization list? BTW: if there are any other problems in the classes definition please add it too. Since I'm revisiting C++ I want to be aware of them.
You should implement constructors of CombinationRule as follows so they will use appropriate constructors of ChemicalElement: CombinationRule::CombinationRule(const ChemicalElement& ce1, const ChemicalElement& ce2) : _ce1(ce1), _ce2(ce2) { ... } CombinationRule::CombinationRule(const CombinationRule& rule) : _ce1( rule._ce1 ), _ce2( rule._ce2 ) { ... }
2,126,338
2,126,575
Problem compiling C++ class
I am running a C++ program which uses a class from another .cpp file. The class only has a constructor. It works when I test it separately. The main program compiles,but when I run it, I have a bug in the constructor. Any one can think of any situation that could happen? Thanks. I guess I just run the code in terminal, and it is fine. But when I try to build a project in eclipse, it shows following code has multiple definition error: class model { public: int textures []; float vertices[][3]; float triangles[][13]; public: model(const char*); // constructor }; model::model(const char* filename) { error message is: multiple definition of `model::model(char const*)' any idea?
You need to split your code into a .h (header) and a.cpp (implementation) file and put: model::model(const char* filename) { in the latter. Or, rewrite your class so the definition of the constructor (and any other member functions) is inside the class in the header file: class model { ... model(const char*) { // constructor body here } };
2,126,380
2,126,468
Converting mysqlpp::String to C++ int
Ok, I'm relatively new to using the mysqlpp library that is used in Visual Studio to connect to a MySQL database and am having trouble trying to convert a vector of type mysqlpp::String to a vector of type int. Does anyone have any experience with mysqlpp and would mind helping me out a little? I've posted an example of what I'm basically trying to do below that appears in my code. Assume the vector futureItemsets is already populated and I just want to copy over the contents into an integer vector. Thanks for any help you can provide! vector<int> timeFrameItemsets; vector<mysqlpp::String> futureItemsets; for(int j = 0; j < static_cast<int>(futureItemsets.size()); j++) { timeFrameItemsets.push_back(futureItemsets[j]); }
mysqlpp::String has operator int() so your code snippet should work. What problem are you having with it? If you want to be more explicit, you can use mysqlpp::String's conv function: int i = futureItemsets[j].conv<int>(0); timeFrameItemsets.push_back(i);
2,126,421
2,126,429
How does this pointer arithmetic work?
#include <stdio.h> int main(void){ unsigned a[3][4] = { {2,23,6,7}, {8,5,1,4}, {12,15,3,9} }; printf("%u",*((int*)(((char*)a)+4))); return 0; } The output in my machine is the value at a[0][1] i.e 23.Could somebody explain how is this working ? Edit: Rolling Back to old yucky code,exactly what was presented to me :P
So you have your array in memory as so: 2, 23, 6, 7, 8... What this does is cast the array to a char*, which lets you access individual bytes, and it points here: 2, 23, 6, 7, 8... ^ It then adds four bytes, moving it over to the next value (more on this later). 2, 23, 6, 7, 8... ^ Then it turns it into an int* and dereferences it, getting the value 23. There are technically three things wrong with this code. The first is that it assumes that an unsigned is 4 bytes in size. (Hence the + 4). But this isn't necessarily true! Better would have been + sizeof(unsigned), ensuring correctness no matter what size unsigned happens to be. The second problem is the cast to int: the original array was unsigned, but the value is being cast to an int. There exists values in the unsigned range that int cannot represent (because in an int half of the range is in the negatives.) So if one of the values in the array was not representable as an int (meaning the value was greater than INT_MAX), you'd get the wrong value. Better would be to convert to unsigned*, to maintain the correct type. The last thing is the format specifier. The specifier for integers is %d, but the code uses %u, which is for unsigned integers. In effect, even though casting back to int* was wrong, printf is going to cast that value back into an unsigned*, restoring it's integrity. By fixing problem two, problem three fixes itself. There is a hidden fourth problem: The code sucks. This may be for learning purposes, but yuck.
2,126,467
2,126,492
Understanding pointers with file i/o in c++
I'm trying to get a better grasp on pointers. My class assignment was to create the function for the prototype void OpenFile(const char *fileName, ifstream &inFile). void OpenFile(const char *fileName, ifstream &inFile) { inFile.open(FILENAME, ios_base::in); if (!inFile.is_open()) { cerr << "Could not open file " << fileName << "\n"; exit(EXIT_FAILURE); } else { cout << "File Open successful"; } } //FILENAME is defined as: const char * const FILENAME = "file.txt"; // function is called in main with: OpenFile(FILENAME, inFile); I guess what I don't understand is the const char * and the & for the two arguments. I am guessing that the first argument is a const char * because that's how the assignment defined FILENAME. But did I have to use a pointer in this case? Could I have just done const char FILENAME = "file.txt"; and in my OpenFile to have the first parameter just take in a const char. And then again, why do I need a reference for the second parameter of my function? Definitely confused on when to use pointers and when to use references. Thanks!
First, let me say that your function looks a bit strange if you pass in a parameter fileName but then use FILENAME within and fileName is just used for error output. I guess this is not quite correct. Second, to the const char* issue. char itself is just a char (character) and as such is only one single character. const char FILENAME = "file.txt" would thus not work. Instead you'd need an array of chars (const char FILENAME[] = ...), or as it is done in C use a pointer to the memory location of the text, i.e. char*. As you seem to use STL, it may be a good idea to just ditch char* and convert to std::string instead. Third, pointer vs reference is often a matter of taste. At the end they both do the same and within the compiler they are in fact the same. The one difference in use is that you can not pass an empty (null) reference, but you can pass a null pointer. So the recommendation usually is to use references if you really need an object passed, and a pointer for anything that could be optional (in which case you must handle ptr == NULL). Also C strings being char* and other manually allocated memory are usually sent via pointer.
2,126,522
2,126,536
c++ virtual inheritance
Problem: class Base { public: Base(Base* pParent); /* implements basic stuff */ }; class A : virtual public Base { public: A(A* pParent) : Base(pParent) {} /* ... */ }; class B : virtual public Base { public: B(B* pParent) : Base(pParent) {} /* ... */ }; class C : public A, public B { public: C(C* pParent) : A(pParent), B(pParent) {} // - Compilation error here /* ... */ }; At the position given, gcc complains that it cannot match function call to Base(), i.e. the default constructor. But C doesn't inherit directly from Base, only through A and B. So why does gcc complain here? Ideas? TIA /Rob
virtual base classes are special in that they are initialized by the most derived class and not by any intermediate base classes that inherits from the virtual base. Which of the potential multiple initializers would the correct choice for initializing the one base? If the most derived class being constructed does not list it in its member initalization list then the virtual base class is initialized with its default constructor which must exist and be accessible. Note that a virtual base identifier is allowed to be use in a constructor's initializer list even if it is not a direct base of the class in question.
2,126,633
2,126,709
Private inheritance and composition, which one is best and why?
suppose i have a class engin and i inherit a class car from engin class class engin { public: engin(int nobofcylinders); void start(); }; class car:private engin { public: car():e(8){} void start() { e.start(); } private: engin e; }; now the same can be done by the composition, the question is which approch would be best and is mostly used in programming, and why???????
I prefer to think of inheritance as derived is a kind of base, that basically means public inheritance. In case of private inheritance it more like derived has a base, which IMHO doesn't sound right, because that's IMHO the work for composition not inheritance of any kind. So, since private inheritance and composition essentially mean same thing logically, which to choose? With the example you posted, I'd most certainly go for composition. Why? I tend to think of all kinds of inheritance as a kind of relationship, and with the example you posted, I can't think of a situation where I could say a car is kind of an engine, it simply isn't. It's indeed like a car has an engine, so why would a car inherit from an engine? I see no reason. Now, indeed there are cases where it's good to have private inheritance, namely boost::noncopyable, with it's ctor/dtor being protected, you'd have hard time instantiating it, and indeed since we want our class to have a noncopyable part, that's the only way to go. Some style guides (e.g. google c++ style guide) even recommend to never use private inheritance, for reasons similar to what I already written - private inheritance is just a bit confusing.
2,126,751
2,126,763
Beginner Question - Exiting while loop, input type double as condition, C++
I've only just recent began learning C++ and am having a little issue with while loops when the condition for the while loop is an input, of type double, from the user. I understand that if the user doesn't enter a value compatible with the double type then the loop is automatically broken. The issue is my console application exits upon entering anything other than a double. The current exercise I'm working on has asked to make use of a while loop and if statements to calculate a number of entered measurements and output the total. The user enters a value and then the measuring system (i.e 25 m for 25 metres). It also has to record and output the highest and lowest values entered. double value = 0; double total = 0; double high = 0; double low = 0; string unit = " "; while (cin >> value >> unit && unit != "convert") { if (unit == "in") {total = total+(value*2.54);// in = inches converting to cm if (value*2.54 > high) high = value; if (value*2.54 < low) low = value; } else if (unit == "m"){total = total+(value*100);// m = metres, converting to cm if (value*100 > high) high = value; if (value*100 < low) low = value; } else if (unit == "ft"){total = total+(value*30.48);// ft = feet, converting to ft if (value*30.48 > high) high = value; if (value*30.48 < low) low = value; } else if (unit == "cm"){total = total+value;// cm = centremetres if (value*2.54 > high) high = value; if (value*2.54 < low) low = value; } else cout << "Unable to calculate unit type - " << unit << endl; value = 0; } cout << "Total length in centre-metres: " << total << endl << "Total length in metres: " << total/100 << endl << "Total length in feet: " << total/30.48 << endl << "Total length in inches: " << total/2.54 << endl << "\nHighest value: " << high << ", Lowest value: " << low << endl; keep_window_open(); return 0; keep_window_open() is part of the custom header file that came with my C++ book, all it does is ask for a user to enter a character to quit. I know the current state of the program is a bit bloated but I wanted to get it all working correctly first. I had to use a work around of, if the user enters 'convert' as a unit the loop is killed so I could actually see if it was working correctly. The program does finish/complete its task when anything other than an double is entered into value but the results flash up on the console window and then it exits immediately. Any help is appreciated.
Your problem is that when you say: cin >> value and enter anything other than a double, the stream goes bad, because value is expecting a double. Your keep_window_open() function also fails, because the stream is still bad. There are two ways round this: Run your program from an existing command line prompt window - this will stay open after the program ends. This is the best general purpose solution. Clear the stream before using your "pause" code. Unfortunately, the endline you typed will still be in the buffer. Replace your "pause" code with: _ string line; if ( ! cin ) { cin.clear(); getline( cin, line ); } getline( cin, line );
2,127,015
2,127,036
C++ Conversion Not Working
#include <iostream> using namespace std; /*Use void functions, they perform some action but do not return a value*/ //Function Protoype, input,read in feet and inches: void input (double& feet, double& inches); //Function Prototype, calculate, calculate with given formulae. void calculate(double& feet, double& inches); //Function Prototype, output, outputs calculations to screen. void output (double meters, double centimeters); int main () { double feet; double inches; char repeat; do { //Call input: input(feet, inches); //Call calculate: calculate(feet, inches); //Call output: output (feet, inches); cout << "\n"; cout << "Repeat? (Y/N): "; cin >> repeat; cout << "\n"; } while (repeat == 'Y' || repeat == 'y'); } //Input function definition: void input (double& feet, double& inches) { cout << "Please enter the length in feet" << endl; cin >> feet; cout << "Please enter the length in inches" << endl; cin >> inches; } //Calculate function definition, insert formulae here: void calculate (double& feet, double& inches) { feet = (feet * 0.3048); inches = (inches * 2.54); } //Output function definition: void output (double meters, double centimeters) { cout << meters << " meters & " << centimeters << " cm's. " << endl; } Why is my conversion not working? Or what am I doing wrong? Objective: Given a length in feet and inches I am suppose to output an equivalent length in meters and centimeters. //Calculate function definition, insert formula here: void calculate (double& feet, double& inches) { feet = (feet * 0.3048); inches = (inches * 2.54); }
That seems a bizarre way of doing it, changing the actual input variables. I would opt instead for: void calculate (double feet, double inches, double& meters, double& centimeters) { double all_inches = feet * 12.0 + inches; centimeters = all_inches * 2.54; meters = int (centimeters / 100.0); centimeters -= (meters * 100.0); } In any case, even if you do use the same variables for input and output (and then they should be renamed to something more appropriate), it's still easiest to convert to a single form (inches) then do the conversion to centimeters then back to m/cm. In your current code, if you pass in 1ft,0in, you'll get back 0.3048m,0cm rather than the more correct 30.48cm. By using the code in this answer, it will be converted first to 12.0 inches, then from there to 30.48cm, then to 0m,30.48cm. Similarly, four and a half feet (4ft,6in) will first be converted to 54 inches, then to 137.16cm, then to 1m,37.16cm.
2,127,039
2,127,155
Smallest number that is evenly divisible by all of the numbers from 1 to 20?
I did this problem [Project Euler problem 5], but very bad manner of programming, see the code in c++, #include<iostream> using namespace std; // to find lowest divisble number till 20 int main() { int num = 20, flag = 0; while(flag == 0) { if ((num%2) == 0 && (num%3) == 0 && (num%4) == 0 && (num%5) == 0 && (num%6) == 0 && (num%7) == 0 && (num%8) == 0 && (num%9) == 0 && (num%10) == 0 && (num%11) == 0 && (num%12) ==0 && (num%13) == 0 && (num%14) == 0 && (num%15) == 0 && (num%16) == 0 && (num%17) == 0 && (num%18)==0 && (num%19) == 0 && (num%20) == 0) { flag = 1; cout<< " lowest divisible number upto 20 is "<< num<<endl; } num++; } } i was solving this in c++ and stuck in a loop, how would one solve this step...... consider num = 20 and divide it by numbers from 1 to 20 check whether all remainders are zero, if yes, quit and show output num or else num++ i din't know how to use control structures, so did this step if ((num%2) == 0 && (num%3) == 0 && (num%4) == 0 && (num%5) == 0 && (num%6) == 0 && (num%7) == 0 && (num%8) == 0 && (num%9) == 0 && (num%10) == 0 && (num%11) == 0 && (num%12) ==0 && (num%13) == 0 && (num%14) == 0 && (num%15) == 0 && (num%16) == 0 && (num%17) == 0 && (num%18)==0 && (num%19) == 0 && (num%20) == 0) ` how to code this in proper manner? answer for this problem is: abhilash@abhilash:~$ ./a.out lowest divisible number upto 20 is 232792560
There is a faster way to answer the problem, using number theory. Other answers contain indications how to do this. This answer is only about a better way to write the if condition in your original code. If you only want to replace the long condition, you can express it more nicely in a for loop: if ((num%2) == 0 && (num%3) == 0 && (num%4) == 0 && (num%5) == 0 && (num%6) == 0 && (num%7) == 0 && (num%8) == 0 && (num%9) == 0 && (num%10) == 0 && (num%11) == 0 && (num%12) ==0 && (num%13) == 0 && (num%14) == 0 && (num%15) == 0 && (num%16) == 0 && (num%17) == 0 && (num%18)==0 && (num%19) == 0 && (num%20) == 0) { ... } becomes: { int divisor; for (divisor=2; divisor<=20; divisor++) if (num%divisor != 0) break; if (divisor != 21) { ...} } The style is not great but I think this is what you were looking for.
2,127,087
2,127,095
Is this a memory leak? How should it be done?
I have something like this: void Test(void) { char errorMessage[256]; spintf(errorMessage,... blablabla); throw new CustomException(errorMessage); } Will this be a memory leak because errorMessage will be not freed? Or will this cause an exception when accessing the message of the exception inside a try{}catch because the errorMessage has been freed when going out from the function¿? Thanks in advance.
The memory of errorMessage will already be freed when accessed by the catch handler. However, you could just copy it into a std::string in CustomException's constructor. A memory leak, on the other hand, could be caused by the exception itself, since you put it on the heap. This is not necessary.
2,127,310
2,127,436
C/C++ bitfields versus bitwise operators to single out bits, which is faster, better, more portable?
I need to pack some bits in a byte in this fashion: struct { char bit0: 1; char bit1: 1; } a; if( a.bit1 ) /* etc */ or: if( a & 0x2 ) /* etc */ From the source code clarity it's pretty obvious to me that bitfields are neater. But which option is faster? I know the speed difference won't be too much if any, but as I can use any of them, if one's faster, better. On the other hand, I've read that bitfields are not guaranteed to arrange bits in the same order across platforms, and I want my code to be portable. Notes: If you plan to answer 'Profile' ok, I will, but as I'm lazy, if someone already has the answer, much better. The code may be wrong, you can correct me if you want, but remember what the point to this question is and please try and answer it too.
I would rather use the second example in preference for maximum portability. As Neil Butterworth pointed out, using bitfields is only for the native processor. Ok, think about this, what happens if Intel's x86 went out of business tomorrow, the code will be stuck, which means having to re-implement the bitfields for another processor, say RISC chip. You have to look at the bigger picture and ask how did OpenBSD manage to port their BSD systems to a lot of platforms using one codebase? Ok, I'll admit that is a bit over the top, and debatable and subjective, but realistically speaking, if you want to port the code to another platform, its the way to do it by using the second example you used in your question. Not alone that, compilers for different platforms would have their own way of padding, aligning bitfields for the processor where the compiler is on. And furthermore, what about the endianess of the processor? Never rely on bitfields as a magic bullet. If you want speed for the processor and will be fixed on it, i.e. no intention of porting, then feel free to use bitfields. You cannot have both!
2,127,325
2,127,345
std::vector insert() reallocation
I was looking through the std::vector code and I found something I didn't quite get. When capacity < size() + 1 it needs to reallocate the buffer so it can insert the new element. What it does (as far as I've been able to extract from the code) is: allocate the new buffer copy the prefix of the old buffer (0 - index of insertion) construct the new element in the new buffer copy the suffix of the old buffer (index - end) call destructor on all items in old buffer deallocate old buffer The prefix and suffix copy is done with memmove as far as I could see. Isn't memmove a pure binary copy of the data? It doesn't call the constructor of the elements, does it? What I was wondering is, why does the function call the destructor on the elements in the old buffer if the memory is just moved, not re-constructed in the new buffer?
I looked through the MSVC8 vector implementation - I can't see a memmove(). The previous vector elements are not moved, they're copied and their copy c'tor is called to copy them over to the new buffer (the buffer is allocated in a single allocation, elements are constructed using placement new). Of course this is only the MSVC implementation, but it's how a vector should behave according to the standard. However, using memmove is sometimes OK - for example for a std::vector<int> - and STL implementations are free to specialize for this case. You might have missed a template 'branch' reading the source code.
2,127,432
2,128,270
GDB doesn't work with -D_FILE_OFFSET_BITS=64
I'm compiling a i386 C++ app on Snow Leopard. When I compile with -D_FILE_OFFSET_BITS=64 I can't use the binary with gdb. I get the following error message: warning: Could not find object file "/var/folders/kw/kwmH332LGwCIh3GrRREgCk+++TI/-Tmp-//ccZfMAM5.o" - no debug information available for "test.cpp".
This likely has nothing at all to do with -D_FILE_OFFSET_BITS=64. When you compile on Mac OS, debug info is not pulled into the executable, but remains in the object file, and the debugger looks for it there. From your warning message, it appears that you did: g++ -D_FILE_OFFSET_BITS=64 -g test.cpp This creates a temporary object file (with name like ccZfMAM5.o), links that object file into the executable, and then removes the object file. Since the debugger can't read debug info from no longer present object file, you get the warning. Instead, do this: g++ -g -c -D_FILE_OFFSET_BITS=64 test.cpp g++ -g test.o This will make test.o object file (and debug info contained in it) available to the debugger.
2,127,540
2,127,557
Can anyone explain this algorithm for calculating large factorials?
i came across the following program for calculating large factorials(numbers as big as 100).. can anyone explain me the basic idea used in this algorithm?? I need to know just the mathematics implemented in calculating the factorial. #include <cmath> #include <iostream> #include <cstdlib> using namespace std; int main() { unsigned int d; unsigned char *a; unsigned int j, n, q, z, t; int i,arr[101],f; double p; cin>>n; p = 0.0; for(j = 2; j <= n; j++) p += log10(j); d = (int)p + 1; a = new unsigned char[d]; for (i = 1; i < d; i++) a[i] = 0; //initialize a[0] = 1; p = 0.0; for (j = 2; j <= n; j++) { q = 0; p += log10(j); z = (int)p + 1; for (i = 0; i <= z/*NUMDIGITS*/; i++) { t = (a[i] * j) + q; q = (t / 10); a[i] = (char)(t % 10); } } for( i = d -1; i >= 0; i--) cout << (int)a[i]; cout<<"\n"; delete []a; return 0; }
Note that n! = 2 * 3 * ... * n so that log(n!) = log(2 * 3 * ... * n) = log(2) + log(3) + ... + log(n) This is important because if k is a positive integer then the ceiling of log(k) is the number of digits in the base-10 representation of k. Thus, these lines of code are counting the number of digits in n!. p = 0.0; for(j = 2; j <= n; j++) p += log10(j); d = (int)p + 1; Then, these lines of code allocate space to hold the digits of n!: a = new unsigned char[d]; for (i = 1; i < d; i++) a[i] = 0; //initialize Then we just do the grade-school multiplication algorithm p = 0.0; for (j = 2; j <= n; j++) { q = 0; p += log10(j); z = (int)p + 1; for (i = 0; i <= z/*NUMDIGITS*/; i++) { t = (a[i] * j) + q; q = (t / 10); a[i] = (char)(t % 10); } } The outer loop is running from j from 2 to n because at each step we will multiply the current result represented by the digits in a by j. The inner loop is the grade-school multiplication algorithm wherein we multiply each digit by j and carry the result into q if necessary. The p = 0.0 before the nested loop and the p += log10(j) inside the loop just keep track of the number of digits in the answer so far. Incidentally, I think there is a bug in this part of the program. The loop condition should be i < z not i <= z otherwise we will be writing past the end of a when z == d which will happen for sure when j == n. Thus replace for (i = 0; i <= z/*NUMDIGITS*/; i++) by for (i = 0; i < z/*NUMDIGITS*/; i++) Then we just print out the digits for( i = d -1; i >= 0; i--) cout << (int)a[i]; cout<<"\n"; and free the allocated memory delete []a;
2,127,612
2,127,624
Is there a readable implementation of the STL?
I'm on Linux; looking at the STL headers; they're really really complicated. Is there, somewhere, a smaller version of STL that has the core features of the STL, but is actually readable? Thanks!
There is a book The C++ Standard Template Library, co-authored by the original STL designers Stepanov & Lee (together with P.J. Plauger and David Musser), which describes a possible implementation, complete with code - see http://www.amazon.co.uk/C-Standard-Template-Library/dp/0134376331.
2,127,693
2,127,727
SFINAE + sizeof = detect if expression compiles
I just found out how to check if operator<< is provided for a type. template<class T> T& lvalue_of_type(); template<class T> T rvalue_of_type(); template<class T> struct is_printable { template<class U> static char test(char(*)[sizeof( lvalue_of_type<std::ostream>() << rvalue_of_type<U>() )]); template<class U> static long test(...); enum { value = 1 == sizeof test<T>(0) }; typedef boost::integral_constant<bool, value> type; }; Is this trick well-known, or have I just won the metaprogramming Nobel prize? ;) EDIT: I made the code simpler to understand and easier to adapt with two global function template declarations lvalue_of_type and rvalue_of_type.
It's a well known technique, I'm afraid :-) The use of a function call in the sizeof operator instructs the compiler to perform argument deduction and function matching, at compile-time, of course. Also, with a template function, the compiler also instantiates a concrete function from a template. However, this expression does does not cause a function call to be generated. It's well described in SFINAE Sono Buoni PDF. Check other C++ SFINAE examples.
2,127,779
2,127,845
what kind of datatype should i use for this 600851475143 in c++?
i'm using c++, even if i declare long int, there is error like...... long int num = 600851475143; warning: integer constant is too large for ‘long’ type which datatype should be used in this case?
A lot of it depends on the platform and compiler you are using. If you are on a x64 platform, a long datatype in C++ should work. A signed long ranges from −9,223,372,036,854,775,808 to +9,223,372,036,854,775,807. An unsigned long on the other hand ranges from 0 to +18,446,744,073,709,551,615. Also depending on the compiler and platform there are a few other datatypes which effectively is the same thing (doubleword, longword, long long, quad, quadword, int64). C (not C++) supports the long long data type. Say if you are on Fedora 10 x32 then gcc 4.3.0 supports the long long datatype but you must put the LL after the large literal. See http://www.daniweb.com/forums/thread162930-2.html
2,127,797
2,127,819
Significance of -pthread flag when compiling
In various multi threaded C and C++ projects I've seen the -pthread flag applied to both the compiling and linking stage while others don't use it at all and just pass -lpthread to the linking stage. Is there any danger not compiling and linking with the -pthread flag - i.e. what does -pthread actually do ? I'm primarily interested in Linux platforms.
Try: gcc -dumpspecs | grep pthread and look for anything that starts with %{pthread:. On my computer, this causes files to be compiled with -D_REENTRANT, and linked with -lpthread. On other platforms, this could differ. Use -pthread for most portability. Using _REENTRANT, on GNU libc, changes the way some libc headers work. As a specific example, it makes errno call a function returning a thread-local location.
2,127,978
2,127,988
C++ strcpy non-constant expression as array bound
I turned back to C++ after a long time in C#, PHP and other stuff and I found something strange: temp.name = new char[strlen(name) + strlen(r.name) + 1]; this compiles temp.name = (char *)malloc(sizeof(char[strlen(name) + strlen(r.name) + 1])); this doesn't (temp.name is a char *) The compiler error is error C2540: non-constant expression as array bound Does anyone know what the problem might be and how it might be remedied? Thank you.
sizeof(...) expects a constant compile-time expression. strlen is not a compile-time expression, it is a function which needs to be executed to get a result. Therefore, the compiler is not able to reserve sufficient storage for an array declared like this: char c[strlen("Hello")]; Although the length of the string is clearly 5, the compiler does not know. To avoid this pitfall, do not use sizeof here. Instead: char* c = (char*)malloc(strlen(name)+strlen(rname)+1); This gives you a pointer to n bytes in return. sizeof(char)==1 is always true, so the number of bytes in the buffer equals the number of chars you can store in it. To malloc arrays of a different type, multiply with the static size of one array element: int* c = (int*) malloc(sizeof(int)*100); This is Ok, because sizeof is applied to a compile-time expression. Of course, the C++ way is much cleaner: int* c = new int[100];
2,128,119
2,128,194
Create Square Window C++
Stuck on a little fiddly problem. I'm creating a GUI in C++ using XP and VS C++ using the command CreateWindow(). My question is, how do I make the inside paintable region a perfect square. When passing in the size of the window to create, some of this is deducted for the menu bar at the top, border all around etc. Are there any real time variables I can pass in, e.g. to create a 500x500 window would be: ...500+BORDER,500+MENU_TOP+BORDER... Thanks everyone
The way I usually do it is with AdjustWindowRect. I find it simpler than the other suggested methods (which should work just as well, it's your choice). Use it as such: RECT rect = {0, 0, desiredWidth, desiredHeight}; AdjustWindowRect(&rect, windowStyle, hasMenu); const int realWidth = rect.right - rect.left; const int realHeight = rect.bottom - rect.top; And pass realWidth & realHeight to CreateWindow. The function will, as its name suggests, adjust the window according to your window style and menu use, so that the client region matches your desired size.
2,128,128
2,128,154
How can I generate random samples from bivariate normal and student T distibutions in C++?
what is the best approach to generate random samples from bivariate normal and student T distributions? In both cases sigma is one, mean 0 - so the only parameter I am really interested in is correlation (and degrees of freedom for student t). I need to have the solution in C++, so I can't unfortunately use already implemented functions from MatLab or Mathematica.
You can use the GNU GSL libraries. See here for Bivariate normal: http://www.gnu.org/software/gsl/manual/html_node/The-Bivariate-Gaussian-Distribution.html and Student's t-distribution here: http://www.gnu.org/software/gsl/manual/html_node/The-t_002ddistribution.html They are straight forward to use.
2,128,239
2,128,252
Typecasting, ints and chars in c++
I'm trying to write a function to detect separators as defined by an assignment and I know it is not good programming style to #define EXCLAMATION_POINT 33, but to instead do #define EXCLAMATION_POINT '!' This is my code: #include <iostream> #include <ostream> using namespace std; #define PERIOD '.' #define QUESTION_MARK '?' #define EXCLAMATION_POINT '!' #define COMMA ',' #define COLON ':' #define SEMICOLON ';' inline bool IsSeparator(int x) { if (isspace(x) || x == PERIOD || x == QUESTION_MARK || x == EXCLAMATION_POINT || x == COMMA || x == COLON || x == SEMICOLON) { return true; } else { return false; } } int main (int argc, char * const argv[]) { int input; cout << "Enter characters: \n"; input = cin.get(); if (!IsSeparator(input)) cout << "true"; else { cout << "false"; } return 0; } But in my IsSeparator(), how do I typecast that int to a char to be compared to '!'. I thought if I did something like (char)EXCLAMATION_POINT that would work, but it does not and the value is left at an int. What am I doing wrong here? Thanks!
You don't need any cast, but: if (!IsSeparator(input)) should be: if (IsSeparator(input)) Also, your prompt: cout << "Enter characters: \n"; implies you can enter multiple characters. So you can, but cin.get() will only read one. Regarding giving symbolic names to things. Suppose you are parsing a file where the separator is a colon. It then makes sense to say: const char SEPARATOR = ':'; because you can then change it when the file format changes, for example to: const char SEPARATOR = '|'; but it doesn't normally make sense to give your own names to the members of the ASCII (or whatever) character set. In your code, it might make sense to create an array of separators (I'm not showing all the ones you use for my ease of typing): const char SEPARATORS[] = {':', '|', '!', 0 }; and then have your validation function iterate over the array. Note in this case, the array could also have been expressed as a string literal: const char * const SEPARATORS = ":|!";
2,128,307
2,128,363
Ok to provide constructor + trivial operators for behaviorless aggregates?
This is a follow-up question to 2043381. Consider the following: struct DataBundle { std::string name; int age; DataBundle() : age(0) {} DataBundle(const std::string& name, int age) : name(name), age(age) {} void swap(DataBundle& rhs) {name.swap(rhs.name); std::swap(age, rhs.age);} DataBundle& operator=(DataBundle rhs) {swap(rhs); return *this;} bool operator==(const DataBundle& rhs) const {return (name == rhs.name) && (age == rhs.age);} bool operator!=(const DataBundle& rhs) const {return !(*this == rhs);} } In the spirit of rule #41 of C++ Coding Standards (see related article), would this still be considered a behaviorless aggregate? I don't like writing "dumb" classes with mostly getters/setters, and would rather use an all-public struct to indicate it's just a "bundle-o-data". But in the above example, am I at the point where I should make DataBundle a class with getters/setters?
No, no need for getters and setters yet. It is still a plain data structure where no methods implement actions modifying the data structure - compare, assign, swap are no 'behaviour' here, they're stub needed by the language to perform basic operations and to make the data structure actually usable. You need to decide whether there are any dependencies or invariants to be hold between the fields of structure. If they exist (or may exist in future), use getters or setters to ensure them (i.e. adjust attribute a if attribute b is changed). If not, declare everything public. name and age are decoupled properties of a human being, I don't think accessors are really necessary here. Of course it's a matter of taste.
2,128,321
2,128,727
Can main function call itself in C++?
Can anybody tell what's the problem of the code below? int main () { return main(); } I tested, it compiles correctly. It's running forever. Anymore trick behind the scene?
TLDR: Calling main results in undefined behavior. There seems to be confusion about the terminology used in the standard, and the implications that has for the programmer and compiler. Firstly, the standard alone determines everything about the C++ language. If your particular version of a particular compiler allows some particular action, that has no bearing on whether or not that action is legal. For the remainder of the post, I'm referring to the ISO03 standard. So to quote once again, the standard says in §3.6.1.3: The function main shall not be used within a program. Additionally, §3.2 defines "used" as: An object or non-overloaded function is used if its name appears in a potentially-evaluated expression. This means that once the program begins executing, main should never be entered again. That means programmers cannot call main, that means the compiler cannot insert another call to main (why it would, who knows), you cannot take the address of main and call that, etc. You cannot even have the potential of calling main. The only call to main should be by the run-time library the program is running on; all other calls invoke undefined behavior. (Which means anything could happen!) Now onto compiler behavior: A diagnosable rule is defined as (§1.4.1): The set of diagnosable rules consists of all syntactic and semantic rules in this International Standard except for those rules containing an explicit notation that “no diagnostic is required” or which are described as resulting in “undefined behavior.” In our case, §3.6.1.3 defines a diagnosable rule. Here's what compilers should do according to §1.4.2: — If a program contains no violations of the rules in this International Standard, a conforming implementation shall, within its resource limits, accept and correctly execute3) that program. — If a program contains a violation of any diagnosable rule, a conforming implementation shall issue at least one diagnostic message, except that — If a program contains a violation of a rule for which no diagnostic is required, this International Standard places no requirement on implementations with respect to that program. So compilers are not required to enforce rules. All compilers have to do is take well-formed programs (§1.3.14) and turn them into an executable program. A compiler is free to warn, error, etc. however it likes, as long as it does not conflict with the language. It is required to display a message in our particular case, according to the second clause. For this particular problem, on gcc the -pedantic option will warn about the illegality of calling main within the program. Visual Studio will not warn about calling main, but on any warning level (greater than 0) it will warn about the recursive nature of the program. What does all this mean in terms of the answers you should expect? It means it's completely meaningless to try and define with certainty what the code snippet posted will do. Calling main results in undefined behavior, and trying to define undefined behavior is obviously a lost cause. The only honest answer anyone can give to "what happens when I call main?" is "Anything." I hope this clears things up.
2,128,389
2,128,420
Edit values in config. file
Currently, I'm using ReadFile() and WriteFile() APIs to write & read from file. are there any API functions to replace/edit text if the data is large enough to be written again? I only heard about SetFilePointer() but i'm not quite sure how to use it to replace the text from a file. For example, select a string/char from file say, value '0' of Key2. Key1 = 0 Key2 = 0 and change it to '1'. Key1 = 0 Key2 = 1
The functions GetPrivateProfileString and WritePrivateProfileString might be good for this.
2,128,442
2,128,452
What does (1U << X) do?
I found this piece of code: enum { IsDynamic = (1U << 0), // ... IsSharable = (1U << 1), // ... IsStrong = (1U << 2) // ... }; What does the (1U << X) do?
It sets bitmasks: 1U << 0 = 1 1U << 1 = 2 1U << 2 = 4 etc... What happens is 1U (unsigned value 1) is shifted to the left by x bits. The code you posted is equivalent to: enum { IsDynamic = 1U, // binary: 00000000000000000000000000000001 IsSharable = 2U, // binary: 00000000000000000000000000000010 IsStrong = 4U // binary: 00000000000000000000000000000100 }
2,128,496
2,128,509
C++ compilation problem
Pretty much forgot how to code C++ at all. Anyway, here is the problem. I am trying to load a class defined in a .cpp file I wrote myself. In the main function: ... ... #include "loader.h" ... ... model load_model("TechnologyEnterpriseFacility_Day_Gregor/ TechnologyEnterpriseFacility_Gregor.model"); the header file looks like this: #ifndef LOADER_H_ #define LOADER_H_ class model { public: int textures []; float vertices[][3]; float triangles[][13]; model(const char*); // constructor }; #endif /* LOADER_H_ */ and here is the .cpp file: #include <iostream> #include <fstream> #include <string> #include <sstream> #include <typeinfo> #include "loader.h" using namespace std; model::model(const char* filename) { ... ... When I compile the main function, I got error message: gcc -o glrender glrender.cpp -lglut /tmp/cc3sWIgb.o: In function `__static_initialization_and_destruction_0(int, int)': glrender.cpp:(.text+0x11b): undefined reference to `model::model(char const*)' collect2: ld returned 1 exit status comments and ideas are welcomed, thanks.
Didn't you forget to insert model.cpp in your compilation line ? gcc -o glrender glrender.cpp model.cpp -lglut
2,128,560
2,128,599
How to determine if a file can be written using C++
In C++ how can I determine if the program has either read-only access or read-write access to a file? I searched the boost filesystem library but I have yet to find something to help me. Right now I thinking of opening the file, trying to write inside and check for error, but that doesn't seem a very appropriate way of doing this. Any clue? EDIT : it would need to be cross platform
At the end of the day, the only way to test if you can write data to a file on a modern OS is to actually try to write it. Lots of things could have happened to the file between tests for permission and the actual write.
2,128,620
2,128,643
How to create timer in WinApi (C++)?
How to create timer in WinApi (C++)?
Call the SetTimer function. This allows you to specify a callback function, or to have Windows post you a WM_TIMER message.
2,128,838
2,128,955
compile time polymorphism and runtime polymorphism
I noticed that somewhere polymorphism just refer to virtual function. However, somewhere they include the function overloading and template. Later, I found there are two terms, compile time polymorphism and run-time polymorphism. Is that true? My question is when we talked about polymorphism generally, what's the widely accepted meaning?
Yes, you're right, in C++ there are two recognized "types" of polymorphism. And they mean pretty much what you think they mean Dynamic polymorphism is what C#/Java/OOP people typically refer to simply as "polymorphism". It is essentially subclassing, either deriving from a base class and overriding one or more virtual functions, or implementing an interface. (which in C++ is done by overriding the virtual functions belonging to the abstract base class) Static polymorphism takes place at compile-time, and could be considered a variation of ducktyping. The idea here is simply that different types can be used in a function to represent the same concept, despite being completely unrelated. For a very simple example, consider this template <typename T> T add(const T& lhs, const T& rhs) { return lhs + rhs; } If this had been dynamic polymorphism, then we would define the add function to take some kind of "IAddable" object as its arguments. Any object that implement that interface (or derive from that base class) can be used despite their different implementations, which gives us the polymorphic behavior. We don't care which type is passed to us, as long as it implements some kind of "can be added together" interface. However, the compiler doesn't actually know which type is passed to the function. The exact type is only known at runtime, hence this is dynamic polymorphism. Here, though, we don't require you to derive from anything, the type T just has to define the + operator. It is then inserted statically. So at compile-time, we can switch between any valid type as long as they behave the same (meaning that they define the members we need) This is another form of polymorphism. In principle, the effect is the same: The function works with any implementation of the concept we're interested in. We don't care if the object we work on is a string, an int, a float or a complex number, as long as it implements the "can be added together" concept. Since the type used is known statically (at compile-time), this is known as static polymorphism. And the way static polymorphism is achieved is through templates and function overloading. However, when a C++ programmer just say polymorphism, they generally refer to dynamic/runtime polymorphism. (Note that this isn't necessarily true for all languages. A functional programmer will typically mean something like static polymorphism when he uses the term -- the ability to define generic functions using some kind of parametrized types, similar to templates)
2,128,995
2,398,856
LNK2001 error when compiling windows forms application with VC++ 2008
I've been trying to write a small application which will work with mysql in C++. I am using MySQL server 5.1.41 and MySQL C++ connector 1.0.5. Everything compiles fine when i write console applications, but when i try to compile windows forms application exactly the same way (same libraries, same paths, same project properties) i get this errors: Error 1 error LNK2001: unresolved external symbol "public: virtual int __clrcall sql::mysql::MySQL_Savepoint::getSavepointId(void)" (?getSavepointId@MySQL_Savepoint@mysql@sql@@$$FUAMHXZ) test1.obj test1 Error 2 error LNK2001: unresolved external symbol "public: virtual class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __clrcall sql::mysql::MySQL_Savepoint::getSavepointName(void)" (?getSavepointName@MySQL_Savepoint@mysql@sql@@$$FUAM?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) test1.obj test1 following instructions from here, i've got this: Undecoration of :- "?getSavepointId@MySQL_Savepoint@mysql@sql@@UEAAHXZ" is :- "public: virtual int __cdecl sql::mysql::MySQL_Savepoint::getSavepointId(void) __ptr64" Undecoration of :- "?getSavepointName@MySQL_Savepoint@mysql@sql@@UEAA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ" is :- "public: virtual class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl sql::mysql::MySQL_Savepoint::getSavepointName(void) __ptr64" but what should i do now?
Project + Properties, General, change Common Language Runtime support to /clr from /clr:pure
2,129,155
2,134,984
C++ equivalent for memset on char*
I have this code char * oldname = new char[strlen(name) + 1]; memcpy(oldname,name,strlen(name) + 1); name = new char[strlen(oldname) + strlen(r.name) + 1]; memset(name, '\0', strlen(name)); strcat(name,oldname); strcat(name," "); strcat(name,r.name); I understand that it is a no no to use memcpy and memset but I haven't understood exactly how to use this in C++, preferably without std. Does anyone know? Thank you.
char * oldname = new char[strlen(name) + 1]; //memcpy(oldname,name,strlen(name) + 1); strcpy(oldname,name); name = new char[strlen(oldname) + strlen(r.name) + 1]; //memset(name, '\0', strlen(name)); name[0] = '\0'; strcat(name,oldname); strcat(name," "); strcat(name,r.name); I understand this now, just wanted to paste this code for all future visitors The commented lines are equivalent with the uncommented ones below them. C commented, C++ uncommented.
2,129,189
2,129,365
C++0x move constructor gotcha
Edit: I re-asked this same question (after fixing the problems noted with this question) here: Why does this C++0x program generates unexpected output? The basic idea is that pointing to moveable things may net you some odd results if you aren't careful. The C++ move constructor and move assignment operator seem like really positive things. And they can be used in situations where the copy constructor makes no sense because they don't require duplicating resources being pointed at. But there are cases where they will bite you if you aren't careful. And this is especially relevant as I've seen proposals to allow the compiler to generate default implementations of the move constructor. I will provide a link to such if someone can give me one. So, here is some code that has some flaws that may not be completely obvious. I tested the code to make sure it compiles in g++ with the -std=gnuc++0x flag. What are those flaws and how would you fix them? #if (__cplusplus <= 199711L) && !defined(__GXX_EXPERIMENTAL_CXX0X__) #error This requires c++0x #endif #include <unordered_set> #include <vector> #include <utility> #include <algorithm> class ObserverInterface { public: virtual ~ObserverInterface() {} virtual void observedChanged() = 0; virtual void observedGoingAway() = 0; }; class Observed { private: typedef ::std::unordered_set<ObserverInterface *> obcontainer_t; public: Observed() {} Observed(const Observed &) = delete; const Observed &operator =(const Observed &b) = delete; // g++ does not currently support defaulting the move constructor. Observed(Observed &&b) : observers_(::std::move(b.observers_)) { } // g++ does not currently support defaulting move assignment. const Observed &operator =(Observed &&b) { observers_ = ::std::move(b.observers_); return *this; } virtual ~Observed() { for (auto i(observers_.begin()); i != observers_.end(); ++i) { (*i)->observedGoingAway(); } } void unObserve(ObserverInterface *v) { auto loc(observers_.find(v)); if (loc != observers_.end()) { observers_.erase(loc); } } void changed() { if (!observers_.empty()) { // Copy observers_ to bector so unObserve works ::std::vector<ObserverInterface *> tmp; tmp.reserve(observers_.size()); tmp.assign(observers_.begin(), observers_.end()); for (auto i(tmp.begin()); i != tmp.end(); ++i) { (*i)->observedChanged(); } } } private: obcontainer_t observers_; }; class Observer : public ObserverInterface { public: Observer() {} Observer(const Observer &) = delete; const Observer &operator =(const Observer &b) = delete; // g++ does not currently support defaulting the move constructor. Observer(Observer &&b) : observed_(b.observed_) { b.observed_ = 0; return *this; } // g++ does not currently support defaulting move assignment. const Observer &operator =(Observer &&b) { observed_ = b.observed_; b.observed_ = 0; return *this; } virtual ~Observer() { if (observed_) { observed_->unObserve(this); observed_ = 0; } } virtual void observedChanged() { doStuffWith(observed_); } virtual void observedGoingAway() { observed_ = 0; } private: Observed *observed_; // Defined elsewhere void doStuffWith(Observed *); };
There are lots of problems with the code. Observer::observed_ is left uninitialized in the default constructor, leading to an undefined behavior when the destructor gets called. No value but 0 is ever assigned to Observer::observed_, making the variable superfluous. Even if there was a way to associate an observer with an observed, you're not re-registering when moving the observer. You're trying to return a value from observer's move constructor. Boost.Signals already solves whatever problem you're trying to solve. It is more idiomatic to return non-const reference from assignment operators.
2,129,200
2,129,418
view the default functions generated by a compiler?
Is there any way to view the default functions ( e.g., default copy constructor, default assignment operator ) generated by a compiler such as VC++2008 for a class which does not define them?
With the clang compiler, you can see them by passing the -ast-dump argument. Clang is still in development stage, but you can already use it for these things: [js@HOST2 cpp]$ cat main1.cpp struct A { }; [js@HOST2 cpp]$ clang++ -cc1 -ast-dump main1.cpp typedef char *__builtin_va_list; struct A { public: struct A; inline A(); inline A(struct A const &); inline struct A &operator=(struct A const &); inline void ~A(); }; [js@HOST2 cpp]$ I hope that's what you asked for. Let's change the code and look again. [js@HOST2 cpp]$ cat main1.cpp struct M { M(M&); }; struct A { M m; }; [js@HOST2 cpp]$ clang++ -cc1 -ast-dump main1.cpp typedef char *__builtin_va_list; struct M { public: struct M; M(struct M &); inline struct M &operator=(struct M const &); inline void ~M(); }; struct A { public: struct A; struct M m; inline A(); inline A(struct A &); inline struct A &operator=(struct A const &); inline void ~A(); }; [js@HOST2 cpp]$ Notice how the implicitly declared copy constructor of A now has a non-const reference parameter, because one of its members has too (member m), and that M has no default constructor declared. For getting the generated code, you can let it emit virtual machine intermediate language. Let's look on the generated code for this: struct A { virtual void f(); int a; }; A f() { A a; a = A(); return a; } // using def-ctor, assignment and copy-ctor [js@HOST2 cpp]$ clang++ -cc1 -O1 -emit-llvm -o - main1.cpp | c++filt [ snippet ] define linkonce_odr void @A::A()(%struct.A* nocapture %this) nounwind align 2 { entry: %0 = getelementptr inbounds %struct.A* %this, i32 0, i32 0 ; <i8***> [#uses=1] store i8** getelementptr inbounds ([3 x i8*]* @vtable for A, i32 0, i32 2), i8*** %0 ret void } define linkonce_odr %struct.A* @A::operator=(A const&)(%struct.A* %this, %struct.A* nocapture) nounwind align 2 { entry: %tmp = getelementptr inbounds %struct.A* %this, i32 0, i32 1 ; <i32*> [#uses=1] %tmp2 = getelementptr inbounds %struct.A* %0, i32 0, i32 1 ; <i32*> [#uses=1] %tmp3 = load i32* %tmp2 ; <i32> [#uses=1] store i32 %tmp3, i32* %tmp ret %struct.A* %this } define linkonce_odr void @A::A(A const&)(%struct.A* nocapture %this, %struct.A* nocapture) nounwind align 2 { entry: %tmp = getelementptr inbounds %struct.A* %this, i32 0, i32 1 ; <i32*> [#uses=1] %tmp2 = getelementptr inbounds %struct.A* %0, i32 0, i32 1 ; <i32*> [#uses=1] %tmp3 = load i32* %tmp2 ; <i32> [#uses=1] store i32 %tmp3, i32* %tmp %1 = getelementptr inbounds %struct.A* %this, i32 0, i32 0 ; <i8***> [#uses=1] store i8** getelementptr inbounds ([3 x i8*]* @vtable for A, i32 0, i32 2), i8*** %1 ret void } Now, i don't understand that intermediate language (which is defined at llvm.org). But you can translate all that code into C using the llvm compiler: [js@HOST2 cpp]$ clang++ -cc1 -O1 -emit-llvm -o - main1.cpp | llc -march=c -o - | c++filt [snippet] void A::A()(struct l_struct.A *llvm_cbe_this) { *((&llvm_cbe_this->field0)) = ((&_ZTV1A.array[((signed int )2u)])); return; } struct l_struct.A *A::operator=(A const&)(struct l_struct.A *llvm_cbe_this, struct l_struct.A *llvm_cbe_tmp__1) { unsigned int llvm_cbe_tmp3; llvm_cbe_tmp3 = *((&llvm_cbe_tmp__1->field1)); *((&llvm_cbe_this->field1)) = llvm_cbe_tmp3; return llvm_cbe_this; } void A::A(A const&)(struct l_struct.A *llvm_cbe_this, struct l_struct.A *llvm_cbe_tmp__2) { unsigned int llvm_cbe_tmp3; llvm_cbe_tmp3 = *((&llvm_cbe_tmp__2->field1)); *((&llvm_cbe_this->field1)) = llvm_cbe_tmp3; *((&llvm_cbe_this->field0)) = ((&_ZTV1A.array[((signed int )2u)])); return; } Tada! Notice how it sets the virtual table pointer in the copy constructor and default constructor. Hope this helps.
2,129,230
2,129,242
cout << order of call to functions it prints?
the following code: myQueue.enqueue('a'); myQueue.enqueue('b'); cout << myQueue.dequeue() << myQueue.dequeue(); prints "ba" to the console while: myQueue.enqueue('a'); myQueue.enqueue('b'); cout << myQueue.dequeue(); cout << myQueue.dequeue(); prints "ab" why is this? It seems as though cout is calling the outermost (closest to the ;) function first and working its way in, is that the way it behaves?
There's no sequence point with the << operator so the compiler is free to evaluate either dequeue function first. What is guaranteed is that the result of the second dequeue call (in the order in which it appears in the expression and not necessarily the order in which it is evaluated) is <<'ed to the result of <<'ing the first (if you get what I'm saying). So the compiler is free to translate your code into some thing like any of these (pseudo intermediate c++). This isn't intended to be an exhaustive list. auto tmp2 = myQueue.dequeue(); auto tmp1 = myQueue.dequeue(); std::ostream& tmp3 = cout << tmp1; tmp3 << tmp2; or auto tmp1 = myQueue.dequeue(); auto tmp2 = myQueue.dequeue(); std::ostream& tmp3 = cout << tmp1; tmp3 << tmp2; or auto tmp1 = myQueue.dequeue(); std::ostream& tmp3 = cout << tmp1; auto tmp2 = myQueue.dequeue(); tmp3 << tmp2; Here's what the temporaries correspond to in the original expression. cout << myQueue.dequeue() << myQueue.dequeue(); | | | | | | |____ tmp1 _____| |_____ tmp2 ____| | | |________ tmp3 _________|
2,129,235
2,129,768
How to pass a row of boost::multi_array and std::vector by reference to the same template function?
I have a problem with this bit of code: #include <boost/multi_array.hpp> #include <boost/array.hpp> #include <vector> #include <iostream> template <typename Vec> void foo(Vec& x, size_t N) { for (size_t i = 0; i < N; ++i) { x[i] = i; } } int main() { std::vector<double> v1(10); foo(v1, 5); std::cout << v1[4] << std::endl; boost::multi_array<double, 2> m1; boost::array<double, 2> shape; shape[0] = 10; shape[1] = 10; m1.resize(shape); foo(m1[0], 5); std::cout << m1[0][4] << std::endl; return 0; } Trying to compile it with gcc, I get the error: boost_multi_array.cpp: In function 'int main()': boost_multi_array.cpp:26: error: invalid initialization of non-const reference of type 'boost::detail::multi_array::sub_array<double, 1u>&' from a temporary of type 'boost::detail::multi_array::sub_array<double, 1u>' boost_multi_array.cpp:7: error: in passing argument 1 of 'void foo(Vec&, size_t) [with Vec = boost::detail::multi_array::sub_array<double, 1u>]' It works as expected for boost::multi_array when I change the type of the first argument of function foo from Vec& to Vec, but then the std::vector is passed by value, which is not what I want. How can I achieve my goal without writing two templates?
The problem is that for NumDims > 1, operator[] returns a temporary object of type template subarray<NumDims-1>::type. A (not so nice) work-around would be the something like the following: typedef boost::multi_array<double, 2> MA; MA m1; MA::reference ref = m1[0]; foo(ref, 5); // ref is no temporary now An alternative would be to wrap your implementation and provide an overload for the multi-array case.... E.g.: (note: i didn't see how to get the overload to work with boost::multi_array<T,N>::reference, please don't put it into productive use with this detail:: version ;) template<class T> void foo_impl(T x, size_t N) { for (size_t i = 0; i < N; ++i) { x[i] = i; } } template<class T> void foo(T& t, size_t n) { foo_impl<T&>(t, n); } template<typename T, size_t size> void foo(boost::detail::multi_array::sub_array<T, size> r, size_t n) { foo_impl(r, n); }
2,129,263
2,169,192
How to build LLVM using GCC 4 on Windows?
I have been able to build LLVM 2.6 (the llvm-2.6.tar.gz package) using MinGW GCC 3.4.5. I haven't tested properly, but it seems to work. The trouble is, I have libraries of my own which don't build using GCC3, but which work fine in GCC4 (template issues). I believe the first official GCC4 version for MinGW is GCC 4.4.0. EDIT Decluttered - everything useful in the "tried this tried that" info is now in the answer. EDIT Most of this question/answer is redundant with LLVM 2.7 - the standard configure, make routine works fine in MinGW with no hacks or workarounds.
If at first you don't succeed... I can now build LLVM 2.6 using MinGW GCC 4.4.0, and it isn't too hard once you know how. I still cannot run the DejaGNU tests, though at first sight that shouldn't be that hard - most likely I'll need the CygWin packages for dejagnu and expect. I also haven't built llvm-gcc yet. Before the step-by-step, here are the three problems... Problem 1... Attempting to build llvm using the standard build instructions fails with the following compiler error in Signals.cpp (win32/Program.inc) llvm[1]: Compiling Signals.cpp for Release build In file included from Signals.cpp:33: Win32/Signals.inc: In function 'LONG LLVMUnhandledExceptionFilter(_EXCEPTION_POINTERS*)': Win32/Signals.inc:234: error: exception handling disabled, use -fexceptions to enable The workaround is to use "make -k -fexceptions" - answer found in the pure language documentation. Problem 2... Even with the first workaround, the following compiler error occurs... ExternalFunctions.cpp: In function 'bool ffiInvoke(void (*)(), llvm::Function*, const std::vector<llvm::GenericValue, std::allocator<llvm::GenericValue> >&, const llvm::TargetData*, llvm::GenericValue&)': ExternalFunctions.cpp:207: error: 'alloca' was not declared in this scope It seems that an option is being specified which disables the "alloca" built-in. The workaround is to edit the problem file C:\llvm-2.6\lib\ExecutionEngine\Interpreter\ExternalFunctions.cpp Just after the "#include <string>" line, insert... #define alloca __builtin_alloca Problem 3... Even with the compilation errors fixed, the example programs won't run. The run-time errors are... Assertion failed: errorcode == 0, file RWMutex.cpp, line 87 This relates to the use of the pthreads library, in the following lines of RWMutex.cpp 86: // Initialize the rwlock 87: errorcode = pthread_rwlock_init(rwlock, &attr); 88: assert(errorcode == 0); The basic issue is that pthreads support is included in MinGW GCC, and included in the builds of AFAICT all the GCC4 variants - including the unofficial TDM builds, as well as including MinGW GCC 4.4.0. This was not included with MinGW GCC 3.4.5, which is why LLVM builds fine with default options on that compiler. Using 4.4.0, the LLVM configure script detects the pthreads support and uses it - but the pthreads-w32 library used seems not to be fully compatible. One workaround is to delete the following files from mingw gcc 4.4.0 as suggested in http://markmail.org/message/d7zw2zjq7svevsci - yes, I know I previously said they weren't there, but I had my folder layout confused... mingw32\include\pthread.h mingw32\include\sched.h mingw32\include\semaphore.h mingw32\lib\libpthread.a It is better, though, to simply tell the configure script to disable threads... ./configure --disable-threads So, the steps are... First, install the following MinGW and MSYS packages... binutils-2.20-1-mingw32-bin.tar.gz mingwrt-3.17-mingw32-dev.tar.gz mingwrt-3.17-mingw32-dll.tar.gz w32api-3.14-mingw32-dev.tar.gz gcc-full-4.4.0-mingw32-bin-2.tar.lzma make-3.81-20090914-mingw32-bin.tar.gz tcltk-8.4.1-1.exe MSYS-1.0.11.exe msysDTK-1.0.1.exe bash-3.1.17-2-msys-1.0.11-bin.tar.lzma bison-2.4.1-1-msys-1.0.11-bin.tar.lzma flex-2.5.35-1-msys-1.0.11-bin.tar.lzma libregex-0.12-1-msys-1.0.11-dll-0.tar.lzma This package list may be more than needed - in particular tcl tk is only needed for the DejaGNU tests, which I haven't got working yet. Make sure that the \bin folder of your MinGW install is on the PATH (Control Panel, System, Advanced, Environment Variables). Extract llvm-2.6.tar.gz Edit the file C:\llvm-2.6\lib\ExecutionEngine\Interpreter\ExternalFunctions.cpp, and just after the line "#include <string>", add the line #define alloca __builtin_alloca Start an MSYS command prompt, and run... cd /c/llvm-2.6 ./configure --disable-threads make -k CXXFLAGS=-fexceptions I'm assuming you extracted llvm to c:\llvm-2.6 Handy hint - try "./configure --help" Consider the --enable-targets=host-only and --enable-doxygen configure script options in particular.
2,129,388
2,129,429
How to create a class to wrap GLUT?
I'm writing a game for school in OpenGL. Since there will be several more similar assignments I want to make a small framework for doing common things in OpenGL. I have made a few simple games before and I usually break it down into an IO class to handle input and drawing to the screen, Game class for the main game loop/logic, and classes for whatever objects there are in the game. Before I was using SDL, so my question is, is this the right way of going about this in OpenGL? I've already ran into some trouble. I want my IO class to handle initializing the window, drawing the scene, and mouse clicks. So the constructor looked like this: IO::IO() { currWindowSize[0] = DEF_WIDTH; currWindowSize[1] = DEF_HEIGHT; glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA ); glutInitWindowPosition( INIT_WINDOW_POSITION[0], INIT_WINDOW_POSITION[1] ); glutInitWindowSize( currWindowSize[0], currWindowSize[1] ); glutCreateWindow( "TEST" ); setUp(); glutDisplayFunc(drawScene); glutMainLoop(); } However, drawScene is a class method. Is there a way to pass a class method to glutDisplayFunc() without making it static?
Unfortunately the glutDisplayFunc() doesn't take a void* pointer so you could've fake an object context. You will have to make a static function that can call into the correct IO instance using a static variable. I see some slight trouble with your pattern also, though. As far as I know, glutMainLoop() never returns until you terminate the GLUT context, therefore you have a constructor that practically never returns, so your program flow is unreasonable. You should move that call into a separate run() method in your class. (Personally I would use GLFW, which avoids the entire callback mess with GLUT, although you have to write your mainloop.)
2,129,521
2,129,531
Why doesn't sizeof parse struct members?
I know that sizeof is a compile-time calculation, but this seems odd to me: The compiler can take either a type name, or an expression (from which it deduces the type). But how do you identify a type within a class? It seems the only way is to pass an expression, which seems pretty clunky. struct X { int x; }; int main() { // return sizeof(X::x); // doesn't work return sizeof(X()::x); // works, and requires X to be default-constructible }
An alternate method works without needing a default constructor: return sizeof(((X *)0)->x); You can wrap this in a macro so it reads better: #define member_sizeof(T,F) sizeof(((T *)0)->F)
2,129,645
2,129,664
Can you use wxMutex in an event handler?
Is it possible to use wxMutex->Lock() in an event handler? Since it's the main program thread (gui thread) it can't sleep right?
You certainly can - it's not going to blow up your computer or melt your hard drive or cause demons to fly out of your nostrils if you try. That said, doing anything on your UI thread that might block is bad, bad, bad, bad, bad. So while you technically can, you really shouldn't.
2,129,700
2,129,707
C++ Expected class-name before '{' token. Inheritance
I've been googling and reading about this and didn't come up with an answer yet, maybe someone can help me with this. I want my UserPile class to be able to access data members and class member functions from my CardPile class. I keep getting the error mention in the title. Could someone explain what is happening? The inheritance tutorials I have seen look just like my code except mine is multiple source code files. //CardPile.h #include <iostream> #include <string> #include <vector> using namespace std; class Card; class CardPile { protected: vector<Card> thePile; //Card thePile[]; int pileSize; public: CardPile(); void insertCard( Card ); Card accessCard( int); void displayPile(); void shuffle(); //shuffle the pile void initializeDeck(); //create deck of cards void deal(CardPile &, CardPile &); void showHand(); bool checkForAce(); void discard(CardPile); void drawCard(CardPile &); }; //UserPlayer.h using namespace std; class UserPlayer: public CardPile { private: //CardPile userPile; public: UserPlayer(); }; //UserPlayer.cpp #include "UserPlayer.h" #include "CardPile.h" UserPlayer::UserPlayer() { } I don't have anything happening in this UserPlayer class yet, because I will be using functions from the base class, so I want to at least see it compile before I start writing it. Thanks for anyone's help.
You have to include CardPile.h in UserPlayer.h if you want to use the class CardPile there. You are also missing include guards in the headers, e.g.: // CardPile.h: #ifndef CARDPILE_H #define CARDPILE_H class CardPile { // ... }; #endif Without this you are effectively including CardPile.h twice in UserPlayer.cpp - once from UserPlayer.h and once via the line #include "CardPile.h"
2,129,705
2,129,727
Why is (rand() % anything) always 0 in C++?
I am having trouble getting rand() to work in C++. rand() normally gives me a very large number. When I try to use the modulo operator (%) to give it a range, it always returns 0, no matter what. Seeding the random number generator at the beginning of the program doesn't help either.
The following code works just fine for me (emitting a random number between 0 included and 1000 excluded each time it's run): #include <cstdlib> #include <ctime> #include <iostream> int main() { std::srand(time(0)); std::cout<<(std::rand() % 1000)<<std::endl; return 0; }
2,129,718
2,129,733
Switch optimization for many cases guarantees equal access time for any case? ( C++ )
I've seen answers here for specific languages, about switches with more than 5 cases being optimized with jump tables to guarantee constant access time for any case. Is that so for C / C++? Is it in particular for gcc? for visual studio? If not, would sorting cases in order of occurrence frequency help?
The standard doesn't guarantee anything about how the switch statement will be implemented. I've never seen a compiler produce a hash table, though quite a few will produce a jump table. Unless my memory is working even worse than usual, both VS and gcc can produce jump tables when the cases are sufficiently dense (for different values of "sufficiently"). Unfortunately, it's almost impossible to say (or necessarily even figure out) when sorting by frequency of occurrence will help -- it's different not only between compilers, but even between different versions of the same compiler.
2,130,070
2,133,749
Specific Time Zone In boost::posix_time::ptime
I have the following time : 2010-01-25 03:13:34.384 - GMT Time Zone 2010-01-25 11:13:34.384 - My Local I wish to convert to timestamp in ms. However, since I only obtain local time string from caller "2010-01-25 11:13:34.384" If I do it this way : // ts is "2010-01-25 11:13:34.384" (My Local) boost::posix_time::ptime t(boost::posix_time::time_from_string(ts)); boost::posix_time::ptime end(boost::gregorian::date(1970,1,1)); boost::posix_time::time_duration dur = t - end; // epoch is 1264418014384 // 2010-01-25 11:13:34.384 (GMT) -- But I want 2010-01-25 03:13:34.384 // 2010-01-25 19:13:34.384 (My Local) -- But I want 2010-01-25 11:13:34.384 long long epoch = dur.total_milliseconds(); Is there any way to tell boost::posix_time, that the ts string which it receives, is belong to My Local timezone?
I have this in my local tree (namespace prefix omitted): /// wall-clock translation to UTC const ptime from_wall_clock( const ptime& value, const time_zone_ptr& from ) { assert( from.get()); // interpret as local time const local_date_time from_local( value.date(), value.time_of_day(), from, local_date_time::NOT_DATE_TIME_ON_ERROR ); // get UTC return from_local.utc_time(); }
2,130,099
2,175,786
storing line numbers of expressions with boost.spirit 2
I am planning on doing a script transformation utility (for extended diagnostic information) using Boost.Spirit 2. While there is support for line information etc. for parsing errors, how i can store line numbers for successfully parsed expressions with Qi?
As per the mailing list, Spirit.Classic positional iterators can also be used with Spirit 2. There is also an article on an iter_pos-parser on the Spirit-blog. I will update when i had time to test.
2,130,158
2,130,174
Is the number of types in a C++ template variant limited?
I'm trying to understand how variants are implemented, and reading: http://www.codeproject.com/KB/cpp/TTLTyplist.aspx And I'm getting the impression that I can't write a variant that takes X types; but that the template writer picks some N, and I can only have less than-N types in a variant. Is this correct? Thanks!
In C++03, there are no variadic templates. This means yes; you simply have to pick some N to go up to, and live with that. In C++0x, there will be variadic templates, so you could use one definition for all X. If you're looking to make changing the number easy, you can use Boost.Preprocessor and have it do the work for you: #define MAXIMUM_TYPELIST_SIZE 20 // or something struct empty{}; template <BOOST_PP_ENUM_BINARY_PARAMS(MAXIMUM_TYPELIST_SIZE, typename T, =empty)> struct typelist; template <BOOST_PP_ENUM_PARAMS(MAXIMUM_TYPELIST_SIZE, typename T)> struct typelist { typedef T1 head; typedef typelist< BOOST_PP_ENUM_PARAMS(BOOST_PP_DEC(MAXIMUM_TYPELIST_SIZE), T)> tail; enum { length = tail::length+1 }; }; If MAXIMUM_TYPELIST_SIZE were 5, those macro's would expand to what the article has. (Of course, if you're using Boost just use their meta-programming library.)
2,130,226
2,130,250
inline virtual function
In C++, my understanding is that virtual function can be inlined, but generally, the hint to inline is ignored. It seems that inline virtual functions do not make too much sense. Is that right? Can anybody give a case in which an inline virtual function is good?
Under normal circumstances, a virtual function will be invoked via a pointer to a function (that's contained in the class' vtable). That being the case, a virtual function call can only be generated inline if the compiler can statically determine the actual type for which the function will be invoked, rather than just that it must be class X or something derived from X. The primary time an inline virtual function makes sense is if you have a performance critical situation, and know that a class will frequently be used in a way that allows the compiler to determine the actual type statically (and at least one target compiler optimizes out the call via pointer).
2,130,291
2,130,363
App looking for an invalid dynamic library
alt text http://img63.imageshack.us/img63/5726/screenshot20100125at124.png I keep getting multiple error windows for an app i'm developing asking for ._libpal_bullet.dll when it should really be just libpal_bullet.dll. The weird thing is after I get all the error messages, the app runs anyway using the correct dlls that exist in the same directory. How can i get rid of these errors?
Thanks Extrakun, you indirectly helped me figure this one out. I guess this happens when you copy code between OSes. The problem was that there were duplicate files of these library names in the build folder. They were metadata files from OS X, which must have come over to the Windows side when I copied the folder to Windows. It's strange that they would be attempted to be executed even though they have different names to the proper DLLs. Anyway deleting the files (they were hidden!) solved the issue.
2,130,326
2,130,402
In wxwidgets, how do I lock a vector that is shared between gui thread and worker thread?
If I can't call lock on a mutex in the main application thread (my event handler because you can't lock the main gui thread), how do I share any information between my worker and my main thread?
Just have your worker thread communicate with the main thread through the event handling system. Use AddPendingEvent to send status messages back to the main thread and ProcessEvent to handle the updates.
2,130,387
2,130,400
Would These Be Considered Magic Numbers?
I've just completed writing a program for a programming class, and I want to avoid use of magic numbers, so here's my question: In the function below, would my array indexers be considered magic numbers? Code: string CalcGrade(int s1, int s2, int s3, double median) { const int SIZE = 23; const int LETTER_GRADE_BARRIERS[SIZE] = { 400, 381, 380, 361, 360, 341, 340, 321, 320, 301, 300, 281, 280, 261, 260, 241, 240, 221, 220, 201, 200, 181, 180 }; double finalGrade; string letterGrade; finalGrade = s1 + s2 + s3 + median; if (finalGrade >= LETTER_GRADE_BARRIERS[1] && finalGrade <= LETTER_GRADE_BARRIERS[0]) { letterGrade = "A"; } else if (finalGrade >= LETTER_GRADE_BARRIERS[3] && finalGrade <= LETTER_GRADE_BARRIERS[2]) { letterGrade = "A-"; } else if (finalGrade >= LETTER_GRADE_BARRIERS[5] && finalGrade <= LETTER_GRADE_BARRIERS[4]) { letterGrade = "B+"; } else if (finalGrade >= LETTER_GRADE_BARRIERS[7] && finalGrade <= LETTER_GRADE_BARRIERS[6]) { letterGrade = "B"; } else if (finalGrade >= LETTER_GRADE_BARRIERS[9] && finalGrade <= LETTER_GRADE_BARRIERS[8]) { letterGrade = "B-"; } else if (finalGrade >= LETTER_GRADE_BARRIERS[11] && finalGrade <= LETTER_GRADE_BARRIERS[10]) { letterGrade = "C+"; } else if (finalGrade >= LETTER_GRADE_BARRIERS[13] && finalGrade <= LETTER_GRADE_BARRIERS[12]) { letterGrade = "C"; } else if (finalGrade >= LETTER_GRADE_BARRIERS[15] && finalGrade <= LETTER_GRADE_BARRIERS[14]) { letterGrade = "C-"; } else if (finalGrade >= LETTER_GRADE_BARRIERS[17] && finalGrade <= LETTER_GRADE_BARRIERS[16]) { letterGrade = "D+"; } else if (finalGrade >= LETTER_GRADE_BARRIERS[19] && finalGrade <= LETTER_GRADE_BARRIERS[18]) { letterGrade = "D"; } else if (finalGrade >= LETTER_GRADE_BARRIERS[21] && finalGrade <= LETTER_GRADE_BARRIERS[20]) { letterGrade = "D-"; } else if (finalGrade <= LETTER_GRADE_BARRIERS[22]) { letterGrade = "Fail"; } return letterGrade; } Thanks!
Yes, any number other than -1,0 or 1 is probably a magic number. Unless you're a real guru, then you're probably allowed to use powers of two freely as well :-) As an aside, you could probably refactor that code to be a little more understandable, something like: string CalcGrade (int s1, int s2, int s3, double median) { // Grade lookup arrays. If grade is >= limit[n], string is grades[n]. // Anything below D- is a fail. static const int Limits[] = {400, 380, 360, 340,320, 300, 280,260, 240, 220,200,180 }; static const int Grades[] = {"A+","A","A-","B+","B","B-","C+","C","C-","D+","D","D-"}; double finalGrade = s1 + s2 + s3 + median; // Check each element of the array and, if the final grade is greater // than or equal to, return the grade string. for (int i = 0; i < sizeof(Limits) / sizeof(*Limits); i++) if (finalGrade >= Limits[i]) return Grades[i]; // Otherwise, failed. return "Fail"; } This removes the magic numbers spread all over the code to an area where it's immediately obvious how they work (assuming you align them nicely). It also removes a problem with your original solution as to what we do with someone that achieved a score of 380.5 - it's not really fair to fail those bods :-) Or to assign a grade to "" to those above 400 (since there doesn't appear to be a way to return "A+").
2,130,419
2,130,490
String hashing with linear probing
I am stuck trying to figure out how to do string hashing with linear probing. Basically, the idea is to hash every string from a dictionary (90000 words), and retrieve anagrams of selected words. Here's what I did: created a hash table 2*90000 in size using a simple hash function, I hash each word from the dictionary, get a value check if that hash table index is empty, if it is, assign the value, if not, generate a new hash value. after every word is in the hash table, and I perform a search the search word will receive a hash value after the hash function, and it will be checked whether that value exists in the hash table or not. if it exists, it will compare the string using permutations. if the match is true, it will output it. if not, it will keep looking using a new hash value. problem is, the whole process is extremely slow... it indexes fine, but searching takes REALLY long time. I am out of ideas on how to make this faster.. Thank you for your time reading this.
Put all the letters in alphabetical order first, then hash the result with any hashing algorithm you please (crc32, md5sum, sha1, count the vowels, anything... though counting the vowels will lead to a less-efficient solution), and store the word as a leaf node to that hash entry (in a linked list, obviously) -- do a mod(x) on the hash result to limit the buckets to 2^x. Then, when you go to find an anagram, do the exact same "insert" procedure on your test word: alphabetize the letters, then run it through your same hash function. Then for each leaf node, compare the alphabetized letter list with the saved word's alphabetized list. Each match is an anagram. (I normally don't like to give homework help, but this one was too tempting. Now I kind of want to go write a fun little program to find all the anagrams in a given dictionary.)
2,130,712
2,130,729
Sorting digits of an integer
You are given an integer 51234 (say) we need to sort the digits of a number the output will be 12345. How to do it without using array ?
You can use a loop and % 10 to extract each digit. An outer loop from 0 to 9 could be used to test if the digit exists. If it exists, print it. In pseudo code: n = integer // 51234 FOR digit = 0 TO 9 temp = n REPEAT IF temp % 10 = digit THEN PRINT digit temp /= 10 UNTIL temp = 0 Edit: This test in gcc shows that it handles zeros and repeated digits: $ cat sortdigits.c #include <stdio.h> main () { int n,digit,temp; n = 43042025; for (digit=0;digit<9;digit++) for (temp=n;temp>0;temp/=10) if (temp%10==digit) printf("%d",digit); printf("\n"); } $ ./sortdigits 00223445
2,130,802
2,133,783
WCF service with Qt?
I would like my Qt app to expose a service to another app written in .Net using WCF. Is there any support in Qt for implementing WCF services?
AFAIK there is no 'native' Qt support for WCF or extensions; however as you know WCF can consume and expose a web service (in addition to a WCF or remoting service, etc.) All you need to do is expose it as a Web Service for the other .NET app to consume. But that brings up an interesting aspect; usually you would write a windows service (I presume you are on Windows) which is exposed as a Web service rather than one via Qt. Qt is not ideal as it is a GUI framework (and a very good one); you will get into a few interesting situations as discussed here. It is usually easier to consume a web service with Qt as shown in this example. Do you have the option to expose your service using some other stack such as ASP.NET or WCF or Java?
2,130,838
2,130,887
Convert std::string to MSVC specific __int64
May I know how I can convert std::string, to MSVC specific __int64?
_atoi64, _atoi64_l, _wtoi64, _wtoi64_l std::string str = "1234"; __int64 v =_atoi64(str.c_str()); See also this link (although it is for linux/unix): Why doesn't C++ reimplement C standard functions with C++ elements/style?
2,130,864
2,130,953
Cannot access private member in singleton class destructor
I'm trying to implement this singleton class. But I encountered this error: 'Singleton::~Singleton': cannot access private member declared in class 'Singleton' This is flagged in the header file, the last line which contains the closing brace. Can somebody help me explain what is causing this problem? Below is my source code. Singleton.h: class Singleton { public: static Singleton* Instance() { if( !pInstance ) { if( destroyed ) { // throw exception } else { Create(); } } return pInstance; } private: static void Create() { static Singleton myInstance; pInstance = &myInstance; } Singleton() {} Singleton( const Singleton& ); Singleton& operator=( const Singleton& ); ~Singleton() { pInstance = 0; detroyed = false; } static Singleton* pInstance; static bool destroyed; }; Singleton.cpp: Singleton* Singleton::pInstance = 0; bool Singleton::destroyed = false; Inside my main function: Singleton* s = Singleton::Instance(); If I make the destructor as public, then the problem disappears. But a book (Modern C++ Design) says it should be private to prevent users from deleting the instance. I actually need to put some code for cleanup for pInstance and destroyed inside the destructor. By the way, I'm using Visual C++ 6.0 to compile.
You should probably have let us know that the version of Visual C++ you're working with is VC6. I can repro the error with that. At this point, I have no suggestion other than to move up to a newer version of MSVC if possible (VC 2008 is available at no cost in the Express edition). Just a couple other data points - VC2003 and later have no problem with the Singleton destructor being private as in your sample.
2,131,006
2,132,135
How to create a ReadWriteMutex without specifying the semaphore's resource count?
The usual pattern for a ReadWriteMutex is to use a semaphore and have the writer loop to acquire all the resources: inline void write_lock() { ScopedLock lock(acquire_mutex_); for (size_t i=0; i < resource_count_; ++i) { if (sem_wait(semaphore_) < 0) { fprintf(stderr, "Could not acquire semaphore (%s)\n", strerror(errno)); } } } This is fine except that you have to specify the resource count during semaphore initialization and arbitrarily choosing a resource count of 10 or 99999 does not feel right. Is there a better pattern that would allow "infinite" readers (no need for a resource count) ?
I found a solution: using pthread_rwlock_t (ReaderWriterLock on Windows). These locks do not require a specific 'max_readers_count'. I suspect that the implementation for this lock uses some kind of condition variable to lock readers entry when a writer needs to write and an atomic reader count. Comparing this with my homebrewed semaphore based lock shows that writers are favored (they tend to run first).
2,131,087
2,341,244
Creating dll from cpp files with nmake
There is a problem: i need to compile the dll from all source *.cpp files in a particular folder with a help of nmake. For example, cpp files stored in the folder ".\src", and they must be compiled into one dll. Where i can read about nmake? Or some examples?
Checkout nmake: build DLL
2,131,093
2,131,106
Distributing the Visual C++ Runtime Libraries (MSVCRT)
I have an ATL/WTL project developed using Visual Studio 2008 and up until now I have been statically linking with the CRT libraries, avoiding the need to ship them. However, I now need to consider using the dynamic libraries (DLL) instead - in order to reduce the size of the code and because I want to use the excellent crashrpt tool (which requires you dynamically link to the CRT.) Now, MS supply both a stand-alone installer (vcredist_x86.exe) and an MSM package but this is no good for me for two reasons: I am not using an MSI based installer (I am using InnoSetup). My application installs on a limited user account and the vcredist_x86.exe installer will not work. Therefore I want to ship the CRT DLLs and install then in my applications program folder. Now, this is something you can do as I found the following blog post by Martyn Lovell, the MSVC Libraries Development Lead that says: However, if you want to install-applocal, you should make sure that your application has a manifest, and then copy the whole of this folder into your EXE directory: X:\Program Files\Microsoft Visual Studio 8\VC\redist\x86\Microsoft.VC80.CRT and other folders if you use more than the CRT. Make sure you include the manifest. Just want I am after - except I don't understand this part: make sure that your application has a manifest My question is - how do I create an application manifest that references the CRT DLLs I want to use? The only manifest information my projects currently use is the following (which ensures the app uses v6 of the Common Controls): /manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\" Can someone provide me with instructions on how to work the manifest magic using Visual Studio 2008? There is a Microsoft.VC90.CRT.manifest file in my Visual Studio VC\redist\x86\Microsoft.VC90.CRT folder - do I need to use this somehow? Note: This is a similar - but different - question to this one.
Visual Studio will generate the correct manifest for you when you pass the /MD flag.
2,131,191
2,131,361
Is it recommended to trap SIGPIPE in bash script?
I have a problem while executing a bash script from C++ using the system call command. The script catches a SIGPIPE signal and exit with return code 141. This problem has started to appear only in the last release of my code. My Questions are as follows: Why does this SIGPIPE occur now and didn't occur before? Is it safe to ignore the SIGPIPE and what are the consequences?
1) That's very hard to answer without knowing exactly what you changed. 2) If a sequence of commands appears in a pipeline, and one of the reading commands finishes before the writer has finished, the writer receives a SIGPIPE signal. So whether you can ignore it depends on whether that is acceptable behavior for your script. More info here
2,131,397
2,167,139
How to get Shared Object in Shared Memory
Our app depends on an external, 3rd party-supplied configuration (including custom driving/decision making functions) loadable as .so file. Independently, it cooperates with external CGI modules using a chunk of shared memory, where almost all of its volatile state is kept, so that the external modules can read it and modify it where applicable. The problem is the CGI modules require a lot of the permanent config data from the .so as well, and the main app performs a whole lot of entirely unnecessary copying between the two memory areas to make the data available. The idea is to make the whole Shared Object to load into Shared Memory, and make it directly available to the CGI. The problem is: how? dlopen and dlsym don't provide any facilities for assigning where to load the SO file. we tried shmat(). It seems to work only until some external CGI actually tries to access the shared memory. Then the area pointed to appears just as private as if it was never shared. Maybe we're doing something wrong? loading the .so in each script that needs it is out of question. The sheer size of the structure, connected with frequency of calls (some of the scripts are called once a second to generate live updates), and this being an embedded app make it no-go. simply memcpy()'ing the .so into shm is not good either - some structures and all functions are interconnected through pointers.
I suppose the easiest option would be to use memory mapped file, what Neil has proposed already. If this option does not fill well, alternative is to could be to define dedicated allocator. Here is a good paper about it: Creating STL Containers in Shared Memory There is also excellent Ion Gaztañaga's Boost.Interprocess library with shared_memory_object and related features. Ion has proposed the solution to the C++ standardization committee for future TR: Memory Mapped Files And Shared Memory For C++ what may indicate it's worth solution to consider.
2,131,482
2,131,503
Can we use a timer for itself?
Actually this is what i want to do; When a condition appears, my program will close itself and after five minutes it will re-open. Is it possible with only one .exe -by using any OS property-? I do it with two .exe if (close_condition){ //call secondary program system ("secondary.exe"); return (0); } and my secondary program just waits for five minutes and calls the primary one. main (){ Sleep (300000)//sleep for five minutes; system ("primary.exe"); return (0); } i want to do it without secondary program. (sorry for poor english)
You can do it with one application that simply has different behaviour if a switch is given (say myapp.exe /startme). system() is a synchronous call by the way, it does only return when the command run is finished. In win32 CreateProcess() is what you are looking for. You can also just follow Jays suggestion of letting the OS schedule your job using NetScheduleJobAdd(). But, depending on what you're trying to achieve, a better solution might be to simply hide your application for 5 minutes.
2,131,604
2,131,809
How to implement a basic Variant (& a visitor on the Variant) template in C++?
I have tried reading: http://www.boost.org/doc/libs/1_41_0/boost/variant.hpp http://www.codeproject.com/KB/cpp/TTLTyplist.aspx and chapter 3 of "Modern C++ Design" but still don't understand how variants are implemented. Can anyone paste a short example of how to define something like: class Foo { void process(Type1) { ... }; void process(Type2) { ... }; }; Variant<Type1, Type2> v; v.somethingToSetupType1 ...; somethingToTrigger process(Type1); v.somethingToSetupType2 ...; somethingToTrigger process(Type2); Thanks!
If i had to define a variant object, i'd probably start with the following : template<typename Type1, typename Type2> class VariantVisitor; template<typename Type1, typename Type2> class Variant { public: friend class VariantVisitor<Type1, Type2>; Variant(); Variant(Type1); Variant(Type2); // + appropriate operators = ~Variant(); // deal with memory management private: int type; // 0 for invalid data, 1 for Type1, 2 for Type2 void* data; }; template<typename Visitor, typename Type1, typename Type2> class VariantVisitor { private: Visitor _customVisitor; public: void doVisit(Variant<Type1, Type2>& v) { if( v.type == 1 ) { _customVisitor( *(Type1*)(v.data)); } else if( v.type == 2 ) { _customVisitor( *(Type2*)(v.data)); } else { // deal with empty variant } } }; template<typename Visitor, typename Type1, typename Type2> void visit( Visitor visitor, Variant<Type1, Type2> v ) { VariantVisitor<Visitor, Type1, Type2>(visitor).doVisit(v); } then use MPL vectors to make the approach work for more than just two different types. In the end, you could write something like this : Variant<Type1, Type2> v; class MyVisitor { public: operator()(Type1); operator()(Type2); }; MyVisitor visitor; v = Type1(); visit(visitor, v); v = Type2(); visit(visitor, v); NB : there is no chance this code compiles, but this describes the ideas i'd use.
2,131,904
2,131,927
Trusting the Return Value Optimization
How do you go about using the return value optimization? Is there any cases where I can trust a modern compiler to use the optimization, or should I always go the safe way and return a pointer of some type/use a reference as parameter? Is there any known cases where the return value optimization cant be made?, Seems to me that the return value optimization would be fairly easy for a compiler to perform.
Whenever compiler optimizations are enabled (and in most compilers, even when optimizations are disabled), RVO will take place. NRVO is slightly less common, but most compilers will perform this optimization as well, at least when optimizations are enabled. You're right, the optimization is fairly easy for a compiler to perform, which is why compilers almost always do it. The only cases where it "can't be made" are the ones where the optimization doesn't apply: RVO only applies when you return an unnamed temporary. If you want to return a named local variable, NRVO applies instead, and while it is slightly more complex for a compiler to implement, it's doable, and modern compilers have no problem with it.
2,132,114
2,132,140
Recursive and non recursive procedures for trees
as we know that the trees are recursive data structures, We use recurrsion in writing the procedures of tree like delete method of BST etc. the advantage of recurrsion is, our procedures becomes very small (for example the code of inorder traversal is of only 4 or 5 lines) rather than a non recurrsive procedure which would be lengthy but not as complex as recurssive procedure in understanding perspective. that is why i hate recurrsion and i prefer to write non recurrsive procedure and i have done that in binary serach trees and avl trees. Now please elaborate that, prefering non recursive procedures over recurrsive procedures is bad or good thing."
Recursion is a tool like any other. You don't have to use every tool that's available but you should at least understand it. Recursion makes a certain class of problems very easy and elegant to solve and your "hatred" of it is irrational at best. It's just a different way of doing things. The "canonical" recursive function (factorial) is shown below in both recursive and iterative forms and, in my opinion, the recursive form more clearly reflects the mathematical definition of f(1) = 1, f(n) = n*f(n-1) for n>1. Iterative: Recursive: def fact(n): def fact(n): r = n if n == 1: while n > 1: return 1 r = r * n return n * fact(n-1) n = n - 1 return r Pretty much the only place I would prefer an iterative solution to a recursive one (for solutions that are really well suited for recursion) is when the growth in stack size may lead to problems (the above factorial function may well be one of those since stack growth depends on n but it may also be optimised to an iterative solution by the compiler). But this stack overflow rarely happens since: Most stacks can be configured where necessary. Recursion (especially tail-end recursion where the recursive call is the last thing that happens in the function) can usually be optimised to an iterative solution by an intelligent compiler. Most algorithms I use in recursive situations (such as balanced trees and so on, as you mention) tend to be O(logN) and stack use doesn't grow that fast with increased data. For example, you can process a 16-way tree storing two billion entries with only seven levels of stack (167 =~ 2.6 billion).
2,132,305
2,226,132
How to get a message request from its sequence number?
Given a sequence number, I need to find the corresponding request message string. I can't find a way to it easily do that with quickFix lib. To be short, I've had the idea to use the FileStore "body" file to help me retrieve the message request string from a sequence number,as the FileStore class exposes a convenient method: get(int begin, int end, std::vector result) But I am facing an issue: as those files are accessed by another FileStore instance (from the Initiator instance) those files are inaccessible from any other part of my application under Windows OS: as it forbids a second owner on the those files. Do I need to rewrite my own mechanism to get request message string form their sequence number?
I'm not sure why are you trying to get the 'message string' based on sequence number. Is this during trading? Can you modify your application code? Your application gets the messages from the server/client so you can just dump the message as string (in c++ they have methods something to do with ToString() or similar). You could keep the string in a dictionary with the sequence number as id and so on. The library gets you to peek at the outgoing messages as well. If it is after traiding the messages you can set the engine to create data files and then just process the data file, it has all the messages received and sent. Sorry, I just can't figure out what exactly you are trying to use.
2,132,747
4,563,701
Warning C4251 when building a DLL that exports a class containing an ATL::CString member
I am converting an ATL-based static library to a DLL and am getting the following warning on any exported classes that use the ATL CString class (found in atlstr.h): warning C4251: 'Foo::str_' : class 'ATL::CStringT' needs to have dll-interface to be used by clients of class 'Foo' I am correctly declaring the Foo class as exported via __declspec(dllexport). Is this a warning I can safely ignore or am I doing something wrong? The DLL project settings are set to dynamically link with ATL, but this doesn't seem to make any difference. For example: #ifdef DLLTEST_EXPORTS #define DLLTEST_API __declspec(dllexport) #else #define DLLTEST_API __declspec(dllimport) #endif // This class is exported from the DLLTest.dll class DLLTEST_API Foo { public: Foo(); CString str_; // WARNING C4251 HERE }; All clients of this DLL will also be using ATL.
This thread gives what I consider a better answer, by Doug Harrison (VC++ MVP): [This warning is] emitted when you use a non-dllexported class X in a dllexported class Y. What's so bad about that? Well, suppose Y has an inline function y_f that calls a function x_f belonging to X that is not also inline. If y_f is inlined inside some client that doesn't statically link X, the link will fail, because x_f won't be found.
2,132,904
2,133,244
Externalizing parameters for VS2008 C++ project compilation
Is there some way to externalize the paths of libraries that are used in the compilation process on Visual Studio 2008? Like, *.properties files? My goal is to define "variables" referencing locations to headers files and libraries, like *.properties files are used in the Ant build system for Java.
I think you're looking for .vsprops files. They're comparable to the *.properties files.
2,133,103
2,133,149
Passing platform-specific data in a platform independent design?
I have a game engine design written in C++ where a platform-independent game object is contained within a platform-specific Application object. The problem I'm trying to solve is the case where I need to pass OS-specific data from the Application to the game. In this case, I'd need to pass the main HWND from Windows for DirectX or an OpenGL context for the other platforms to the renderer I'm using. Unfortunately I have little control over the renderer, which can expect platform-specific data. I realize I could initialize the renderer on the Application side, but I'd rather have the game decide when and where to do it. Generally, I have control over the Application side but not the game side. The game writer might choose to use a different renderer. I've also entertained the idea of having some kind of "Property Manager" where I can pass data around through strings, but I don't like that idea very much. Any ideas?
Remember that you only need to know the target platform at compile time. With this information, you can 'swap in and out' components for the correct platform. In a good design, the Game should not require any information about it's platform; it should only hold the logic and related components. Your 'Engine' classes should worry about the platform. The Game classes should only interface with the Engine objects via public functions that aren't specific to the platform; you can have multiple versions of the Engine objects for each platform, and choose which one to use at compile time. For example, you could have a Texture 'engine' class that represents a texture in the game. If you support OS X and Windows, you could have a "Texture.h" which includes "Windows/Texture.h" or "OSX/Texture.h" depending on the platform you're compiling on. Both headers will define a Texture class with the same interface (i.e. they'll both have the same public functions with the same arguments), but their implementation will be platform-specific. To clarify, the Game should tell the Application to initialize the Renderer; there should be a strict line between the game logic and the implementation details. The renderer is an implementation detail, not part of the game logic. The game classes should know nothing about the system and only about the game world.
2,133,185
2,133,501
How to get Default JVM INITIAL ARGS In JNI
I'm trying to get the default jvm args of the available JVM but I'm getty a strange output. Anyone can point me to what's wrong? Output: 65542 �p����Y����k�.L�R���g���J����sk��,��*�Jk��xk�� Code: #include "jni.h" #include <iostream> #include <dlfcn.h> #include <cstdlib> using namespace std; void * JNI_FindCreateJavaVM(char *vmlibpath) { void *libVM = dlopen(vmlibpath, RTLD_LAZY); if (libVM == NULL) { return NULL; } return dlsym(libVM, "JNI_GetDefaultJavaVMInitArgs"); } int main() { JavaVMOption vm_options; JavaVMInitArgs vm_args; vm_args.version = JNI_VERSION_1_6; vm_args.ignoreUnrecognized = JNI_FALSE; vm_args.options = &vm_options; void* (*lib_func)(void *) = 0; lib_func = (void*(*)(void*)) JNI_FindCreateJavaVM( "/usr/lib/jvm/java-6-sun/jre/lib/i386/client/libjvm.so"); lib_func(&vm_args); cout << vm_args.version << endl; cout << vm_args.options[0].optionString << endl; return 0; }
The prototype for JNI_GetCreatedJavaVMs is: jint JNI_GetCreatedJavaVMs(JavaVM **vmBuf, jsize bufLen, jsize *nVMs); You call the function with a *JavaVMInitArgs parameter and I am not sure why you expect your code to print anything reasonable.
2,133,250
2,133,260
"X does not name a type" error in C++
I have two classes declared as below: class User { public: MyMessageBox dataMsgBox; }; class MyMessageBox { public: void sendMessage(Message *msg, User *recvr); Message receiveMessage(); vector<Message> *dataMessageList; }; When I try to compile it using gcc, it gives the following error: MyMessageBox does not name a type
When the compiler compiles the class User and gets to the MyMessageBox line, MyMessageBox has not yet been defined. The compiler has no idea MyMessageBox exists, so cannot understand the meaning of your class member. You need to make sure MyMessageBox is defined before you use it as a member. This is solved by reversing the definition order. However, you have a cyclic dependency: if you move MyMessageBox above User, then in the definition of MyMessageBox the name User won't be defined! What you can do is forward declare User; that is, declare it but don't define it. During compilation, a type that is declared but not defined is called an incomplete type. Consider the simpler example: struct foo; // foo is *declared* to be a struct, but that struct is not yet defined struct bar { // this is okay, it's just a pointer; // we can point to something without knowing how that something is defined foo* fp; // likewise, we can form a reference to it void some_func(foo& fr); // but this would be an error, as before, because it requires a definition /* foo fooMember; */ }; struct foo // okay, now define foo! { int fooInt; double fooDouble; }; void bar::some_func(foo& fr) { // now that foo is defined, we can read that reference: fr.fooInt = 111605; fr.foDouble = 123.456; } By forward declaring User, MyMessageBox can still form a pointer or reference to it: class User; // let the compiler know such a class will be defined class MyMessageBox { public: // this is ok, no definitions needed yet for User (or Message) void sendMessage(Message *msg, User *recvr); Message receiveMessage(); vector<Message>* dataMessageList; }; class User { public: // also ok, since it's now defined MyMessageBox dataMsgBox; }; You cannot do this the other way around: as mentioned, a class member needs to have a definition. (The reason is that the compiler needs to know how much memory User takes up, and to know that it needs to know the size of its members.) If you were to say: class MyMessageBox; class User { public: // size not available! it's an incomplete type MyMessageBox dataMsgBox; }; It wouldn't work, since it doesn't know the size yet. On a side note, this function: void sendMessage(Message *msg, User *recvr); Probably shouldn't take either of those by pointer. You can't send a message without a message, nor can you send a message without a user to send it to. And both of those situations are expressible by passing null as an argument to either parameter (null is a perfectly valid pointer value!) Rather, use a reference (possibly const): void sendMessage(const Message& msg, User& recvr);
2,133,583
2,455,330
WIX C++ Custom Action
I have a basic WIX custom action: UINT __stdcall MyCustomAction(MSIHANDLE hInstaller) { DWORD dwSize=0; MsiGetProperty(hInstaller, TEXT("MyProperty"), TEXT(""), &dwSize); return ERROR_SUCCESS; } Added to the installer: <CustomAction Id="CustomActionId" FileKey="CustomDll" DllEntry="MyCustomAction"/> <InstallExecuteSequence> <Custom Action="CustomActionId" Before="InstallFinalize" /> </InstallExecuteSequence> The problem is that, no matter what i do, the handle hInstaller is not valid. I've set the action to commit, deferred, changed the place in InstallExecute sequence, hInstaller is always not valid. Any help would be appreciated. Thanks.
You need to export the called function so MSI can call it using undecorated C style name Replace your code with this extern "C" _declspec(dllexport) UINT __stdcall MyCustomAction(MSIHANDLE hInstall); extern "C" UINT __stdcall MyCustomAction(MSIHANDLE hInstall) { DWORD dwSize=0; MsiGetProperty(hInstaller, TEXT("MyProperty"), TEXT(""), &dwSize); return ERROR_SUCCESS; }
2,133,630
2,133,670
Can a class method be both inline and static?
Does it even make sense?
static means that the method isn't associated with an instance of a class. (i.e. it has no "this" pointer). inline is a compiler hint that the code for the method ought to be included inline where it is called, instead of being called via a normal branch. (Be aware that many compilers ignore this keyword, and use their own metrics to decide whether to inline). These are orthogonal (unrelated) concepts, so there's no particular reason they couldn't be combined.
2,133,651
2,133,952
Spectrogram C++ library
For my current project in C++ / Qt I need a library (LGPL is preferred) which can calculate a spectrogram from a signal ( basically an array of doubles ). I already use Qwt for the GUI part. Any suggestions? Thanks.
It would be fairly easy to put together your own spectrogram. The steps are: window function (fairly trivial, e.g. Hanning) FFT (FFTW would be a good choice but if licensing is an issue then go for Kiss FFT or similar) calculate log magnitude of frequency domain components (trivial: log(sqrt(re * re + im * im))
2,133,903
2,133,934
Convert float to bigint (aka portable way to get binary exponent & mantissa)
In C++, I have a bigint class that can hold an integer of arbitrary size. I'd like to convert large float or double numbers to bigint. I have a working method, but it's a bit of a hack. I used IEEE 754 number specification to get the binary sign, mantissa and exponent of the input number. Here is the code (Sign is ignored here, that's not important): float input = 77e12; bigint result; // extract sign, exponent and mantissa, // according to IEEE 754 single precision number format unsigned int *raw = reinterpret_cast<unsigned int *>(&input); unsigned int sign = *raw >> 31; unsigned int exponent = (*raw >> 23) & 0xFF; unsigned int mantissa = *raw & 0x7FFFFF; // the 24th bit is always 1. result = mantissa + 0x800000; // use the binary exponent to shift the result left or right int shift = (23 - exponent + 127); if (shift > 0) result >>= shift; else result <<= -shift; cout << input << " " << result << endl; It works, but it's rather ugly, and I don't know how portable it is. Is there a better way to do this? Is there a less ugly, portable way to extract the binary mantissa and exponent from a float or double? Thanks for the answers. For posterity, here is a solution using frexp. It's less efficient because of the loop, but it works for float and double alike, doesn't use reinterpret_cast or depend on any knowledge of floating point number representations. float input = 77e12; bigint result; int exponent; double fraction = frexp (input, &exponent); result = 0; exponent--; for (; exponent > 0; --exponent) { fraction *= 2; if (fraction >= 1) { result += 1; fraction -= 1; } result <<= 1; }
Can't you normally extract the values using frexp(), frexpf(), frexpl()?
2,134,165
2,137,872
C++ Design pattern for Search and Replace
I have big paragraph with some special characters as %1 , %2, %3 I need to know if there is any design pattern to replace those with proper values and create final paragraph. For Example: Following is my static paragraph. %1 is beautiful country , %2 is the capital of %1, %1 national language is %3. I get values of %1,%2, %3 by some source.
you can use strstr or sscanf to find string pointers to a semi-pattern(both are part of the c std library), how ever, to replace, you would need to expand the memory block to accommodate the replacements(if they are bigger), have a look at grep(for unix), or see some of the string search algo's, like Boyer-Moore. You can also have a look at the google template system or pegtl
2,134,329
2,136,482
Are multiline tooltips possible using CWnd::EnableTooltips()?
I'm attempting to make my tooltips multiline, but I don't seem to be having much luck with it. I call CWnd::EnableTooltips() directly after creation (in this case, an edit box) and I handle the TTN_NEEDTEXT message. My tooltips display correctly, but only display as a single line. I've tried adding '\n' to the string I pass when handling TTN_NEEDTEXT, and also tried '\r\n'. No luck. It just displays them as normal text in the tooltip string. I then tried manually inserting 0x0D0A, but this just displays as boxes. I've been digging a bit, and have found a few offhand references on the web saying that multiline behavior may not work when using tooltips through the CWnd functions. I'd prefer not to have to replace with CToolTipCtrl (since it's a rather large project). Has anyone ran into this before? If so, is there any way around it?
I was successful in making a \n delimited tooltip into a multi-line tooltip using the following code in the TTN_NEEDTEXT handler For DevStudio 6 CToolTipCtrl* pToolTip = AfxGetThreadState()->m_pToolTip; pToolTip->SetMaxTipWidth(SHRT_MAX); You have to call again each time TTN_NEEDTEXT is called or it won't stick. I found this trick reading the code from http://www.codeproject.com/KB/list/CListCtrl_ToolTip.aspx NOTE: the code there actually does the following but that won't compile in VS6 as the ModuleThreadState doesn't have the m_pToolTip member in VS6 (I haven't tried the following in VS2005+ but i presume it would work there) BOOL CListCtrl_EnableToolTip::OnToolNeedText(UINT id, NMHDR* pNMHDR, LRESULT* pResult) { ... // Break tooltip into multiple lines if it contains newlines (/n/r) CToolTipCtrl* pToolTip = AfxGetModuleThreadState()->m_pToolTip; if (pToolTip) pToolTip->SetMaxTipWidth(SHRT_MAX); ... }
2,134,363
2,134,389
The C `clock()` function just returns a zero
The C clock() function just returns me a zero. I tried using different types, with no improvement... Is this a good way to measure time with good precision? #include <time.h> #include <stdio.h> int main() { clock_t start, end; double cpu_time_used; char s[32]; start = clock(); printf("\nSleeping 3 seconds...\n\n"); sleep(3); end = clock(); cpu_time_used = ((double)(end - start)) / ((double)CLOCKS_PER_SEC); printf("start = %.20f\nend = %.20f\n", start, end); printf("delta = %.20f\n", ((double) (end - start))); printf("cpu_time_used = %.15f\n", cpu_time_used); printf("CLOCKS_PER_SEC = %i\n\n", CLOCKS_PER_SEC); return 0; } Sleeping 3 seconds... start = 0.00000000000000000000 end = 0.00000000000000000000 delta = 0.00000000000000000000 cpu_time_used = 0.000000000000000 CLOCKS_PER_SEC = 1000000 Platform: Intel 32 bit, RedHat Linux, gcc 3.4.6
clock() reports CPU time used. sleep() doesn't use any CPU time. So your result is probably exactly correct, just not what you want.
2,134,384
2,134,792
How to use ETW from a C++ Windows client
I'm researching Event Tracing for Windows (ETW) to allow a user-mode windows client to write out tracing information. The existing documentation is, to put it lightly, insanely incomplete. What would really help is a simple C++ example that writes out tracing messages using ETW. Does such an example exist? Is there other ETW documentation you might recommend?
To write a Provider for ETW, you have two options: write it as a manifest-based provider (preferred for Windows Vista or higher). Check out an example here. write it as a classic provider for legacy support. You can find an example here. I suppose you want to use a manifest-based approach, as its better and can support up to eight sessions. The first step a manifest-based provider needs to do is to register the event using EventRegister() and then write to it via the EventWrite() or EventWriteString() function.
2,134,391
2,179,747
Create an interactive logon session
I'm trying to create a utility similar to Microsoft's abandoned Super Fast User Switcher (download), which allows fast user switching without going through the Welcome screen. I have a working implementation using the undocumented WinStationConnectW API (along with WTSEnumerateSessions), but it can only switch to a user who is already logged in. How can I create a login session so that it can switch to a user who is not logged in? I only need to support XP, although it'd be nice to work on Vista / Seven. (My current code already does) I know that this is possible because Super Fast User Switcher does it. (Although it needs a Windows service to do it) I'm writing C#, but I can translate any answer into C#.
I solved this in XP by calling the undocumented InitiateInteractiveLogon function in the ShellLocalMachine COM object in shgina.dll. This method, which can only be called by the Local System account, will log a user on to the console. (It cannot log a user on to an RDP session) The version of the DLL included with Windows 7 (and presumably also Vista) does not contain this method.
2,134,758
2,135,455
Unittest++: test for multiple possible values
i am currently implementing a simple ray tracer in c++. I have a class named OrthonormalBasis, which generates three orthogonal unit vectors from one or two specified vectors, for example: void OrthonormalBasis::init_from_u ( const Vector& u ) { Vector n(1,0,0); Vector m(0,1,0); u_ = unify(u); v_ = cross(u_,n); if ( v_.length() < ONB_EPSILON ) v_ = cross(u_,m); w_ = cross(u_,v_); } I am testing all my methods with the Unittest++ framework. The Problem is, that there is more than one possible solution for a valid orthonormal basis. For example this test: TEST ( orthonormalbasis__should_init_from_u ) { Vector u(1,0,0); OrthonormalBasis onb; onb.init_from_u(u); CHECK_EQUAL( Vector( 1, 0, 0 ), onb.u() ); CHECK_EQUAL( Vector( 0, 0, 1 ), onb.v() ); CHECK_EQUAL( Vector( 0, 1, 0 ), onb.w() ); } sometimes it succeeds, sometimes it fails, because the vectors v and w could also have a negative 1, and still represent a valid orthonormal basis. Is there a way to specify multiple expected values? Or do you know another way to do that? It is important, that i get the actual and expected values printed to the stdout, in order to debug the methods so this solution won't do the job: TEST ( orthonormalbasis__should_init_from_u ) { Vector u(1,0,0); OrthonormalBasis onb; onb.init_from_u(u); CHECK_EQUAL( Vector( 1, 0, 0 ), onb.u() ); CHECK( Vector( 0, 0, 1 ) == onb.v() || Vector( 0, 0,-1 ) == onb.v() ); CHECK( Vector( 0, 1, 0 ) == onb.w() || Vector( 0,-1, 0 ) == onb.w() ); }
Surely if all you are testing is whether your basis is orthonormal, then that's what you need to test? // check orthogonality CHECK_EQUAL( 0, dot(onb.u(), onb.v)); CHECK_EQUAL( 0, dot(onb.u(), onb.w)); CHECK_EQUAL( 0, dot(onb.v(), onb.w)); // check normality CHECK_EQUAL( 1, dot(onb.u(), onb.u)); CHECK_EQUAL( 1, dot(onb.v(), onb.v)); CHECK_EQUAL( 1, dot(onb.w(), onb.w));
2,134,836
2,134,874
What Linux library supports sockets, ioctl calls, tuntap, etc...?
What is the name of the runtime library which implements Linux network interfaces, like sockets, tuntaps, netlink, etc...? For example when I create an UDP socket and make an ioctl call to fetch network interface info, which library actually implements that call? What are the corresponding *.so files on most linux dstirbutions?
These are c library calls, and as such are in the libc library.
2,134,844
2,134,876
Why can't I put a "using" declaration inside a class declaration?
I understand the troubles you can get into when you put a using declaration inside a header file, so I don't want to do that. Instead I tried to put the using (or a namespace foo =) within the class declaration, to cut down on repetitive typing within the header file. Unfortunately I get compiler errors. Seems like it would be a useful feature. #ifndef FOO_H #define FOO_H // This include defines types in namespace gee::whiz::abc::def, // such as the class Hello. #include "file_from_another_namespace.h" // using namespace gee::whiz::abc::def; // BAD! namespace x { namespace y { namespace z { struct Foo { using namespace gee::whiz::abc::def; // Illegal. namespace other = gee::whiz::abc::def; // Illegal. // Foo(gee::whiz::abc::def::Hello &hello); // annoyingly long-winded Foo(other::Hello &hello); // better //... }; } } } // end x::y::z namespace #endif // FOO_H In the real code, the namespace names are much longer and annoying and it's not something I can change. Can anyone explain why this is not legal, or (better) if there's a workaround?
Could you do typedef gee::whiz::abc::def::Hello Hello?
2,134,943
2,134,975
Which overloaded version of operator will be called
Suppose i have declared subscript operators in a class char& operator[] (int index); const char operator[](int index) const; In what condition the second overload is called. Is it only called through a const object. In the following scenarios which version of operator will be called. const char res1 = nonConstObject[10]; nonConstObject[10];
The first one is called. Don't get confused by the return value; only the arguments are considered to select the method. In this case, the implicit this is non-const, so the non-const version is called.
2,135,036
2,135,085
How to export C++ function as a dll that throws exception?
When I try to export the following function as a dll: extern "C" __declspec(dllexport) void some_func() { throw std::runtime_error("test throwing exception"); } Visual C++ 2008 gives me the following warning: 1>.\SampleTrainer.cpp(11) : warning C4297: 'some_func' : function assumed not to throw an exception but does 1> The function is extern "C" and /EHc was specified I need to extern "C" because I use Qt QLibrary to load the dll and resolve the function name. Without extern "C" it can't find the some_func() function.
If you are determined to do what the compiler is warning you about, why not just suppress the warning? #pragma warning(disable: 4247)
2,135,094
2,135,268
gcc reverse_iterator comparison operators missing?
I am having a problem using const reverse iterators on non-const containers with gcc. Well, only certain versions of gcc. #include <vector> #include <iostream> using namespace std; int main() { const char v0[4] = "abc"; vector<char> v(v0, v0 + 3); // This block works fine vector<char>::const_iterator i; for (i = v.begin(); i != v.end(); ++i) cout << *i; cout << endl; // This block generates compile error with gcc 3.4.4 and gcc 4.0.1 vector<char>::const_reverse_iterator r; for (r = v.rbegin(); r != v.rend(); ++r) cout << *r; cout << endl; return 0; } This program compiles OK and runs with gcc 4.2.1 (Mac Leopard) and with Visual Studio 8 and 9 (Windows), and with gcc 4.1.2 (Linux). However, there is a compile error with gcc 3.4.4 (cygwin) and with gcc 4.0.1 (Mac Snow Leopard). test.cpp:18: error: no match for 'operator!=' in 'r != std::vector<_Tp, _Alloc>::rend() [with _Tp = char, _Alloc = std::allocator<char>]()' Is this a bug in earlier versions of gcc? Due to other problems with gcc 4.2.1 on Mac, we need to use gcc 4.0.1 on Mac, so simply using the newer compiler is not a perfect solution for me. So I guess I need to change how I use reverse iterators. Any suggestions?
It is a defect in the current standard: http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#280 Edit: Elaborating a bit: The issue is that, in the current standard: vector::reverse_iterator is specified as std::reverse_iterator<vector::iterator>, and vector::const_reverse_iterator as std::reverse_iterator<vector::const_iterator>. The relational operators on std::reverse_iterator are defined with a single template parameter, making reverse_iterator<iterator> and reverse_iterator<const_iterator> non-comparable. In your code, you compare a const_reverse_iterator with the result of calling "rend()" on a non-const vector, which is a (non-const) reverse_iterator. In C++0x, two related changes are made to fix issues like this: Relational operators on reverse_iterator now take two template parameters Containers like vector have extra methods to explicitely request a const_iterator: cbegin(), cend(), crbegin() and crend(). In your case, a workaround would be to explicitely request the const_reverse_iterator for rend(): vector<char>::const_reverse_iterator r; const vector<char>::const_reverse_iterator crend = v.rend(); for (r = v.rbegin(); r != crend; ++r) cout << *r;
2,135,116
2,135,469
How can I determine distance from an object in a video?
I have a video file recorded from the front of a moving vehicle. I am going to use OpenCV for object detection and recognition but I'm stuck on one aspect. How can I determine the distance from a recognized object. I can know my current speed and real-world GPS position but that is all. I can't make any assumptions about the object I'm tracking. I am planning to use this to track and follow objects without colliding with them. Ideally I would like to use this data to derive the object's real-world position, which I could do if I could determine the distance from the camera to the object.
When you have moving video, you can use temporal parallax to determine the relative distance of objects. Parallax: (definition). The effect would be the same we get with our eyes which which can gain depth perception by looking at the same object from slightly different angles. Since you are moving, you can use two successive video frames to get your slightly different angle. Using parallax calculations, you can determine the relative size and distance of objects (relative to one another). But, if you want the absolute size and distance, you will need a known point of reference. You will also need to know the speed and direction being traveled (as well as the video frame rate) in order to do the calculations. You might be able to derive the speed of the vehicle using the visual data but that adds another dimension of complexity. The technology already exists. Satellites determine topographic prominence (height) by comparing multiple images taken over a short period of time. We use parallax to determine the distance of stars by taking photos of night sky at different points in earth's orbit around the sun. I was able to create 3-D images out of an airplane window by taking two photographs within short succession. The exact technology and calculations (even if I knew them off the top of my head) are way outside the scope of discussing here. If I can find a decent reference, I will post it here.
2,135,199
2,135,232
How to compile this on Windows
Ok. I am trying to compile the following application on Windows (Segmenter, see step 3). I checked out the source and changed the references so that'd all be good. It's basically a one file app, with a reference to ffmpeg. The makefile reads: gcc -Wall -g segmenter.c -o segmenter -lavformat -lavcodec -lavutil -lbz2 -lm -lz -lfaac -lmp3lame -lx264 -lfaad I have the Visual C++ compiler, but I just have no clue how to compile the above line using that compiler, or should I grab Gcc for Windows?
The line indicates a very simple compile. It's compiling the file with one standard argument (-g for compiling with debug symbols, on MSVC it's /Zi). But it's linking with a lot of libraries (that's all the -l options). I recognize two of those as standard compression libraries (bz2 and z), so you are going to need to build those libraries first.
2,135,355
2,135,468
Crash, while printing contents of linked-list
I'm having some trouble printing out the contents of a linked list. I'm using an example code that I found somewhere. I did edit it a bit, but I don't think that's why it's crashing. class stringlist { struct node { std::string data; node* next; }; node* head; node* tail; public: BOOLEAN append(std::string newdata) { if (head) { tail->next = new node; if (tail->next != NULL) { tail=tail->next; tail->data = newdata; return TRUE; } else return FALSE; } else { head = new node; if (head != NULL) { tail = head; head->data = newdata; return TRUE; } else return FALSE; } } BOOLEAN clear(std::string deldata) { node* temp1 = head; node* temp2 = NULL; BOOLEAN result = FALSE; while (temp1 != NULL) { if (temp1->data == deldata) { if (temp1 == head) head=temp1->next; if (temp1==tail) tail = temp2; if (temp2 != NULL) temp2->next = temp1->next; delete temp1; if (temp2 == NULL) temp1 = head; else temp1 = temp2->next; result = TRUE; } else // temp1->data != deldata { temp2 = temp1; temp1 = temp1->next; } } return result; } BOOLEAN exists(std::string finddata) { node* temp = head; BOOLEAN found = FALSE; while (temp != NULL && !found) { if (temp->data == finddata) found=true; else temp = temp->next; } return found; } void print() { node* tmp = head; while (tmp) { printf("%s", tmp->data.c_str()); tmp = tmp->next; } } stringlist() { head=NULL; tail=NULL; } }; My main() function is really simple: int main() { stringlist mylist; if (mylist.append("something")) count++; if (mylist.append("else")) count++; if (mylist.append("yet")) count++; cout<<"Added "<<count<<" items\n"; mylist.print(); return 0; } For some reason in Print() tmp is never NULL
As @rmn pointed out, you're not initializing the value of node->next. BOOLEAN append(std::string newdata) { if (head) { tail->next = new node; if (tail->next != NULL) { tail=tail->next; tail->data = newdata; tail->next = NULL; // <- this is the part that is missing return TRUE; } else return FALSE; } else { head = new node; if (head != NULL) { tail = head; head->data = newdata; head->next = NULL; // <- it's also missing here. return TRUE; } else return FALSE; } } You could solve this by having a default constructor for node: struct node { std::string data; node* next; node() : next(NULL) { } }; With the default constructor you won't need to add tail->next = NULL;.
2,135,397
2,137,352
Design options for references into a thread safe cache when evicting older entries
I'm trying to design a simple cache that follows the following rules: Entries have a unique key When the number of entries in the cache exceeds a certain limit, the older items are evicted (to keep the cache from getting too large). Each entry's data is immutable until the entry is removed from the cache. A 'reader' can access an entry in the cache and the entry must be valid for the lifetime of the reader. Each reader can be on its own thread, and all readers access the same cache instance. Thread safety with this cache is important, since we don't want readers holding a reference to an entry, only to have it evicted by another thread somewhere else. Hence, my current implementation just copies out the whole entry when reading from the cache. This is fine for smaller objects, but once objects get too large there's too much copying going on. It's also not so great with large numbers of readers that are accessing the same cached entry. Since the data is immutable, it would be great if every reader to the same message could just hold a reference instead of a copy, but in some thread safe manner (so it wouldn't get evicted). A previous implementation used reference counting to achieve this...but it's very tricky with threads, and I went with this simpler approach. Are there any other patterns/ideas I could use to improve this design?
In a native system without a higher power (such as a VM) capable of performing garbage collection, you aren't going to do much better performance or complexity wise than reference counting. You are are correct the reference counting can be tricky - not only does the increment and decrement have to atomic, but you need to ensure that the object can't be deleted out from under you before you are able to increment it. Thus, if you store the reference counter inside the object, you'll have to somehow avoid the race that occurs between the time you read the pointer to the object out of the cache, and manage to increment the pointer. If your structure is a standard container, which is not already thread-safe, you will also have to protect the container from unsupported concurrent access. This protection can dovetail nicely with avoiding the reference counting race condition described above - if you use a read-writer lock to protect the structure, combined with atomic increments of the in-object reference counter while still holding the reader lock, you'll be protected from anyone deleting the object out from under you before you get the reference count, since such mutators must be "writers". Here, objects can be evicted from the cache while still having a positive reference count - they will be destroyed when the last outstanding reference is dropped (by your smart pointer class). This is typically considered a feature, since it means that at least some object can always be removed from the cache, but it also has the downside that there is no strict upper on the number of objects "alive" in memory, since the reference counting allows objects to say alive even after they've left the cache. Whether this is acceptable to you depends on your requirements and details such as how long other threads may hold references to objects. If you don't have access to (non-standard) atomic increment routines, you can use a mutex to do the atomic increment/decrement, although this may increase the cost significantly in both time and per-object space. If you want to get more exotic (and faster) you'll need to design a container which is itself threadsafe, and come up with a more complex reference counting mechanism. For example, you may be able to create a hash table where the primary bucket array is never re-allocated, so can be accessed without locking. Furthermore, you can use non-portable double-wide CAS (compare and swap) operations on that array to both read a pointer and increment a reference count adjacent to it (128 bits of stuff on a 64-bit arch), allowing you to avoid the race mentioned above. A completely different track would be to implement some kind of "delayed safe delete" strategy. Here avoid reference counting entirely. You remove references from your cache, but do not delete objects immediately, since other threads may still hold pointers to the object. Then later at some "safe" time you delete the object. Of course, the trick is discover when such a safe time exists. Basic strategies involve each thread signaling when they "enter" and "leave" a danger zone during which they may access the cache and hold references to contained objects. Once all threads which were in the danger zone when an object was removed from the cache have left the danger zone, you can free the object while being sure that no more references are held. How practical this is depends on whether you have logical "enter" and "leave" points in your application (many request-oriented applications will), and whether the "enter" and "leave" costs can be amortized across many cache accesses. The upside is no reference counting! Of course, you still need a thread-safe container. You can find references to many academic papers on the topic and some practical performance considerations by examining the papers linked here.
2,135,441
2,135,511
How to create something like firefox's bookmark sidebard in Visual Studio 2008 C++ project?
I have visual studio 2008, and want to build an GUI application that on the left side has a frame that can be minimized like the firefox bookmark sidebar. So my questions are: 1) What type of project do I need? 2) What controls actually make up the sidebar. 3) What do I make the main frame so that I can resize it when the sidebar is open. A example would also be cool. Thanks in advance. CP
It looks like a TaskPane (CTaskPane ) attached to a simple SDI frame window (taking into account firefox is doing a lot of things custom with their own toolkit (I think, and I've been known to be wrong) Download the MFC VS2008 feature pack (with the new UI controls) and the feature pack samples and have a look at some of the sample projects (for example "TaskPane" and "VisualStudioDemo"
2,135,788
2,137,500
What do C and Assembler actually compile to?
So I found out that C(++) programs actually don't compile to plain "binary" (I may have gotten some things wrong here, in that case I'm sorry :D) but to a range of things (symbol table, os-related stuff,...) but... Does assembler "compile" to pure binary? That means no extra stuff besides resources like predefined strings, etc. If C compiles to something else than plain binary, how can that small assembler bootloader just copy the instructions from the HDD to memory and execute them? I mean if the OS kernel, which is probably written in C, compiles to something different than plain binary - how does the bootloader handle it? edit: I know that assembler doesn't "compile" because it only has your machine's instruction set - I didn't find a good word for what assembler "assembles" to. If you have one, leave it here as comment and I'll change it.
C typically compiles to assembler, just because that makes life easy for the poor compiler writer. Assembly code always assembles (not "compiles") to relocatable object code. You can think of this as binary machine code and binary data, but with lots of decoration and metadata. The key parts are: Code and data appear in named "sections". Relocatable object files may include definitions of labels, which refer to locations within the sections. Relocatable object files may include "holes" that are to be filled with the values of labels defined elsewhere. The official name for such a hole is a relocation entry. For example, if you compile and assemble (but don't link) this program int main () { printf("Hello, world\n"); } you are likely to wind up with a relocatable object file with A text section containing the machine code for main A label definition for main which points to the beginning of the text section A rodata (read-only data) section containing the bytes of the string literal "Hello, world\n" A relocation entry that depends on printf and that points to a "hole" in a call instruction in the middle of a text section. If you are on a Unix system a relocatable object file is generally called a .o file, as in hello.o, and you can explore the label definitions and uses with a simple tool called nm, and you can get more detailed information from a somewhat more complicated tool called objdump. I teach a class that covers these topics, and I have students write an assembler and linker, which takes a couple of weeks, but when they've done that most of them have a pretty good handle on relocatable object code. It's not such an easy thing.