question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,837,434
1,837,595
mySql Connector exception (C++ library for mysql) when inserting row into non-empty table
I have not done much database programming at all. I am working from some example code for using MySQL Connector/C++. When I run the following code I get a crash on the last line in some std::string code - but it ONLY crashes when the table is not empty. If the table is empty, it inserts the row and works fine. If the table is non empty it crashes. I am pretty confused. Is there something I am doing wrong with the primary key or the other values? (the column names have been changed here, but otherwise the code is verbatim) When I look at the variable in the std::string template code (what little I can see) I don't see any familiar values of data that I was attempting to insert - so that was no help at all. I see something like "HY000" as a string value, but I am not certain where that is coming from. Initially i thought it might be the date string, but the code works fine with an empty table and then crashes when non-empty. That indicates the date string works fine. prep_stmt = con->prepareStatement("INSERT INTO sometable(val1, val2, val3, Date, val5, val6, val7) VALUES (?, ?, ?, ?, ?, ?, ?)"); /* `idLicenses` INT NOT NULL , `val1` VARCHAR(45) NOT NULL , `val2` INT NOT NULL , `val3` INT ZEROFILL NULL , `Date` DATETIME NOT NULL , `val5` VARCHAR(45) NOT NULL , `val6` VARCHAR(45) NOT NULL , `val7` VARCHAR(45) NOT NULL , */ // val1, val5, val6 and val7 are std::strings, val2 and val3 are ints. prep_stmt->setString(1, val1); prep_stmt->setInt(2, val2); prep_stmt->setInt(3, 0); prep_stmt->setDateTime(4, /* I created some date string here*/); prep_stmt->setString(5, val5); prep_stmt->setString(6, val6); prep_stmt->setString(7, val7); prep_stmt->execute(); This is on a MS platform using Visual Studio 2008. The database is up and running and I can use other database query tools to see the tables, etc. EDIT: I see looking at the mysql exception that I get: "Using unsupported buffer type: 4191960 (parameter: 3)" errno 2036 EDIT: I am not sure if the accepted answer was exactly the right answer, but it helped me get to a solution. Basically I removed all non-null attributes, took out zero fill and set the primary key to auto-increment. Now it works fine
I suspect it's either your zero-filled INT or the DATETIME column (not sure which is column 3). Try creating your table with something like: `val3` INT(10) ZEROFILL , where 10 is the number of positions to zero-fill. I'm also not sure the NULL is necessary, so I excluded it above. Also, can you post the date string you created if the above doesn't work?
1,837,559
1,837,598
passing Temporary variables to reference arg in Constructor works. but not for functions in general. Why?
Consider the following code. Here, A a(B()) compiles even though the constructor is A(B& b); But print(B()) does not work. But print is also declared as print(B& b); Why this inconsistency? #include <iostream> using namespace std; class B{ public: char b; }; class A { public: B b; A(B& b); A() { } }; A::A(B& b) { this->b = b; } void print(B& b) { } int main(){ print(B()); A a(B()); }
It compiles because it's not creating an instance of A. It's declaring a function named a that returns an A and receives one unnamed parameter of type pointer-to-function-returning-B. Since it's just a declaration, it compiles. If you're referred to a elsewhere in the code, you'd have seen additional problems. For why that's a function declaration instead of an object definition, the term to look up is most vexing parse.
1,837,656
1,837,986
Jump Table Switch Case question
I am trying to understand some things about jump tables and its relationship between a switch case statement. I was told that a jump table is a O(1) structure that the compiler generates which makes lookup of values essentially about as fast as you can get. However in some cases a Hashtable/Dictionary might be faster. I was also told this will only work if the switch case contains ordered data values. Can someone please confirm or deny this and explain what a jump table is, it's importance and the time complexity versus using a dictionary or hashtable. Thanks.
A jump table is an abstract structure used to transfer control to another location. Goto, continue, and break are similar, except they always transfer to a specific location instead of one possibility from many. In particular, this control flow is not the same as a function call. (Wikipedia's article on branch tables is related.) A switch statement is how to write jump tables in C/C++. Only a limited form is provided (can only switch on integral types) to make implementations easier and faster in this common case. (How to implement jump tables efficiently has been studied much more for integral types than for the general case.) A classic example is Duff's Device. However, the full capability of a jump table is often not required, such as when every case would have a break statement. These "limited jump tables" are a different pattern, which is only taking advantage of a jump table's well-studied efficiency, and are common when each "action" is independent of the others. Actual implementations of jump tables take different forms, mostly differing in how the key to index mapping is done. That mapping is where terms like "dictionary" and "hash table" come in, and those techniques can be used independently of a jump table. Saying that some code "uses a jump table" doesn't imply by itself that you have O(1) lookup. The compiler is free to choose the lookup method for each switch statement, and there is no guarantee you'll get one particular implementation; however, compiler options such as optimize-for-speed and optimize-for-size should be taken into account. You should look into studying data structures to get a handle on the different complexity requirements imposed by them. Briefly, if by "dictionary" you mean a balanced binary tree, then it is O(log n); and a hash table depends on its hash function and collision strategy. In the particular case of switch statements, since the compiler has full information, it can generate a perfect hash function which means O(1) lookup. However, don't get lost by just looking at overall algorithmic complexity: it hides important factors.
1,837,815
1,838,657
Is it possible to use separate threads for reading and writing with Boost.Asio?
According to the Boost Documentation, having multiple threads call io_service::run() sets up a pool of threads that the IO service can use for performing asynchronous tasks. It explicitly states that all threads that have joined the pool are considered equivalent. Does this imply that it is not possible to have a separate thread for reading from a socket and a separate one for writing? If it is possible, how would I implement this?
Any thread that calls io_service::run() can be used to invoke asynchronous handlers. But you can't specifically specify which thread executes which type of operation. For example, if you call io_service::run() in 2 background threads, and you were to call socket::async_send and socket::async_receive in a main thread, your handlers will be executed in any background thread that is currently available. So yes, all threads are basically considered equivalent, and may be used for any asynchronous operation.
1,837,867
1,855,842
problem parsing a xml file with MSXML4 in C++
Here is my parsing code: MSXML2::IXMLDOMNodePtr pNode = m_pXmlDoc->selectSingleNode(kNameOfChild.c_str()); MSXML2::IXMLDOMNodeListPtr pIDOMNodeList = NULL; MSXML2::IXMLDOMNodePtr pIDOMNode = NULL; long numOfChildNodes= 0; BSTR bstrItemText; HRESULT hr; MSXML2::IXMLDOMElementPtr pChildNode = m_pXmlDoc->getElementsByTagName(kNameOfChild.c_str()); hr = m_pXmlDoc->get_childNodes(&pIDOMNodeList); hr = pIDOMNodeList->get_length(&numOfChildNodes); And my xml file: <?xml version="1.0"?> <GovTalkMessage> <EnvelopeVersion>1.0</EnvelopeVersion> <Header> <MessageDetails> <Class>MOSWTSC2</Class> <Qualifier>acknowledgement</Qualifier> <Function>submit</Function> <TransactionID>20021202ABC</TransactionID> <CorrelationID>B07B9ED3176193DDC4EC39063848A927</CorrelationID> <ResponseEndPoint PollInterval="10"> https://secure.gateway.gov.uk/poll </ResponseEndPoint> <GatewayTimestamp>2001-01-31T10:20:18.345</GatewayTimestamp> </MessageDetails> <SenderDetails/> </Header> <GovTalkDetails> <Keys/> </GovTalkDetails> <Body/> </GovTalkMessage> kNameOfchild is "Qualifier" pNode is always NULL pChildNode is always NULL hr returns S_OK numOfChildNodes is always 0 So, what am I doing wrong? Thanks
Try /GovTalkMessage/Header/MessageDetails/Qualifier for the XPath query.
1,837,979
1,838,088
Handling touch detection in iPhone with C++?
I'm working on a game for the iPhone, for several reasons most of the code is in C++. I need to write a TouchesManager for my Game, I know about the methods touchesBegan: touchesEnded: and touchesMoved: I would really like to make a manager in C++ so I can subscribe some classes to this manager, so they can handle touch events in my Game. I have been thinking on making a C++ interface to handle the "touchesBegan: ended: and moved:" that I could implement in the classes I'm interested to respond to touches... I would really like to know a good simple way this could be achieved, I really need to keep C++ for many reasons ( I love Obj-C / Cocoa-touch, don't get me wrong here please ) Thank you all!
At a higher level, I would create a C++ base class with the exact arguments/names (maybe even self and _cmd). Someplace, you would need to create these, and establish connections from the manager to the objects queried. The objc objects could either hold a pointer to their C++ implementation/receiver, or you could use an index, or you could use self and a hash/map approach. So the manager could hold onto a collection of event receivers, and then the UIView would implement the method, which would forward the message to the manager to parse the command (what do you do with the commands/events??). Alternatively, if all you want is implementation, then just use ObjectiveC++ and add the event receiver/processor as an ivar to the UIResponder. Addition: Added a quick pseudo-code illustration for 'then just use ObjectiveC++ and add the event receiver/processor as an ivar to the UIResponder'. // Mr.Gando: // To answer your question about what do I need to do with events, // for example I need to subscribe a button to the manager, so when // it get's touched, a method "Fire" is called... just an example, // but I think your answer is good. Does this Manager have to be // thread safe ? ///////////////////////////////////////////////////////////////////// /* not declared in event_manager_t's scope, so that objc only files may declare members without error - if all your code is objc++, then relocate */ class mon_event_manager_event_handler_t { /* ... */ void touchesBegan(id sender, NSSet * touches, UIEvent * event) { assert(sender && touches && event); assert(this->getResponder() && this->getResponder() == sender); if (this->getResponder() && this->getResponder() == sender && this->isSubscribed() && this->isInterestedInTouchesBeganEvents()) { SharedEventManager().touchesBegan(this, sender, touches, event); } } private: UIResponder * responder_; UInt32 flags_EventsOrActionsOfInterest_; bool isSubscribed_; }; /** implement as singleton */ class event_manager_t { /* ... */ void touchesBegan(handler_t* const handler, id sender, NSSet * touches, UIEvent * event) { this->fire(); } void fire() { NSLog(@"Fire()"); /* you can message anything here, just realize that events may not occur on the recipient's work thread */ } static mon_event_manager_event_handler_t* CreateNextHandler(UIResponder * responder) { /* SharedEventManager() must guard its data here */ mon_event_manager_event_handler_t* result(SharedEventManager().createOrReuseHandler()); result->setResponder(responder); SharedEventManager().registerNewHandler(handler); return result; } static void RemoveHandler(mon_event_manager_event_handler_t* handler) { /* SharedEventManager() must guard its data here */ SharedEventManager().removeHandler(handler); } }; /** @return the event_manager_t singleton object */ event_manager_t& SharedEventManager(); ///////////////////////////////////////////////////////////////////// struct mon_event_manager_event_handler_t; @interface MonResponder { mon_event_manager_event_handler_t* handler_; } @end ///////////////////////////////////////////////////////////////////// @implementation MonResponder /* ... */ - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { assert(handler_ && "TODO: create the handler"); handler_->touchesBegan(self, touches, event); /* ... */ } @end /////////////////////////////////////////////////////////////////////
1,838,271
1,838,310
Types in a public c++ API
I'm writing a library and wonder what's the best practice for datatypes used in a public API. Given the function void foo (int bar) which expects an index to some internal array/container. What type should that be? Because an index can never be negative I could use unsigned int or size_t. Or should I stick with a plain int and assert / throw if some invalid value is provided? In general: Should I choose a type based on the valid data range (e.g. to avoid negative checks) or not? EDIT: another example, suppose my library provides a function for printing a file. The user can choose the range of pages to be printed: void print (int page_from, int page_to)
If the array/container you are talking about is just a generic abstract application-independent array, then the most appropriate type would be size_t. You can, of course, provide a typedef name for the type in your interface. Again, this is only appropriate when you are working with abstract arrays, like in a generic container library, or a generic sort function etc. One you get into an application specific area, size_t is no longer the appropriate type. In your application specific area that index would normally have some application-specific semantics not immediately related to arrays. For example, it can be an "employee id" of some sort, or "cell number" or "color index" or something else. In such cases you would normally already have a pre-chosen integer type to represent the corresponding quantity. (And the choice will not normally have anything to do with arrays.) This is exactly the type you should use in your interface. As for signedness/unsignedness of the type... I for one firmly believe that unsigned quantities should be represented by unsigned types, i.e. a normal array index should be unsigned.
1,838,308
1,838,330
What's C++ Really Doing When I Accidently Use a Variables to Declare Array Length?
I was helping a friend with some C++ homework. I warned said friend that the kind of programming I do (PHP, Perl, Python) is pretty different from C++, and there were no guarantees I wouldn't tell horrible lies. I was able to answer his questions, but not without stumbling over my own dynamic background. While I was reacquainting myself with C++ array semantics, I did something stupid like this (simplified example to make my question clearer) #include <iostream> #include <cstring> using namespace std; int main() { char easy_as_one_two_three[] = {'A','B','C'}; int an_int = 1; //I want an array that has a length of the value //that's currently in an_int (1) //This clearly (to a c++ programmer) doesn't do that. //but what is it doing? char breaking_things[an_int]; cout << easy_as_one_two_three << endl; return 1; } When I compile and run this program, it produces the following output ABC???? However, if I comment out my bogus array declaration #include <iostream> #include <cstring> using namespace std; int main() { char easy_as_one_two_three[] = {'A','B','C'}; int an_int = 1; //I want an array that has a length of the value //that's currently in an_int (1) //This clearly (to a c programmer) doesn't do that. //but what is it doing? //char breaking_things[an_int]; cout << easy_as_one_two_three << endl; return 1; } I get the output I expect: ABC So, what exactly is happening here? I understand (vaguely) that when you create an array, you're pointing to a specific memory address, and when you give an array a length, you're telling the computer "reserve the next X blocks for me". What I don't understand is, when I use a variable in an array declaration, what am I telling the computer to do, and why does it have an effect on a completely separate array? Compiler is g++, version string is science:c++ alanstorm$ g++ -v Using built-in specs. Target: i686-apple-darwin9 Configured with: /var/tmp/gcc/gcc-5493~1/src/configure --disable-checking -enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.0/ --with-gxx-include-dir=/include/c++/4.0.0 --with-slibdir=/usr/lib --build=i686-apple-darwin9 --with-arch=apple --with-tune=generic --host=i686-apple-darwin9 --target=i686-apple-darwin9 Thread model: posix gcc version 4.0.1 (Apple Inc. build 5493)
Update: Neil pointed out in his comment to the question that you will get error if you compile this with -Wall and -pedantic flags in g++. error: ISO C++ forbids variable-size array You are getting ABC???? because it prints the contents of the array (ABC) and continues to print until it encounters a \0. Had the array been {'A','B','C', '\0'};, the output will be just ABC as expected. Variable-length arrays were introduced in C99 - this doesn't seem to apply to C++ though. It is undefined behavior. Even if you comment out the bogus declaration, the printed output is not always what you expect (ABC). Try giving ASCII values of some printable character (something between 32 and 126) to an_int instead of 1 and you will see the difference. an_int output ------------------------ 40 ABC( 65 ABCA 66 ABCB 67 ABCC 296 ABC( 552 ABC( 1064 ABC( 1024*1024 + 40 ABC( See the pattern here? Apparently it interprets the last byte (LSB) of the an_int as a char, prints it, somehow finds a null char afterwards and stops printing. I think the "somehow" has to do something with the MSB portion of an_int being filled with zeros, but I'm not sure (and couldn't get any results to support this argument either). UPDATE: It is about the MSB being filled zeros. I got the following results. ABC( for 40 - (3 zero bytes and a 40), ABC(( for 10280 (which is (40 << 8) + 40) - (2 zero bytes and two 40s), ABC((( for 2631720 (which is (10280 << 8) + 40) - (1 zero byte and three 40s), ABC((((°¿® for 673720360 (which is (2631720 << 8) + 40) - no zero bytes and hence prints random chars until a zero byte is found. ABCDCBA0á´¿á´¿® for (((((65 << 8) + 66) << 8) + 67) << 8) + 68; These results were obtained on a little endian processor with 8-bit atomic element size and 1-byte address increment, where 32 bit integer 40 (0x28 in hex) is represented as 0x28-0x00-0x00-0x00 (LSB at the lowest address). Results might vary from compiler to compiler and platform to platform. Now if you try uncommenting the bogus declaration, you will find that all the outputs are of the form ABC-randomchars-char_corresponding_to_an_int. This again is the result of undefined behavior.
1,838,368
1,838,732
Calculating the Amount of Combinations
Cheers, I know you can get the amount of combinations with the following formula (without repetition and order is not important): // Choose r from n n! / r!(n - r)! However, I don't know how to implement this in C++, since for instance with n = 52 n! = 8,0658175170943878571660636856404e+67 the number gets way too big even for unsigned __int64 (or unsigned long long). Is there some workaround to implement the formula without any third-party "bigint" -libraries?
Here's an ancient algorithm which is exact and doesn't overflow unless the result is to big for a long long unsigned long long choose(unsigned long long n, unsigned long long k) { if (k > n) { return 0; } unsigned long long r = 1; for (unsigned long long d = 1; d <= k; ++d) { r *= n--; r /= d; } return r; } This algorithm is also in Knuth's "The Art of Computer Programming, 3rd Edition, Volume 2: Seminumerical Algorithms" I think. UPDATE: There's a small possibility that the algorithm will overflow on the line: r *= n--; for very large n. A naive upper bound is sqrt(std::numeric_limits<long long>::max()) which means an n less than rougly 4,000,000,000.
1,838,730
1,838,792
Template with static functions vs object with non-static functions in overloaded operator
Which approach is the better one and why? template<typename T> struct assistant { T sum(const T& x, const T& y) const { ... } }; template<typename T> T operator+ (const T& x, const T& y) { assistant<T> t; return t.sum(x, y); } Or template<typename T> struct assistant { static T sum(const T& x, const T& y) { ... } }; template<typename T> T operator+ (const T& x, const T& y) { return assistant<T>::sum(x, y); } To explain the things a bit more: assistant has no state it only provides several utility functions and later I can define template specialization of it to achieve a different behavior for certain types T. I think for higher optimization levels these two approaches don't lead to different byte codes because anyway the assistant will optimized "away"... Thanks!
It is usually not a question of run-time performance, but one of readability. The former version communicates to a potential maintainer that some form of object initialization is performed. The latter makes the intent much clearer and should be (in my opinion) preferred. By the way, what you've created is basically a traits class. Take a look at how traits are done in the standard library (they use static member functions).
1,838,992
1,839,200
Converting existing C++ web service to a load balanced server?
We have a C++ (SOAP-based) web service deployed Using Systinet C++ Server, that has a single port for all the incoming connections from Java front-end. However recently in production environment when it was tested with around 150 connections, the service went down and hence I wonder how to achieve load-balancing in a C++ SOAP-based web service?
The service is accessed as SOAP/HTTP? Then you create several instances of you services and put some kind of router between your clients and the web service to distribute the requests across the instances. Often people use dedicated hardware routers for that purpose. Note that this is often not truly load "balancing", in that the router can be pretty dumb, for example just using a simple round-robin alrgorithm. Such simple appraoches can be pretty effective. I hope that your services are stateless, that simplifies things. If indiviual clients must maintain affinity to a particualr instance thing get a little tricker.
1,839,093
1,839,696
msgStore was not declared in this scope (XCode)
I'm implementing callback routines for external static C++ library to be used in Objective-C project. Now I have trouble moving data between callback and normal routines. As you can see below my "msgStore" is defined as part of MyMessage class and can be used within class routines such as init(). However attempting same from callback routine, which is NOT part of the MyMessage class, fails. @interface MyMessage : NSObject { NSMutableArray *msgStore; } @property (nonatomic, retain) IBOutlet NSMutableArray *msgStore; // Callback functions declarations void aCBack (const std::string text); @implementation MyMessage @synthesize msgStore; - (id)init { if ((self = [super init])) { } if (msgStore == nil) { msgStore = [NSMutableArray arrayWithCapacity:100]; } return self; } void aCBack (const std::string text) { NSString *msg = [[NSString alloc] initWithCString:(const char *)text.c_str() encoding:NSUTF8StringEncoding]; [msgStore insertObject:msg atIndex:0]; } The last code line gives error message 'msgStore' was not declared in this scope. I'm guessing it's because aCBack is a plain C function and thus does not have automatic "self" pointer? Any ideas how to save data received in callback for use inside Obj-C class?
You cannot call msgStore from the function because it is not in the scope of the function. There are a few ways to get to it in the function. One is to use a singleton class. If you plan on only using one message store, then you can make that class a singleton. That means you can get the object instance of that class by calling a class method, which you can do from any scope. See also: What should my Objective-C singleton look like? MyMessage * myMsg = [MyMessage sharedMessage]; // this will get you a pointer to the shared instance Another way is, if the callback function allows, you can also pass it as a void * data argument, then cast it to a MyMessage in the function. See also Alex Deem's answer. PS. You create the array with [NSArray arrayWithCapacity:], which you might want to make [[NSArray arrayWithCapacity:] retain] or just [[NSArray alloc] initWithCapacity:], so the object won't vannish on the next autoreleasepool housekeeping round.
1,839,128
1,839,258
Why is my glutWireCube not placed in origin?
I have the following OpenGL code in the display function: glLoadIdentity(); gluLookAt(eyex, eyey, eyez, atx, aty, atz, upx, upy, upz); // called as: gluLookAt(20, 5, 5, -20, 5, 5, 0, 1, 0); axis(); glutWireCube (1.); glFlush (); axis() draws lines from (0,0,0) to (10,0,0), (0,10,0) and (0,10,0), plus a line from (1,0,0) to (1,3,0). My reshape function contains the following: glViewport (0, 0, (GLsizei) w, (GLsizei) h); glMatrixMode (GL_PROJECTION); glLoadIdentity (); gluPerspective(45.0, (GLsizei) w / (GLsizei) h, 1.0, 100.0); glMatrixMode (GL_MODELVIEW); This image shows the result of running the program with 1. as the argument to glutWireCube: As you can see, the cube isn't centered around (0,0,0) as the documentation says it should be: The cube is centered at the modeling coordinates origin (...) (source) If I run the program with 5. as the argument, the cube is displaced even further: Why is that, and how do I place the cubes around (0,0,0)? FURTHER INFORMATION It doesn't matter if I switch the order of axis() and glutWireCube. Surrounding axis() with glPushMatrix() and glPopMatrix() doesn't fix it either. SOLUTION I modified gluPerspective to start looking further away from the camera, and now the Z-buffering works properly, so it is clear that the cubes are placed around the origin.
Are you sure axis does not mess with the view matrix ? What happens if you call it after the drawing of the cube ? Edit to add: Actually... Looking at the picture closer, it looks like it might be centered at the origin. The center of the cube seems to align exactly with the intersection of the 3 axes. The only thing that looks suspicious is that the red line does not write over the white edge. do you have Z-buffering properly set up ?
1,839,221
1,851,914
Audio Device, change Speaker setup
I want to change from my program the speaker setup, which is under speaker settings / advanced... section. I tried to find maybe there is some sort of registry entry but no luck till now :| Any Ideas ? Thanks a lot !
Ok, here is the code for what I wanted var ds:IDirectSound; begin if DirectSoundCreate(nil, ds, nil) <> DS_OK then raise Exception.Create('Failed to create IDirectSound object'); ds.SetSpeakerConfig(1);
1,839,224
1,839,237
Why does compiler generate error?
Why does compiler generate error? template<class T> void ignore (const T &) {} void f() { ignore(std::endl); } Compiler VS2008 gives the following error: cannot deduce template argument as function argument is ambiguous.
I think that problem is that std::endl is a template function and compiler cannot deduce template argument for ignore function. template <class charT, class traits> basic_ostream<charT,traits>& endl ( basic_ostream<charT,traits>& os ); To fix a problem you could write something like as follows: void f() { ignore(std::endl<char, std::char_traits<char>>); } But you should know that you will pass pointer to function as argument, not result of function execution.
1,839,225
1,839,283
Float addition promoted to double?
I had a small WTF moment this morning. Ths WTF can be summarized with this: float x = 0.2f; float y = 0.1f; float z = x + y; assert(z == x + y); //This assert is triggered! (Atleast with visual studio 2008) The reason seems to be that the expression x + y is promoted to double and compared with the truncated version in z. (If i change z to double the assert isn't triggered). I can see that for precision reasons it would make sense to perform all floating point arithmetics in double precision before converting the result to single precision. I found the following paragraph in the standard (which I guess I sort of already knew, but not in this context): 4.6.1. "An rvalue of type float can be converted to an rvalue of type double. The value is unchanged" My question is, is x + y guaranteed to be promoted to double or is at the compiler's discretion? UPDATE: Since many people has claimed that one shouldn't use == for floating point, I just wanted to state that in the specific case I'm working with, an exact comparison is justified. Floating point comparision is tricky, here's an interesting link on the subject which I think hasn't been mentioned.
You can't generally assume that == will work as expected for floating point types. Compare rounded values or use constructs like abs(a-b) < tolerance instead. Promotion is entirely at the compiler's discretion (and will depend on target hardware, optimisation level, etc). What's going on in this particular case is almost certainly that values are stored in FPU registers at a higher precision than in memory - in general, modern FPU hardware works with double or higher precision internally whatever precision the programmer asked for, with the compiler generating code to make the appropriate conversions when values are stored to memory; in an unoptimised build, the result of x+y is still in a register at the point the comparison is made but z will have been stored out to memory and fetched back, and thus truncated to float precision.
1,839,422
1,839,437
strange output in comparison of float with float literal
float f = 0.7; if( f == 0.7 ) printf("equal"); else printf("not equal"); Why is the output not equal ? Why does this happen?
This happens because in your statement if(f == 0.7) the 0.7 is treated as a double. Try 0.7f to ensure the value is treated as a float: if(f == 0.7f) But as Michael suggested in the comments below you should never test for exact equality of floating-point values.
1,839,821
1,840,366
Unique id of files and monitoring file system changes
Do files or folders on S60 have some unique id value that can identify them? I would like to have an id that can be later used to extract full path of a file or folder. Is this achievable? If not, what would be the best way to keep track of files of interest? E.g. if I have a pdf reader, and I want to have a menu option to show all pdf files on the system - how do I prevent my application to search all over the whole system every time I chose this option? Can I search it once and easily monitor changes while my application is active? Thank you.
I can't quite see anything in the Symbian OS C++ API that would do exactly what you want. Using RFs::NotifyChange() is probably your best bet.
1,839,844
1,840,477
is pwrite after dup race safe?
On Linux pwrite operation (which is seek+write) is atomic, meaning doing pwrite-s in multiple threads with one file descriptor is safe. I want to create file descriptor duplicate, using dup(). Now, having fd1 and fd2 - will pwrite-s work as expected, or there's danger of race condition?
I think pwrite is an atomic operation if the number of bytes you're writing is less than PIPE_BUF of the pipe you're writing to (from the POSIX programmer's manual).
1,840,012
1,840,048
Do non const internal members of class become const when I have const ref to an object of that class?
Well, I think my problem originates in a lake of knowledge of basic C++ concepts. The problem is, in my code (below) I have the classes Header and Register. For both, I pass a reference to a ifstrem file already opened. The Header reads some bytes from it. Register has a method to return a reference of Header (which is passed in Register constructor). The problem is, when I declare the reference to Header as const (in my Register class), I've got an error message saying: error C2662: 'Header::Field_1' : cannot convert 'this' pointer from 'const Header' to 'Header &' The problem, I guess, is: Field_1 method changes the file cursor through seekg. therefore this member object cannot be const (its internal structure is being changed). Being fstream _stream declared inside Header class, and having a const reference for this class does it make all its internal members const as well? PS: I'm using VS C++ express. The code below doesn't do anything useful, is just an example. // ********** HEADER.H *********** #ifndef __HEADER_H__ #define __HEADER_H__ #include <fstream> class Header { private: std::ifstream* _stream; unsigned long field1; public: Header(std::ifstream* stream); ~Header() { } unsigned long Field_1(void); }; class Register { private: const Header& _header; std::ifstream* _stream; public: Register(const Header& header, std::ifstream* stream); ~Register(){ } const Header& GetHeader(void) { return _header; } }; #endif /*__HEADER_H__*/ //********* PROGRAM.CPP ************* #include <iostream> #include "header.h" using namespace std; Header::Header(ifstream* stream) : _stream(stream) { } unsigned long Header::Field_1(void) { _stream->seekg(0x00, fstream::beg); _stream->read(reinterpret_cast<char*>(&field1), sizeof(field1)); return field1; } Register::Register(const Header& header, std::ifstream* stream): _header(header), _stream(stream) { } int main(void) { ifstream file("test.dat", ios::binary | ios::in); Header h(&file); Register reg(h, &file); cout << "Field 1 " << reg.GetHeader().Field_1() << endl; file.close(); return 0; }
Yes, when GetHeader() returns a const reference to the Header object, you can only call const methods on it. In this case if you declare Field_1as a const method by writing: unsigned long Header::Field_1(void) const (note the const on the end) The trouble is if you do this then within the const method all other members appear as if they are const too (unless you mark them as mutable). As a result you will probably have trouble with the reinterpret_cast<char*>(&field1). In which case the simplest solution is probably to have GetHeader() return a non-const reference. Alternatively you could mark field1 as mutable (but make sure you understand the semantics and dangers of mutable first if you go down that route. My feeling is that making GetHeader() return a non const reference is what you really want here)
1,840,029
1,841,344
passing functor as function pointer
I'm trying to use a C library in a C++ app and have found my self in the following situation (I know my C, but I'm fairly new to C++). On the C side I have a collection of functions that takes a function pointer as their argument. On the C++ side I have objects with a functor which has the same signature as the function pointer needed by the C function. Is there any way to use the C++ functor as a function pointer to pass to the C function?
You cannot directly pass a pointer to a C++ functor object as a function pointer to C code (or even to C++ code). Additionally, to portably pass a callback to C code it needs to be at least declared as an extern "C" non-member function. At least, because some APIs require specific function call conventions and thus additional declaration modifiers. In many environments C and C++ have the same calling conventions and differ only in name mangling, so any global function or static member will work. But you still need to wrap the call to operator() in a normal function. If your functor has no state (it is an object just to satisfy some formal requirements etc): class MyFunctor { // no state public: MyFunctor(); int operator()(SomeType &param) const; } you can write a normal extern "C" function which creates the functor and executes its operator(). extern "C" int MyFunctorInC(SomeType *param) { static MyFunctor my_functor; return my_functor(*param); } If your functor has state, eg: class MyFunctor { // Some fields here; public: MyFunctor(/* some parameters to set state */); int operator()(SomeType &param) const; // + some methods to retrieve result. } and the C callback function takes some kind of user state parameter (usually void *): void MyAlgorithmInC(SomeType *arr, int (*fun)(SomeType *, void *), void *user_state); you can write a normal extern "C" function which casts its state parameter to your functor object: extern "C" int MyFunctorInC(SomeType *param, void *user_state) { MyFunctor *my_functor = (MyFunctor *)user_state; return (*my_functor)(*param); } and use it like this: MyFunctor my_functor(/* setup parameters */); MyAlgorithmInC(input_data, MyFunctorInC, &my_functor); Otherwise the only normal way to do it (normal as in "without generating machine code at runtime" etc.) is to use some static (global) or thread local storage to pass the functor to an extern "C" function. This limits what you can do with your code and is ugly but will work.
1,840,121
1,840,131
Which type of sorting is used in the std::sort()?
Can anyone please tell me that which type of sorting technique (bubble, insertion, selection, quick, merge, count...) is implemented in the std::sort() function defined in the <algorithm> header file?
Most implementations of std::sort use quicksort, (or usually a hybrid algorithm like introsort, which combines quicksort, heapsort and insertion sort). The only thing the standard requires is that std::sort somehow sort the data according to the specified ordering with a complexity of approximately O(N log(N)); it is not guaranteed to be stable. Technically, introsort better meets the complexity requirement than quicksort, because quicksort has quadratic worst-case time.
1,840,241
1,840,278
What's the difference between Boost.MPI and Boost.Interprocess?
I suppose Boost.MPI and Boost.Interprocess are different, right? From a performance perspective, which is faster? Has anyone ever done benchmarking? Can I use them to pass data within the same process (i.e. among different threads)? Thanks!
They are totally different. Boost MPI is for parallel/distributed computing (like massively-parallel super-computers). It requires an existing installation of MPI (Message Passing Interface), such as OpenMPI. MPI is usually used with high-performance clusters of networked computers, or with super computers. The Boost MPI library is basically just a nice wrapper around the normal MPI function calls. Boost.Interprocess, on the other hand, is an API for IPC (Interprocess Communications), i.e. communicating between two processes on a single computer. If you want to share data between processes on the same computer, Boost.Interprocess is useful. But if, as you suggest, you just want to share data between threads, you don't need any of this. You just need a threading API.
1,840,253
1,840,318
template member function of template class called from template function
This doesn't compile: template<class X> struct A { template<int I> void f() {} }; template<class T> void g() { A<T> a; a.f<3>(); // Compilation fails here (Line 18) } int main(int argc, char *argv[]) { g<int>(); // Line 23 } The compiler (gcc) says: hhh.cpp: In function 'void g()': hhh.cpp:18: error: expected primary-expression before ')' token hhh.cpp: In function 'void g() [with T = int]': hhh.cpp:23: instantiated from here hhh.cpp:18: error: invalid use of member (did you forget the '&' ?) Can anyone explain why this is? Is there a way to get it to work?
Try the following code: template<class T> void g() { A<T> a; a.template f<3>(); // add `template` keyword here } According to C++'03 Standard 14.2/4: When the name of a member template specialization appears after . or -> in a postfix-expression, or after nested-name-specifier in a qualified-id, and the postfix-expression or qualified-id explicitly depends on a template-parameter (14.6.2), the member template name must be prefixed by the keyword template. Otherwise the name is assumed to name a non-template. Future C++ Standard seems to be still require this keyword according to draft n2857 14.3/4. Some compilers has special mode that allows to compile original code without errors (Comeau compiles it in so called relaxed mode).
1,840,343
1,840,491
C++ SmartPointers leak on self assign?
i have small problem understanding why my smart pointer class is leaking on self assing. If i do something like this SmartPtr sp1(new CSine());//CSine is a class that implements IFunction iterface sp1=sp1; my colleagues told me that my smart pointer leaks. I added some log messages in my smart pointer to track what is going on and a test and reported this: SmartPtr sp1(new CSine()); ->CSine constructor ->RefCounter increment 0->1 ->RefCounter constructor ->SmartPtr constructor sp1=sp1; ->checks if this.RefCounter == to parameter.RefCounter, if true returns the smart pointer unmodified else modifies the object and returns it with the new values; in this case it returns true and returns the object unchanged. at the end ->SmartPtr destructor ->RefCounter decrement 1->0 ->RefCounter destructor ->CSine destructor i can't understand why they consider that my smart pointer leaks...any ideas? Thank you in advance! class SmartPtr { private: RefCounter* refCnt; void Clear() { if(!isNull() && refCnt->Decr() == 0) delete refCnt; refCnt = 0; }; public: explicit SmartPtr(); explicit SmartPtr(IFunction *pt):refCnt(new RefCounter(pt)){}; SmartPtr(SmartPtr& other) { refCnt = other.refCnt; if (!isNull()) refCnt->Incr(); }; virtual ~SmartPtr(void){Clear();}; SmartPtr& operator=(SmartPtr& other) { if(other.refCnt != refCnt) { if(!rVar.isNull()) other.refCnt->Incr(); Clear(); refCnt = other.refCnt; } return *this; }; SmartPtr& operator=(IFunction* _p) { if(!isNull()) { Clear(); } refCnt = new RefCounter(fct); return *this; }; IFunction* operator->(); const IFunction* operator->() const; IFunction& operator*(); const IFunction& operator*() const; bool isNull() const { return refCnt == 0; }; inline bool operator==(const int _number) const; inline bool operator!=(const int _number) const; inline bool operator==(IFunction* _other) const; inline bool operator!=(IFunction* _other) const; inline bool operator==(SmartPtr& _other) const; inline bool operator!=(SmartPtr& _other) const; }; class RefCounter { friend class SmartPtr; private: IFunction* p; unsigned c; explicit RefCounter(IFunction* _p):c(0),p(_p) { if(_p != NULL) Incr(); cout<<"RefCounter constructor."<<endl; } virtual ~RefCounter(void) { cout<<"RefCounter destructor."<<endl; if(c == 0) delete p; } unsigned Incr() { ++c; cout<<"RefCounter increment count:"<<c-1<<" to "<<c<<endl; return c; } unsigned Decr() { if(c!=0) { --c; cout<<"RefCounter decrement count:"<<c+1<<" to "<<c<<endl; return c; } else return 0; } };
My impression is that there is no memory leak. To be sure: test with valgrind or the VS-alternative use std::tr1::shared_ptr (if this is more than educational)
1,840,348
1,840,367
What is this for loop doing?
What is the for loop doing? I just can't understand it. list<pair<int, double> > nabors; list<pair<int, double> >::iterator i; for (i = nabors.begin(); i != nabors.end() && dist >= i->second; i++);
It's finding the first element in nabors that satisfies the condition dist < i->second If no element satisfies that condition, the iterator i points to nabors.end().
1,840,497
1,840,540
Reason for peculiar ordering of division and multiplication in C++
I'm in the middle of porting some c++ code to java, and I keep running across instances where whoever wrote it kept doing the following: double c = (1.0/(a+1.0)*pow(b, a+1.0)); double d = (1./(integral(gamma, dmax)-integral(gamma, dmin)))*(integral(gamma+1, dmax)-integral(gamma+1, dmin)); Instead of: double c = pow(b, a+1.0)/(a+1.0); double d = (integral(gamma+1, dmax)-integral(gamma+1, dmin))/(integral(gamma, dmax)-integral(gamma, dmin)); The second seems much clearer, and unless I'm wrong about the order of operations in C++ they should do the same thing. Is there some reason to do the first and not the second? The only thing I could think of would be some weird case with precision.
Yes, they're the same. The only reason I can think of is mathematical clarity: sometimes when you're normalizing a quantity, you often write: answer = (1/total) * (some of it) For example, Cauchy's integral theorem is often written f(a) = (1/(2*pi*i)) * integral(f(z)/(z-a), dz)
1,841,149
1,841,201
c++, get phone number from txt file
I'm trying input a phone number in the format: 555-555-5555 into a struct with three int's. I've tried using getline with a delimiter of "-", but I keep getting the error: "cannot convert parameter 1 from 'int' to 'char *'". I tried creating a temp char* variable to store the number in and then type casting it to int, but that didn't work. How should I go about doing this? Thanks edit: here's some of the code: void User::Input(istream& infile) { char* phone_temp; ... infile.getline(phone_temp, sizeof(phoneNum.areaCode), "-"); phoneNum.areaCode = (int)phone_temp; ... }
Since you are posting this as a c++ question, and not a c question, Use istringstream http://www.cplusplus.com/reference/iostream/istringstream/ From my head it your code would become something like: std::string sPhoneNum("555-555-5555"); struct { int p1; int p2; int p3; } phone; char dummy; std::istringstream iss(sPhoneNum); iss >> phone.p1; // first part iss >> dummy; // '-' character iss >> phone.p2; // second part iss >> dummy; // '-' character iss >> phone.p2; // last part EDIT: now that you have posted example code, I see you already start with an istream, you can just use the >> operator directly, no need to create another istringstream operator. See examples: http://www.cplusplus.com/reference/iostream/istream/operator%3E%3E/ Also, stay away from c-style conversion methods with char * and atoi stuff if you don't have to, working with std::string and istreams is the "right" C++ way. It avoids memory leaks and other nasty problems.
1,841,689
1,842,043
Rendering multiple different textures with 1 image? (such as fonts)
Let's say I have a texture which is one file with separate 20 px by 20 px blocks. Within each of these blocks is a new character and I'd like to render different characters on screen as textures using these blocks. How can I use directx to render separate pieces of a texture file?
You will need to render a quad (two triangles) with the UV coordinates mapped to the correct location in this texture for each letter you are rendering. So if you had a quad like this: |\ | | \| and you wanted to draw the entire texture you would assign the vertices UV coordinates of: TopLeft: 0,0 TopRight: 1,0 BottomLeft: 0,1 BottomRight: 1,1 If you wanted to assign the letter at 40,60 with a width and height of 20 and a texture width and height of 200 to this quad then the UV coordinates would be: TopLeft: 40/200,60/200 TopRight: TopLeft.x + 20/200, TopLeft.y BottomLeft: TopLeft.x, TopLeft.y + 20/200 BottomRight: TopRight.x, BottomLeft.y
1,841,721
1,868,334
Why can't a "procedure entry point could not be located in dll" when I definitely put it in?
I have a really vague problem, but I hope someone can help with it. I was modifying a C++ project and yesterday it was still working, but today it's not. I'm pretty sure I didn't change anything, but to be completely sure I checked the project out from SVN again and I even reverted to a previous system restore point (because this is a work computer, it sometimes secretly installs updates etc.). After succesfully compiling it, the program can start up, but after I interact with it, I get this error: The procedure entry point ?methodName@className@@UAEXXZ could not be located in the dynamic link library libName.dll. I've searched the internet, but most people's problems seem to be caused by an older version of the DLL being used. I searched my computer and there is no older version. If I delete the correct version, the application doesn't start. If I then recompile the project, the DLL is created again, so I'm both pretty sure that the application is using the correct DLL and that the compilation is creating it. If I introduce syntax errors into the method that the error refers to, the project refuses to compile, so I guess this means that it is also compiling the files that contain the method. Basically I don't know anything about DLL's, linking, etc. so I would greatly appreciate it if anybody has an idea as to why the functions that are very clearly defined in the project are all of a sudden not making it into the DLL anymore. I know this is vague and if any more information is required I will gladly provide it. Thanks! Update: I have tried the given suggestions, but I'm still stuck. __declspec(dllexport) is apparently not used in the entire project. Opening the DLL with Dependency Walker shows me an empty top right section and the section below it lists the function from the error message. If I check Undecorate C++ Functions it looks fine, but if I don't I get the weird question marks and @s from the error message and there appears to be a difference at the end: ?methodName@className@@UAEXXZ ?methodName@className@@UAEXH@Z Perhaps this is the problem, but I have no idea what it means, what may have caused this and what I can do about it.
I feel a bit stupid, but I found the answer. The application (exe) I was using apparently loaded a second, different dll which had a dependency on the one mentioned in my original post. This second dll was still expecting the old functions and also needed to be recompiled against the updated dll. Many thanks to the people who tried to help me here!
1,842,050
1,842,099
Explanation for return value casting that is going on
#include <Fl/Enumerations.H> class Color { public: static Color amber () {return fl_rgb_color (255, 204, 0);} static Color lighter_gray () {return fl_rgb_color (40, 40, 40); } static Color light_gray () {return fl_rgb_color (179, 179, 179);} static Color gray () {return fl_rgb_color (100, 100, 100);} static Color light_blue () {return fl_rgb_color (107, 107, 255);} static Color white () {return FL_WHITE;} static Color off_white() { return fl_rgb_color(225, 225, 225); } static Color cream() { return fl_rgb_color(204, 236, 255); } static Color black () {return FL_BLACK;} static Color red () {return FL_RED;} static Color green () {return FL_GREEN;} static Color dark_green () {return fl_rgb_color (0, 169, 45);} static Color blue () {return FL_BLUE;} static Color background () {return FL_BACKGROUND_COLOR;} Color (const Fl_Color& c = Color::black ()) : fl_color_ (c) {} operator Fl_Color () const {return fl_color_;} void make_current () const; private: Fl_Color fl_color_; }; and this is an excerpt of the important parts from Fl/Enumerations.h enum Fl_Color { // standard colors // These are used as default colors in widgets and altered as necessary FL_FOREGROUND_COLOR = 0, FL_BACKGROUND2_COLOR = 7, FL_INACTIVE_COLOR = 8, FL_SELECTION_COLOR = 15, // boxtypes generally limit themselves to these colors so // the whole ramp is not allocated: FL_GRAY0 = 32, // 'A' FL_DARK3 = 39, // 'H' FL_DARK2 = 45, // 'N' FL_DARK1 = 47, // 'P' FL_BACKGROUND_COLOR = 49, // 'R' default background color FL_LIGHT1 = 50, // 'S' FL_LIGHT2 = 52, // 'U' FL_LIGHT3 = 54, // 'W' // FLTK provides a 5x8x5 color cube that is used with colormap visuals FL_BLACK = 56, FL_RED = 88, FL_GREEN = 63, FL_YELLOW = 95, FL_BLUE = 216, FL_MAGENTA = 248, FL_CYAN = 223, FL_DARK_RED = 72, FL_DARK_GREEN = 60, FL_DARK_YELLOW = 76, FL_DARK_BLUE = 136, FL_DARK_MAGENTA = 152, FL_DARK_CYAN = 140, FL_WHITE = 255 }; #define FL_FREE_COLOR (Fl_Color)16 #define FL_NUM_FREE_COLOR 16 #define FL_GRAY_RAMP (Fl_Color)32 #define FL_NUM_GRAY 24 #define FL_GRAY FL_BACKGROUND_COLOR #define FL_COLOR_CUBE (Fl_Color)56 #define FL_NUM_RED 5 #define FL_NUM_GREEN 8 #define FL_NUM_BLUE 5 FL_EXPORT Fl_Color fl_inactive(Fl_Color c); FL_EXPORT Fl_Color fl_contrast(Fl_Color fg, Fl_Color bg); FL_EXPORT Fl_Color fl_color_average(Fl_Color c1, Fl_Color c2, float weight); inline Fl_Color fl_lighter(Fl_Color c) { return fl_color_average(c, FL_WHITE, .67f); } inline Fl_Color fl_darker(Fl_Color c) { return fl_color_average(c, FL_BLACK, .67f); } inline Fl_Color fl_rgb_color(uchar r, uchar g, uchar b) { if (!r && !g && !b) return FL_BLACK; else return (Fl_Color)(((((r << 8) | g) << 8) | b) << 8); } inline Fl_Color fl_rgb_color(uchar g) { if (!g) return FL_BLACK; else return (Fl_Color)(((((g << 8) | g) << 8) | g) << 8); } inline Fl_Color fl_gray_ramp(int i) {return (Fl_Color)(i+FL_GRAY_RAMP);} inline Fl_Color fl_color_cube(int r, int g, int b) { return (Fl_Color)((b*FL_NUM_RED + r) * FL_NUM_GREEN + g + FL_COLOR_CUBE);} I have been unable to wrap my mind about what is going on in the following class with regard to the static class definitions returning FL_COLOR enumerations. I can't see how Fl_Color could have any knowledge of the Color class and how the compiler could have any idea of how to convert an Fl_Color into a Color. I do realize that Color has an implicit conversion to Fl_Color, but I didn't think that conversion went both ways. How does this work? Does the compiler just call the constructor and pass in the return value as the first parameter?
The static methods returning a Color all return the result of a call to fl_rgb_color. fl_rgb_color returns a Fl_Color and Color has a single parameter constructor which is not marked explicit and takes a reference to a const Fl_Color so this is a valid implict conversion. The return value of fl_rgb_color is a temporary but because Color takes the Fl_Color parameter by a const reference it is legal to bind the temporary to the constructor parameter. Its lifetime lasts until the construction of the Color object (itself also a temporary for a return value) completes.
1,842,187
1,842,199
How is each byte in an integer stored in CPU / memory?
i have tried this char c[4]; int i=89; memcpy(&c[0],&i,4); cout<<(int)c[0]<<endl; cout<<(int)c[1]<<endl; cout<<(int)c[2]<<endl; cout<<(int)c[3]<<endl; the output is like: 89 0 0 0 which pretty trains my stomache cuz i thought the number would be saved in memory like 0x00000059 so how come c[0] is 89 ? i thought it is supposed to be in c[3]...
Because the processor you are running on is little-endian. The byte order, of a multi-byte fundamental type, is swapped. On a big-endian machine it would be as you expect.
1,842,377
1,867,649
Double buffer common controls
Is there a way to double-buffer the common controls? Currently when they resize they flicker. A lot..... EDIT: If it helps, it is a bunch of button controls and a few edit controls, all sitting on top of a tab control. The Tab control redraws itself, then the buttons redraw themselves. When the buttons redraw, they flicker. EDIT2: Here's an example of the problem I'm having: http://billy-oneal.com/Lobfuscator.exe
Look at using WS_EX_COMPOSITEDand WS_EX_TRANSPARENT styles. They provide doublebuffering, altough WM_PAINT will be called when the underlying bitmap is finished drawing, since it draws child controls from bottom to top, so you can paint only in your window procedure. I've used it in the past and work pretty well. Set your top-level window (container) to extended style WS_EX_COMPOSITED and your child windows with WS_EX_TRANSPARENT. Also, remember to define: #define WINVER 0x501 See CreateWindowEx for information on the composited style. This also makes possible to do perpixel transparency on child windows. UPDATE What about usign WM_PRINTCLIENT to transfer the client area to a bitmap on a DC and blit all the client area as a whole? http://blogs.msdn.com/larryosterman/archive/2008/08/27/larry-s-new-favorite-windows-message-wm-printclient.aspx
1,842,418
1,842,450
c++ / object-oriented quick review?
I am looking for quick reference guide(s) for both OO and C++. I have a few technical interviews coming up and I just want a quick reference that gives the basic overview of the fundamentals. (Nothing too in depth, as I've learned it all once before)
Have a look at this C++ tutorial online. There is also Bruce Eckel's Thinking In C++ freely available book. C++ FAQ Lite is searchable and Herb Sutter's Guru Of The Week series feature many tricky puzzles.
1,842,444
1,842,477
Clarification on a header without #includes
I was reading some code from the Doom 3 SDK ( in a VS solution ) when I found a header like this: #ifndef __PLAYERICON_H__ #define __PLAYERICON_H__ class idPlayerIcon { public: idPlayerIcon(); ~idPlayerIcon(); ...... // omitted public: playerIconType_t iconType; renderEntity_t renderEnt; qhandle_t iconHandle; }; #endif /* !_PLAYERICON_H_ */ The header has no forward class declaration nor #includes so, in my experience it should lead to an error like: Undeclared Identifier or Syntax error, cause renderEntity_t and qhandle_t are not "seen". So how can this compile correctly? Thank you in advance for the answers.
Because every time it is included, the needed entities are forward declared/included right before it, so everything is defined at the point of inclusion. As you correctly say, it will not work any other way.
1,842,445
1,843,116
How to convert std::wstring to a TCHAR*?
How to convert a std::wstring to a TCHAR*? std::wstring.c_str() does not work since it returns a wchar_t*. How do I get from wchar_t* to TCHAR*, or from std::wstring to TCHAR*?
#include <atlconv.h> TCHAR *dst = W2T(src.c_str()); Will do the right thing in ANSI or Unicode builds.
1,842,481
1,844,717
How do I update a value in a row in MySQL using Connector/C++
I have a simple database and want to update an int value. I initially do a query and get back a ResultSet (sql::ResultSet). For each of the entries in the result set I want to modify a value that is in one particular column of a table, then write it back out to the database/update that entry in that row. It is not clear to me based on the documentation how to do that. I keep seeing "Insert" statements along with updates - but I don't think that is what I want - I want to keep most of the row of data intact - just update one column. Can someone point me to some sample code or other clear reference/resource? EDIT: Alternatively, is there a way to tell the database to update a particular field (row/col) to increment an int value by some value? EDIT: So what is the typical way that people use MySQL from C++? Use the C api or the mysql++? I guess I chose the wrong API...
From a quick scan of the docs it appears Connector/C++ is a partial implementation of the Java JDBC API for C++. I didn't find any reference to updateable result sets so this might not be possible. In Java JDBC the ResultSet interface includes support for updating the current row if the statement was created with ResultSet.CONCUR_UPDATABLE concurrency. You should investigate whether Connector/C++ supports updateable resultsets. EDIT: To update a row you will need to use a PreparedStatement containing an SQL UPDATE, and then the statement's executeUpdate() method. With this approach you must identify the record to be update with a WHERE clause. For example update users set userName='John Doe' where userID=? Then you would create a PreparedStatement, set the parameter value, and then executeUpdate().
1,842,626
1,842,648
Location of const in a function
A similar question was previously asked, but none of the answers really provided what I was looking for. I am having trouble deciding where consts should be located in a function. I know a lot of people put them at the top, but if you put them as close as possible to where they are used, you'll reduce code span. I.e. void f() { const FOO = 3; ...// some code if ( bar > FOO ) { ...// do stuff } } or void f() { ...// some code const FOO = 3; if ( bar > FOO ) { ...// do stuff } } I'm leaning towards using the const at the top in small functions, and keeping the span as close as possible in large functions, but I was wondering what others' styles/thoughts are regarding this.
At the lowest scope possible, and directly before their first use. As a matter of style, exceptions can be made for clarity/asthetics, e.g., grouping conceptually similar constants.
1,842,678
1,842,691
C++: newbie initializer list question
Newbie here. I am looking at company code. It appears that there are NO member variables in class A yet in A's constructor it initializes an object B even though class A does not contain any member variable of type B (or any member variable at all!). I guess I don't understand it enough to even ask a question...so what's going on here!? My intuition is that you need a variable before you even try to initialize it. How is it possible (or what good does it do) to initialize an object without having the object? .h: class A: public B { public: A(bool r = true); virtual ~A; private: } .cpp: A::A(bool r) : B(r ? B::someEnumeration : B::anotherEnumeration) { } A::~A() { } Please help. Thanks, jbu
Class A (publicly) inherits from class B: class A: public B The only way to initialize a base class with parameters is through the initializer list.
1,842,732
1,843,692
writing to GUI issue
So i have a setup where two imacs, imac_1 and imac_2, are connected through firewire. imac_1 sends some debugging information to imac_2 and on imac_2 i have a program in c++ that captures debugging information.(see illustration below) Now the problem is that if i write the debugging info to the GUI (created using QT) directly its very slow, by slow i mean that the GUI takes time to load the data. So what i did was to write the debugging info to a buffer and then dump that buffer into the GUI but that was also slow because the GUI takes time to load the data. I was thinking of writing the debugging info to a file and then loading that into the gui. So i would load the first 10,000 lines into the gui and then when the user scrolls down i would load next 10,000 lines. imac_1(transmitter) --->FireWire (medium) --> imac_2 (receiver) any ideas or suggestions???? i am using: Mac OS X, XCode, imac
It sounds like your problem has nothing to do with the two computers communicating, but may instead be your GUI application. I would suggest you try the file approach you mention, if only to isolate the network component from the discussion. Then work on making your GUI faster. If you are adding the lines of text one at a time, that might account for some of the slowness, but 10,000 lines isn't really that many. Other approaches might include turning off redrawing or something similar while you are loading in the text file.
1,842,941
1,842,976
Translating python dictionary to C++
I have python code that contains the following code. d = {} d[(0,0)] = 0 d[(1,2)] = 1 d[(2,1)] = 2 d[(2,3)] = 3 d[(3,2)] = 4 for (i,j) in d: print d[(i,j)], d[(j,i)] Unfortunately looping over all the keys in python isn't really fast enough for my purpose, and I would like to translate this code to C++. What is the best C++ data structure to use for a python dictionary that has tuples as its keys? What would be the C++ equivalent of the above code? I looked at sparse matrices in the boost library, but couldn't find an easy way to loop only over the non-zero elements.
A dictionary would be a std::map in c++, and a tuple with two elements would be a std::pair. The python code provided would translate to: #include <iostream> #include <map> typedef std::map<std::pair<int, int>, int> Dict; typedef Dict::const_iterator It; int main() { Dict d; d[std::make_pair(0, 0)] = 0; d[std::make_pair(1, 2)] = 1; d[std::make_pair(2, 1)] = 2; d[std::make_pair(2, 3)] = 3; d[std::make_pair(3, 2)] = 4; for (It it(d.begin()); it != d.end(); ++it) { int i(it->first.first); int j(it->first.second); std::cout <<it->second <<' ' <<d[std::make_pair(j, i)] <<'\n'; } }
1,842,979
1,843,094
Cost of using std::map with std::string keys vs int keys?
I know that the individual map queries take a maximum of log(N) time. However I was wondering, I have seen a lot of examples that use strings as map keys. What is the performance cost of associating a std::string as a key to a map instead of an int for example ? std::map<std::string, aClass*> someMap; vs std::map<int, aClass*> someMap; Thanks!
In addition to the time complexity from comparing strings already mentioned, a string key will also cause an additional memory allocation each time an item is added to the container. In certain cases, e.g. highly parallel systems, a global allocator mutex can be a source of performance problems. In general, you should choose the alternative that makes the most sense in your situation, and only optimize based on actual performance testing. It's notoriously hard to judge what will be a bottleneck.
1,843,181
1,843,445
Is there a C++/win32 library function to convert a file path to a file:// URL?
I have an LPTSTR for a file path, i.e. C:\Program Files\Ahoy. I would like to convert it to a file:// URL that I can pass to ShellExecute in order to start the system's default browser pointing at the file. I don't want to give the path to ShellExecute directly since file associations may result in it being opened by something other than a web browser. The path is arbitrary, and may contain characters that need to be escaped. Is there an existing library function, along the lines of Python's urllib.pathname2url, that does this translation? This can be done via the Uri class in .NET, but I haven't found anything for plain win32.
There's the UrlCreateFromPath API: http://msdn.microsoft.com/en-us/library/bb773773%28VS.85%29.aspx
1,843,221
1,843,242
Restrict method access to a specific class in C++
I have two closely related classes which I'll call Widget and Sprocket. Sprocket has a set of methods which I want to be callable from Widget but not from any other class. I also don't want to just declare Widget a friend of Spocket because that would give Widget access to ALL protected and private members. I want to restrict Widget's access to only a specific set of methods. One solution I came up with is to create a nested class inside Sprocket that contains wrappers for these methods and make Widget a friend of this nested class. For example: class Sprocket { public: class WidgetInterface { friend class Widget; WidgetInterface(Sprocket* parent) : mParent(parent) {} private: void A() { mParent->A(); } void B() { mParent->B(); } Sprocket* mParent; }; private: void A() { ... } void B() { ... } }; class Widget { public: Widget(Sprocket* sprock) : mSprocketIface(sprock) {} void doStuff() { mSprocketIface.A(); } // Widget can call Sprocket::A() private: Sprocket::WidgetInterface mSprocketIface; }; This results in some code duplication because the method signatures are now declared in two places, but it works. But now suppose I want to add a subclass of Widget called SpecialWidget and I want that class to also have access to the Sprocket methods. I can simply add this new class to the Sprocket friends list or I can add yet another set of protected wrappers in Widget that SpecialWidget (and any other subclass) can access but you can see that this is now becoming a maintenance issue. I don't want to have to update the friends list or the wrappers if I add new classes or change the method signature. If I use the "add another set of wrappers" approach, the method signatures will be duplicated in three places! Does anyone know of a simpler, cleaner way to do this?
If you have two tightly coupled classes, then it's really not worth trying to make friend access any more granular than it is. You control the implementation of both, and you should trust yourself enough to not abuse the ability to call some methods that you don't, strictly speaking, need to call. If you want to make it clear for future code maintainers, add a comment to the friend declaration explaining why it is there (a good idea in general), and what private methods are allowed to be called by the friend class.
1,843,314
1,843,333
Embedded Visual C++/Why is my Symbol Undefined?
I am new to this platform, and I am trying to resolve an issue with existing code that was developed by a contractor many years ago. In Resource.h, I have something that looks like this, where the last two items I have added. #define IDC_HOSPITAL_NAME_LABEL 1069 #define IDC_REASON_LABEL 1070 #define IDC_HOSPITAL_NAME_EDIT 1071 #define IDC_COMMENTS_EDIT 1072 #define IDC_COMMENTS_LABEL 1073 I have compiled and deployed several times, I am using the constants in code and it doesn't complain on compile, however, while it might be unrelated to an issue I am trying to resolve, I do notice that in the IDE, if I right click and "Goto" definition of my new added items, it says "The symbol 'IDC_COMMENTS_LABEL' is undefined." In fact, it will happen even if I do this at the definition, where as it works as expected with the other non-new definitons.
Sounds to me like its just "one of those things". You will notice plenty. Try not to get too wound up by them. In the end ... if it compiles ... don't worry about it :)
1,843,369
1,843,404
How to create a file in a different directory in C++?
#include <iostream> #include <fstream> #include <cstdlib> int main() { std::fstream f1("/tmp/test"); if (!f1) { std::cerr << "f1 failed\n"; } else { std::cerr << "f1 success\n"; } FILE *f2 = fopen("/tmp/test", "w+"); if (!f2) { std::cerr << "f2 failed\n"; } else { std::cerr << "f2 success\n"; } } Creating a file in /tmp/ doesn't work for me using fstreams but it does with fopen. What could be the problem? (I get f1 failed and f2 success when /tmp/test doesn't already exist)
You have to tell the fstream you are opening the file for output, like this std::fstream fs("/tmp/test", std::ios::out); Or use ofstream instead of fstream, that opens the file for output by default: std::ofstream fs("/tmp/test");
1,843,410
1,854,085
OpenCV C++ error in Xcode
I have built the OpenCV libraries using the cmake build system as described here and have added the header, '.a' and '.dylib' files to my terminal c++ project. However when I run the code below (got it from http://iphone-cocoa-objectivec.blogspot.com/2009/01/using-opencv-for-mac-os-in-xcode.html), it gives me the errors below. Has anyone got any advice? Any help will be much appreciated. #include <stdlib.h> #include <stdio.h> #include <math.h> #include <cv.h> #include <highgui.h> int main() { //get the image from the directed path IplImage* img = cvLoadImage("/Users/somedir/Programming/TestProj/fruits.jpg", 1); //create a window to display the image cvNamedWindow("picture", 1); //show the image in the window cvShowImage("picture", img); //wait for the user to hit a key cvWaitKey(0); //delete the image and window cvReleaseImage(&img); cvDestroyWindow("picture"); //return return 0; } Errors Undefined symbols: "_cvLoadImage", referenced from: _main in main.o "_cvNamedWindow", referenced from: _main in main.o "_cvReleaseImage", referenced from: _main in main.o "_cvShowImage", referenced from: _main in main.o "_cvDestroyWindow", referenced from: _main in main.o "_cvWaitKey", referenced from: _main in main.o ld: symbol(s) not found collect2: ld returned 1 exit status
Avoid using Xcode with OpenCV 2.0. If using OpenCV use Windows and also use OpenCV 1.1. It will save a lot of headache. When 2.0/Mac are better documented then transition onto Mac platform/2.0 version. The book (O'Reilly) is good - covers v1.1. The next installment for 2.0 should follow soon. 1.
1,843,567
1,843,594
std::list threading push_back, front, pop_front
Is std::list thread safe? I'm assuming its not so I added my own synchronization mechanisms (I think i have the right term). But I am still running into problems Each function is called by a separate thread. Thread1 can not wait, it has to be as fast as possible std::list<CFoo> g_buffer; bool g_buffer_lock; void thread1( CFoo frame ) { g_buffer_lock = true ; g_buffer.push_back( frame ) ; g_buffer_lock = false; } void thread2( ) { while( g_buffer_lock ) { // Wait } // CMSTP_Send_Frame * pMSTPFrame = NULL ; while ( ! g_buffer_lock && g_buffer.size() > 0 ) { // Get the top item CFoo& pFoo = g_buffer.front() ; // Do something. // remove the front item g_buffer.pop_front(); } } After about 170k calls to thread1 and 900k calls to thread2 I get an exception error on CFoo& pFoo = g_buffer.front() ; That causes the program to crash. stdthrow.cpp: 22 #ifdef _DEBUG _CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL _Debug_message(const wchar_t *message, const wchar_t *file, unsigned int line) { // report error and die if(::_CrtDbgReportW(_CRT_ASSERT, file, line, NULL, message)==1) { ::_CrtDbgBreak(); } } _CRTIMP2_PURE void __CLRCALL_PURE_OR_CDECL _Debug_message(const unsigned short *message, const unsigned short *file, unsigned int line) { // report error and die _Debug_message((wchar_t *) message, (wchar_t *) file, line); } #endif Suggestions, comments, is there a better way of doing things?
Is std::list thread safe? The current C++ standard doesn't even acknowledge the existence of threads, so std::list certainly isn't. Different implementations, however, might provide (different levels of) thread safety. As for your code: If you need a lock, use a lock. That bool variable might not help when the threads are executed on different cores which fetch it from different caches. Use a real mutex instead.
1,843,581
1,844,056
Generate diagnostic message for HRESULT codes?
I'd like to be able to do the equivalent of FormatMessage - generate a text message for debug and even runtime builds that can report some of the common HRESULTs, or even spit out things like what the severity is, what facility it was, and possibly a description of the error code. I found this simple function, but its too simple, and mostly seems to generate "unknown error". But so far I haven't found anything that looks more promising. I can do something like the following: CComPtr<IErrorInfo> iei; if (S_OK == GetErrorInfo(0, &iei) && iei) { // get the error description from the IErrorInfo BSTR bstr = NULL; if (SUCCEEDED(iei->GetDescription(&bstr))) { // append the description to our label Append(bstr); // done with BSTR, do manual cleanup SysFreeString(bstr); } } else if (HRESULT_FACILITY(hr) == FACILITY_WIN32) { // append the description to our label Append(CErrorMessage(HRESULT_CODE(hr)).c_str()); } However, I wonder if I'm accomplishing anything more than _com_error. Does anyone know of a reasonably fleshed out facility for generating error log output for HRESULTs?
As you muse, _com_error::ErrorMessage() should do the trick. If you are getting "Unknown Error", then the HRESULTs you are getting are probably not known to windows. For those messages, try dumping the HRESULT value and figuring out if they actually map to win32 error codes. There are some com macros available to help you split out the bits of the HRESULT.
1,843,716
1,843,767
Is there a difference between a "child control", a "child window" and a "child window control"?
Or are these terms used to refer to the same thing? I'm trying to implement some custom buttons showing a bitmap image, into my Win32 app. One tutorial indicates I should be creating child windows using CreateWindow(). However, I have downloaded a bunch of source code from another tutorial on creating "child controls", and no reference is made to CreateWindow() (other than the one that creates the main/parent window). Can anyone help with what a button is classed as? A control or a Window?
Every control is a window, but not every window is a control. Controls have a parent and are usually one of the window classes that are appropriate in that context, such as a Button.
1,843,747
1,843,839
Why would buffer overruns cause segmentation faults when accessing an integer?
During a call to function B() from function A(), B() allocates a 100-char array and fills it several times, including once with a 101-character string and once with a 110 character string. This is an obvious mistake. Later, function A() tries to access completely unrelated int variable i, and a segmentation fault occurs. I understand why the buffer overrun occurs, but why do I get a segmentation fault when I access this integer? Why is it that I don't simply get garbage data?
When A() calls B(), B's preamble instructions save A's frame pointer—the location on the stack where A keeps local variables, before replacing it with B's own frame pointer. It looks like this: When B overruns its local variables, it messes up the value which will be reloaded into the frame pointer. This is garbage as a frame pointer value, so all of A's local variables are trashed. Worse, future writes to local variables are messing with memory belonging to someone else.
1,843,915
1,844,984
Variable number of arguments (va_list) with a function callback?
I am working on implementing a function that would execute another function a few seconds in the future, depending upon the user's input. I have a priority queue of a class (which I am calling TimedEvent) that contains a function pointer to the action I want it to execute at the end of the interval. Say for instance that the user wants the program to call a function "xyz" after 3 seconds, they would create a new TimedEvent with the time and the function pointer to xyz and add it to the priority queue (which is sorted by time, with the soonest events happening first). I have been able to successfully get the priority queue to pop off the top element after the specified time, but am running into a wall here. The functions I want to call could take a variety of different parameters, from ones that take only a single integer to ones that take 3 integers, a string, etc. and also return different values (some ints, some strings, etc.). I have looked into va_lists (which I have no experience with), but this doesn't seem to be the answer, unless I'm missing something. In summary (the TL;DR version): I would like to be able to call these functions as "diverse" as these with the same function pointer: void func1(int a, int b);<br/> int func2(int a, string b, OtherClass c); Am I on the right track with a va_list and a function callback? Can this be implemented easily (or at all)? Thanks!
I'm inferring here that these functions are API calls that you have no control over. I hacked up something that I think does more or less what you're looking for; it's kind of a rough Command pattern. #include <iostream> #include <string> using namespace std; //these are the various function types you're calling; optional typedef int (*ifunc)(const int, const int); typedef string (*sfunc)(const string&); // these are the API functions you're calling int func1(const int a, const int b) { return a + b; } string func2(const string& a) { return a + " world"; } // your TimedEvent is given one of these class FuncBase { public: virtual void operator()() = 0; }; // define a class like this for each function type class IFuncWrapper : public FuncBase { public: IFuncWrapper(ifunc fp, const int a, const int b) : fp_(fp), a_(a), b_(b), result_(0) {} void operator()() { result_ = fp_(a_, b_); } int getResult() { return result_; } private: ifunc fp_; int a_; int b_; int result_; }; class SFuncWrapper : public FuncBase { public: SFuncWrapper(sfunc fp, const string& a) : fp_(fp), a_(a), result_("") {} void operator()() { result_ = fp_(a_); } string getResult() { return result_; } private: sfunc fp_; string a_; string result_; }; int main(int argc, char* argv[]) { IFuncWrapper ifw(func1, 1, 2); FuncBase* ifp = &ifw; // pass ifp off to your TimedEvent, which eventually does... (*ifp)(); // and returns. int sum = ifw.getResult(); cout << sum << endl; SFuncWrapper sfw(func2, "hello"); FuncBase* sfp = &sfw; // pass sfp off to your TimedEvent, which eventually does... (*sfp)(); // and returns. string cat = sfw.getResult(); cout << cat << endl; } If you have a lot of functions returning the same type, you can define a subclass of FuncBase that implements the appropriate GetResult(), and wrappers for those functions can subclass it. Functions returning void would not require a GetResult() in their wrapper class, of course.
1,844,162
1,844,175
Assisting in avoiding assert... always!
In C and C++ assert is a very heavyweight routine, writing an error to stdout and terminating the program. In our application we have implemented a much more robust replacement for assert and given it its own macro. Every effort has been made to replace assert with our macro, however there are still many ways assert can be reintroduced (e.g., from internal third-party libraries, naïve injection, etc.) Any suggestions on how we can reduce, limit or even eradicate uses of assert? The best answer will be one the compiler can catch for us so we don't have to babysit the code base as much as we do currently.
I'm not sure I really understand the problem, actually. Asserts are only expensive if they go off, which is fine anyway, since you're now in an exception situation. assert is only enabled in debug builds, so use the release build of a third-party library. But really, asserts shouldn't be going off every moment.
1,844,213
1,844,479
Building game logic with events
I'm making a game engine in C++. It is supposed to read all its game-level logic from XML files, so I'm in need of a simple, but rock solid way of creating and handling events. So far all i have done is to use an Action class. It's practically equivalent to throwing callbacks around. An example could be an object (a map), that can change the scene if you click it. What bothers me is that I want to be able to delete the scene without worrying about all the objects that used to activate it.Is there a widely accepted way to do this? The way that I have done this so far is to make all the dependent/dependable objects inherit a dependent/dependable class. The class provides them with a list over objects that depend on them or that they depend on. class Dependent { protected: Dependent(); /// Warning all connected \ref Dependent that the Dependent does not exist. ~Dependent(); /// Connected Dependent \see connect(Dependent*, Dependent*) std::list<Dependent*>* dependents; /// Register a Dependent. void newDependent(Dependent*); /// Check if dependent on the given Dependent. bool listeningTo(const Dependent*) const; /// Used by a destructing connected Dependent to warn that it no longer exists. void stopListening(Dependent*); friend void connect(Dependent*, Dependent*); }; All this for just the ability to check if an element has ceased to exist. There is no automatic checking that the objects don't call the other after one has been deleted, but I'm able to do the check without worrying about using pointer that lead to nowhere. I'm hoping that there is a more elegant way to do this.
It sounds like you want to use a signal library, such as boost::signals or sigc. Either of those libraries will allow any of your objects to know when an event such as a click happens. They can also automate the cleanup when either the signaling object or a listening object is destroyed. Good luck!
1,844,223
1,844,227
#include iostream in C?
In C++ we always put the following at the top of the program #include <iostream> What about for C?
Well, this is called the standard I/O header. In C you have: #include <stdio.h> It's not an analog to <iostream>. There is no analog to iostream in C -- it lacks objects and types. If you're using C++, it's the analog to <cstdio>. stdio man page GNU documentation on Input/Output on Streams See also this fantastic question and its answer, 'printf' vs. 'cout' in C++
1,844,336
1,844,385
Compilers for DOS32?
Where can I get BASIC and C/C++ Compilers for MS-DOS?
There's DJGPP for C/C++. http://www.delorie.com/djgpp/
1,844,404
1,844,414
PeekMessage() Resetting the Mouse Cursor
Im currently messing around with changing the mouse cursor within a game like C++ application for Windows XP. To change the cursor I am using SetCursor() and passing in the desired cursor, which is working. However during the while loop in which PeekMessage() is called the cursor keep getting reset back to the default arrow. This is the offending loop: MSG msg; while( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } While debugging I found that the cursor changed during the call to PeekMessage() after which msg.message == 0x200, which should make the message one of these: WM_MOUSEFIRST = 0x200 WM_MOUSEMOVE = 0x200 I haven't been able to find any information on why this is happening, and have no experience with windows messages. Thanks. Edit: According to here the system redraws the class cursor everytime the mouse moves, effectively setting it back to the default cursor. With this in mind i added this to the window message callback function: case WM_SETCURSOR: return 0; problem solved.
How did you debug that? Unless you use SoftIce or some other application which doesn't share the windows mouse pointer, it would be hard to isolate the debugger from the application.
1,844,736
1,846,363
Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++
How to access elements by row, col in OpenCV 2.0's new "Mat" class? The documentation is linked below, but I have not been able to make any sense of it. http://opencv.willowgarage.com/documentation/cpp/basic_structures.html#mat
On the documentation: http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat It says: (...) if you know the matrix element type, e.g. it is float, then you can use at<>() method That is, you can use: Mat M(100, 100, CV_64F); cout << M.at<double>(0,0); Maybe it is easier to use the Mat_ class. It is a template wrapper for Mat. Mat_ has the operator() overloaded in order to access the elements.
1,844,887
1,844,904
How do you call the copy constructor within a member function of a class?
Here's what I've got: void set::operator =(const set& source) { if (&source == this) return; clear(); set(source); } And here's the error I get: vset.cxx:33: error: declaration of 'source' shadows a parameter How do I properly do this?
I believe with set(source); you are trying to call copy ctor. You can not do that in C++ i.e. you can not explicitly invoke the ctor. What you can do is write a private clone method and call it in both copy ctor and assignment operator.
1,845,474
1,845,609
Concatenate null-terminated strings recursively
I'm inventing interview questions that require analysis of C++ code that does something simple with pointers and recursion. I tried to write strcat() in recursive manner: size_t mystrlen( const char* str ) { if( *str == 0 ) { return 0; } return 1 + mystrlen( str + 1 ); } void mystrcpy( char* to, const char* from ) { if( ( *to = *from ) == 0 ) { return; } mystrcpy( to + 1, from + 1 ); } void mystrcat( char* to, const char* from ) { mystrcpy( to + mystrlen( to ), from ); } What I don't like here is that I have three functions and my strcat() is not very recursive - it just calls two other functions once. Is there a way to rewrite that somehow to reduce the number of functions increasing use of recursion but without sacrificing much of code brevity?
here's my example (the advantage is it has only one recursive call): char * mystrcat(char *dest, const char *src){ if(*dest == 0){ if(*src == 0) // end of recursion cond return dest; *dest = *src++; // actual copy dest[1]=0; // zero out dest buf } mystrcat(dest+1,src); // advance one char return dest; } here's rough test code: main(){ char c[]={'a',0,'b','c',0}; //char c[]={0,'b','c',0}; mystrcat(c,"xy"); //mystrcat(c,""); puts(c); }
1,845,482
1,845,491
What is the uintptr_t data type?
What is uintptr_t and what can it be used for?
uintptr_t is an unsigned integer type that is capable of storing a data pointer (whether it can hold a function pointer is unspecified). Which typically means that it's the same size as a pointer. It is optionally defined in C++11 and later standards. A common reason to want an integer type that can hold an architecture's pointer type is to perform integer-specific operations on a pointer, or to obscure the type of a pointer by providing it as an integer "handle".
1,845,734
1,845,766
Program option library for portable code
I have a portable code running on Visual C++ 2008 and RHEL 5.3 (gcc 4.x.x). My program should accept command line arguments. I consider using some library for that task. My candidats are: Boost program options ACE has this capability too (1) is not in standard and as for (2) we already using it heavily for other tasks. Which is prefered one? Maybe there're other libraries out there?
I like a lot boost::PO, but I never used ACE, so I can't compare. You're saying that boost is not a standard, but is it really a problem? Many people consider it as almost a standard. At least it isn't any exotic library.
1,845,869
1,845,924
Converting operator in enum
I wrote class like this: #pragma once #include "stdafx.h" struct Date { private: int day; int year; enum Month {jan = 1,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec}; Month* month; enum date_state { good,err_flag, bad_day, bad_month, bad_year, }; //I would like to define converting operator from enum to char Date::date_state::operator char() { return err_flag; } date_state err_state; void clear(date_state state = good); date_state rdstate() const; void check_day(const int d)const; void check_month()const; void check_year()const; public: Date(const int d,const Date::Month& m, const int y); }; and basically it doesn't work.
You can't declare member functions for enum date_state, because it is an enum, but you could do so for class Date: class Date { ... enum date_state { good, bad_day, bad_month, bad_year, } err_flag; operator char() { return err_flag; } } But would rather recommend using a normal member function instead, because a conversion operator might easily be used accidently.
1,845,870
1,845,898
why project dependency affect linker settings
any idea why project dependency (Visual Studio) affects linker settings (C++)? I thought that it's enough to chceck linker settings (Additional depend...) or pragma in source code. It's not a big problem, I'm just curious. Thanks.
If I understand correctly, you are referring to the feature that, when you check project B as dependency of project A, B gets linked into A. This is just for usablility. In that case, Visual Studio knows that it has to check B for changes (and rebuild if necessary) if A gets build. It's really just convenience.
1,845,908
1,846,005
Checking for intersection points between two rectangles?
If I have two rectangles whose positions are deifned using two 2D vectors (i.e. top left, bottom right) how can I check for the points they are intersecting?
I assume you actually want the result of the intersection, not only the test if both rectangles intersect. The intersection of rect1 = (l1, t1, r1, b1) and rect2 = (l2, t2, r2, b2) is again a rectangle: rectIntersection = ( max(l1, l2), max(t1, t2), min(r1, r2), min(b1, b2) ) rectIntersection is of course empty if left >= right || top >= bottom assuming a rectangle is left/top-inclusive and right/bottom-exclusive. The rectangles intersect if l1 < r2 && l2<r1 && t1<b2 && t2<t1
1,846,032
1,846,253
What is the easiest way to convert a char array to a WCHAR array?
In my code, I receive a const char array like the following: const char * myString = someFunction(); Now I want to postprocess it as a wchar array since the functions I use afterwards don't handle narrow strings. What is the easiest way to accomplish this goal? Eventually MultiByteToWideChar? (However, since it is a narrow string which I get as input, it doesn't have multibyte characters => probably not the most beautiful solution)
const char * myString = someFunction(); const int len = strlen(myString); std::vector<wchar_t> myWString (len); std::copy(myString, myString + len, myWString.begin()); const wchar_t * result = &myWString[0];
1,846,144
1,846,409
Pattern name for create in constructor, delete in destructor (C++)
Traditionally, in C++, you would create any dependencies in the constructor and delete them in the destructor. class A { public: A() { m_b = new B(); } ~A() { delete m_b; } private: B* m_b; }; This technique/pattern of resource acquisition, does it have a common name? I'm quite sure I've read it somewhere but can't find it now. Edit: As many has pointed out, this class is incomplete and should really implement a copy constructor and assignment operator. Originally, I intentionally left it out since it wasn't relevant to the actual question: the name of the pattern. However, for completeness and to encourage good practices, the accepted answer is what it is.
The answer to your question is RAII (Resource Acquisition Is Initialization). But your example is dangerous: Solution 1 use a smart pointer: class A { public: A(): m_b(new B) {} private: boost::shared_ptr<B> m_b; }; Solution 2: Remember the rule of 4: If your class contains an "Owned RAW pointer" then you need to override all the compiler generated methods. class A { public: A(): m_b(new B) {} A(A const& copy): m_b(new B(copy.m_b)) {} A& operator=(A const& copy) { A tmp(copy); swap(tmp); return *this; } ~A() { delete m_b; } void swap(A& dst) throw () { using std::swap; swap(m_b, dst.m_b); } private: B* m_b; }; I use the term "Owned RAW Pointer" above as it is the simplest example. But RAII is applicable to all resources and when your object contains a resource that you need to manage ('Owned RAW Poiner', DB Handle etc).
1,846,178
1,846,187
Crosscompiling C++; from Linux to Windows, does it really work?
I have the source code for some very simple command line programs. I was considering the option of compiling them on a Linux machine (they were deveoped here) so they can be used on Windows. If I am not wrong this is called Cross-compiling. I have never tried it, but reading yesterday some information, it seems to be kind of complicated or not successful. I would like to hear about your opinions, and how could I port a simple "hello world" program, which compiles on Linux with g++. Thanks
Look into mingw, a suite of tools for building Win32 applications in Linux. If the programs don't depend on any Linux-specific functionality not supported by mingw, you should be fine.
1,846,186
1,846,198
Thread safety of std::map for read-only operations
I have a std::map that I use to map values (field ID's) to a human readable string. This map is initialised once when my program starts before any other threads are started, and after that it is never modified again. Right now, I give every thread its own copy of this (rather large) map but this is obviously inefficient use of memory and it slows program startup. So I was thinking of giving each thread a pointer to the map, but that raises a thread-safety issue. If all I'm doing is reading from the map using the following code: std::string name; //here N is the field id for which I want the human readable name unsigned field_id = N; std::map<unsigned,std::string>::const_iterator map_it; // fields_p is a const std::map<unsigned, std::string>* to the map concerned. // multiple threads will share this. map_it = fields_p->find(field_id); if (map_it != fields_p->end()) { name = map_it->second; } else { name = ""; } Will this work or are there issues with reading a std::map from multiple threads? Note: I'm working with visual studio 2008 currently, but I'd like this to work acros most main STL implementations. Update: Edited code sample for const correctness.
This will work from multiple threads as long as your map remains the same. The map you use is immutable de facto so any find will actually do a find in a map which does not change. Here is a relevant link: http://www.sgi.com/tech/stl/thread_safety.html The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to to shared containers are safe. If multiple threads access a single container, and at least one thread may potentially write, then the user is responsible for ensuring mutual exclusion between the threads during the container accesses. You fall into he "simultaneous read accesses to shared containers" category. Note: this is true for the SGI implementation. You need to check if you use another implementation. Of the two implementations which seem widely used as an alternative, STLPort has built-in thread safety as I know. I don't know about the Apache implementation though.
1,846,385
1,846,447
Running a Windows program and detect when it ends with C++
Suppose I run an application, after some time this app will get closed by user. Is it possible to find out when the program exits? Can I get it's process id when I run that application?
This is a quote from here: #include <windows.h> #include <stdio.h> #include <tchar.h> #include <conio.h> void _tmain( int argc, TCHAR *argv[] ) { STARTUPINFO si; PROCESS_INFORMATION pi; STARTUPINFO sj; PROCESS_INFORMATION pj; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); ZeroMemory( &sj, sizeof(sj) ); sj.cb = sizeof(sj); ZeroMemory( &pj, sizeof(pj) ); // Start the child process p1.exe. Make sure p1.exe is in the // same folder as current application. Otherwise write the full path in first argument. if(!CreateProcess(L".\\p1.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &sj, &pj)) { printf( "Hello CreateProcess failed (%d)\n", GetLastError() ); getch(); return; } // Start child process p2.exe. Make sure p2.exe is in the // same folder as current application. Otherwise write the full path in first argument. if(!CreateProcess(L".\\p2.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { printf( "CreateProcess2 failed (%d)\n", GetLastError() ); getch(); return; } // Wait until child processes exit. WaitForSingleObject( pi.hProcess, INFINITE ); WaitForSingleObject( pj.hProcess, INFINITE ); // Close process and thread handles. CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); CloseHandle( pj.hProcess ); CloseHandle( pj.hThread ); getch(); }
1,846,392
1,846,402
Passing string as an argument in C
I am having a function: int getparam(char *gotstring) and i am passing a string argument to it, like char *sendstring = "benjamin" Instead of the above declaration I can use, int getparam(char gotstring[]) Question: Which one is better? And if I have to use int getparam(char gotstring[]) what are all the other changes I have to make to the existing function?
int getparam(char gotstring[]) and int getparam(char* gotstring) are identical. Personally, I would recommend the latter syntax, because it better describes what is actually going on. The getparam function only has a pointer to the string; it has no knowledge about the actual array size. However, that is just my opinion; either will work.
1,846,450
1,847,867
Cross-platform library for manipulating Windows paths?
I am writing a cross-platform application that needs to inspect and manipulate Windows-paths. Specifically, for the particular problem I am having now, I need to know if a path is absolute or relative. The current code uses boost::filesystem::path which of course works like a charm on Windows: boost::filesystem::path the_path(the_path_as_a_string); if (!the_path.has_root_path()) { /* do stuff */ } The problem with this approach is that boost::filesystem::path only has two modes: native and portable. This means that the Windows path grammar is unavailable when I compile under Linux (it is #ifdefed out in the source). Hence, the path "C:\path" is considered absolute in Windows, but relative in Linux. Can you guys recommend a cross-platform C++ library that can inspect and manipulate Windows-paths? For now, the only Windows-path operation I will do is to check whether a path is absolute or not. The criterion I will use for an absolute path is that it both contains a drive letter, and the path starts with \. An example of an absolute path under this criterion is C:\path. These are both examples of relative paths under this criterion: C:path, \path.
It seems to be difficult to find a library for this. One possibility is PathIsRelative in Winelib, but I don't want to use Winelib. I ended up doing a very specific solution just for deciding this small thing. Assuming that the path is correct (a fair assumption in my case), an absolute path will contain :\, while a relative path will not. So, the bad, but working, solution is: There is no suitable library. Check for existence of :\.
1,846,656
1,846,845
Cast boost::shared_array<char> to boost::shared_array<const char>
How can I cast a boost::shared_array<char> to boost::shared_array<const char>?
Since shared_array has no add_ref method you could emulate it as follows: struct MagicDeleter { MagicDeleter( boost::shared_array<char> ptr ) : ptr(ptr) {}; template<typename T> void operator()(T*) {} protected: boost::shared_array<char> ptr; }; ... boost::shared_array<char> orig_ptr( some_val ); boost::shared_array<const char> new_ptr( orig_ptr.get(), MagicDeleter(orig_ptr) );
1,846,684
1,867,534
.NET COM Library is not unloaded from C++ host process
We have a plugin system here, written in c++. Now that this has to have an ability to upgrade plugins(which are COM) we need to unload the plugin, install the plugin and then load it again. Now the problem is that this has to happen without closing an app. c++ COM dlls get unloaded pretty good but .NET ones not. Here's the sample code I'm using to load/unload the COM. #include "stdafx.h" #import "C:\Projects\MyTLBWithInterface.tlb" raw_interfaces_only, raw_native_types, no_namespace, named_guids int _tmain(int argc, _TCHAR* argv[]) { CoInitialize(0); try { CLSID rclsid; HRESULT hr = CLSIDFromProgID(_T("MY_NET_COM"), &rclsid); if (hr != S_OK) { return false; } IMYInterfaceForCom *cpi =NULL; hr = CoCreateInstance(rclsid, 0, CLSCTX_ALL, __uuidof(IUnknown),reinterpret_cast<void**>(&cpi)); if (SUCCEEDED(hr)) { BSTR name; cpi->GetName(&pluginName); MessageBox(0,pluginName, L"MyApp", MB_OK|MB_ICONERROR); ULONG CC = cpi->Release(); CoFreeUnusedLibraries(); } } catch(_com_error & e) { _bstr_t bstrSource(e.Source()); _bstr_t bstrDescription(e.Description()); printf("\nException:\n\tSource : %s \n\tDescription : %s \n",(LPCSTR)bstrSource,(LPCSTR)bstrDescription); } catch(...) { printf("\nException"); } CoUninitialize(); return 0; }
Resolved via this thread
1,846,856
1,846,879
How do I determine if an indexed mode SDL_Surface has transparency or not?
I've got code I've been working with to load and convert SDL_Surfaces to OpenGL textures, however I've realized that they only work with RGB(A) surfaces. I need to extend the support onto indexed mode images (with or without transparency). Initially, I was looking into ::SDL_SetColorKey(), however it seems to only work with SDL blits. I've read up on SDL_Surface, SDL_PixelFormat and SDL_Color, and then begun to sketch up the following (//# is pseudocode): SDL_Surface *pSurf(::IMG_Load(image)); ::SDL_LockSurface(pSurf); Uint32 bytesPerPixel(pSurf->format->bytesPerPixel); GLenum pixelFormat; Uint8 *pixelData(pSurf->pixels); bool allocated(false); // pixelData isn't allocated if(pSurf->format->palette != 0) // indexed mode image { //# Determine transparency. // HOW? //# bytesPerPixel = 3 or 4 depending on transparency being present; //# pixelFormat = GL_RGB or GL_RGBA depending on bytesPerPixel; Uint32 blockSize(pSurf->w * pSurf->h * bytesPerPixel); pixelData = new Uint8[blockSize]; allocated = true; //# traverse pSurf->pixels, look up pSurf->format->palette references and copy // colors into pixelData; } else { //# Determine pixelFormat based on bytesPerPixel and pSurf->format->Rmask // (GL_RGB(A) or GL_BGR(A)). } //# Pass bytesPerPixel, pixelFormat and pixelData to OpenGL (generate texture, // set texture parameters, glTexImage2D etc). if(allocated) { delete[] pixelData; pixelData = 0; } ::SDL_UnlockSurface(pSurf); ::SDL_FreeSurface(pSurf); So, the question is: how can I determine if the indexed mode image I'm passing to this routine has transparency?
The typical way it's done for indexed mode is either to have a full 32-bit RGBA palette, so you have 8 bits of alpha per indexed color slot. Or, you can just define a certain (range of) palette index as being transparent. OpenGL supports the latter, through the GL_PIXEL_MAP_I_TO_A table accessed through glPixelMap(). See glPixelTransfer() for a description of the translation logic.
1,846,979
1,848,315
force a bit field read to 32 bits
I am trying to perform a less-than-32bit read over the PCI bus to a VME-bridge chip (Tundra Universe II), which will then go onto the VME bus and picked up by the target. The target VME application only accepts D32 (a data width read of 32bits) and will ignore anything else. If I use bit field structure mapped over a VME window (nmap'd into main memory) I CAN read bit fields >24 bits, but anything less fails. ie :- struct works { unsigned int a:24; }; struct fails { unsigned int a:1; unsigned int b:1; unsigned int c:1; }; struct main { works work; fails fail; } volatile *reg = function_that_creates_and_maps_the_vme_windows_returns_address() This shows that the struct works is read as a 32bit, but a read via fails struct of a for eg reg->fail.a is getting factored down to a X bit read. (where X might be 16 or 8?) So the questions are : a) Where is this scaled down? Compiler? OS? or the Tundra chip? b) What is the actual size of the read operation performed? I basiclly want to rule out everything but the chip. Documentation on that is on the web, but if it can be proved that the data width requested over the PCI bus is 32bits then the problem can be blamed on the Tundra chip! edit:- Concrete example, code was:- struct SVersion { unsigned title : 8; unsigned pecversion : 8; unsigned majorversion : 8; unsigned minorversion : 8; } Version; So now I have changed it to this :- union UPECVersion { struct SVersion { unsigned title : 8; unsigned pecversion : 8; unsigned majorversion : 8; unsigned minorversion : 8; } Version; unsigned int dummy; }; And the base main struct :- typedef struct SEPUMap { ... ... UPECVersion PECVersion; }; So I still have to change all my baseline code // perform dummy 32bit read pEpuMap->PECVersion.dummy; // get the bits out x = pEpuMap->PECVersion.Version.minorversion; And how do I know if the second read wont actually do a real read again, as my original code did? (Instead of using the already read bits via the union!)
As an example, the Linux kernel has inline functions that explicitly handle memory-mapped IO reads and writes. In newer kernels it's a big macro wrapper that boils down to an inline assembly movl instruction, but it older kernels it was defined like this: #define readl(addr) (*(volatile unsigned int *) (addr)) #define writel(b,addr) ((*(volatile unsigned int *) (addr)) = (b))
1,847,032
1,910,190
Upgradeable read/write lock Win32
I am in search of an upgradeable read write lock for win32 with the behaviour of pthreads rwlock, where a read lock can be up- and downgraded. What I want: pthread_rwlock_rdlock( &lock ); ...read... if( some condition ) { pthread_rwlock_wrlock( &lock ); ...write... pthread_rwlock_unlock( &lock ); } ...read... pthread_rwlock_unlock( &lock ); The upgrade behaviour is not required by posix, but it works on linux on mac. Currently, I have a working implementation (based on an event, a semaphore and a critical section) that is upgradeable, but the upgrade may fail when readers are active. If it fails a read unlock + recheck + write lock is necessary. What I have: lock.rdlock(); ...read... if( some condition ) { if( lock.tryupgrade() ) { ...write... lock.unlock(); return; } else { lock.unlock(); // <- here, other threads may alter the condition -> lock.wrlock(); if( some condition ) { // so, re-check required ...write... } lock.unlock(); return; } } ...read... lock.unlock(); EDIT: The bounty: I am still in search, but want to add some restrictions: it is used intra-process-only (so based on critical sections is ok, WIN32 mutexes are not ok), and it should be pure WIN32 API (no MFC, ATL etc.). Acquiring read locks should be fast (so, acquiring the read lock should not enter a critical section in its fast path). Maybe an InterlockedIncrement based solution is possible?
The boost shared_mutex class supports reader (shared) and writer (unique) locks and temporary upgrades from shared to unique locks. Example for boost shared_mutex (multiple reads/one write)? I don't recommend writing your own, it's a tricky thing to get right and difficult to test thoroughly.
1,847,038
1,847,074
Illegal call to non-static member function (C++)?
I'm developing a game which is based around the user controlling a ball which moves between areas on the screen. The 'map' for the screen is defined in the file ThreeDCubeGame.cpp: char m_acMapData[MAP_WIDTH][MAP_HEIGHT]; The ThreeDCubeGame.cpp handles most of the stuff to do with the map, but the player (and keyboard input) is controlled by ThreeDCubePlayer.cpp. When a player moves into a new map cell, the game will have to check the contents of that cell and act accordingly. This function in ThreeDCubeGame.cpp is what I am trying to use: inline char GetMapEntry( int iMapX, int iMapY ) { return m_acMapData[iMapX][iMapY]; } So, in order to check whether the player is allowed to move into a map cell I use this function call from ThreeDCubePlayer.cpp: if (ThreeDCubeGame::GetMapEntry(m_iMapX+MAP_OFF_X, m_iMapY+MAP_OFF_Y) == ' ') { // do stuff } But, when I compile this, I get the warning "error C2352: 'ThreeDCubeGame::GetMapEntry' : illegal call of non-static member function". Is this something to do with the scope of the variables? Is it fixable without redesigning all the code?
class A { int i; public: A(): i(0) {} int get() const { return i; } }; int main() { A a; a.get(); // works A::get(); // error C2352 } There's no object to call the function with.
1,847,131
1,847,229
How many digits in this base?
The problem is to derive a formula for determining number of digits a given decimal number could have in a given base. For example: The decimal number 100006 can be represented by 17,11,9,8,7,6,8 digits in bases 2,3,4,5,6,7,8 respectively. Well the formula I derived so far is like this : (log10(num) /log10(base)) + 1. in C/C++ I used this formula to compute the above given results. long long int size = ((double)log10(num) / (double)log10(base)) + 1.0; But sadly the formula is not giving correct answer is some cases,like these : Number 8 in base 2 : 1,0,0,0 Number of digits: 4 Formula returned: 3 Number 64 in base 2 : 1,0,0,0,0,0,0 Number of digits: 7 Formula returned: 6 Number 64 in base 4 : 1,0,0,0 Number of digits: 4 Formula returned: 3 Number 125 in base 5 : 1,0,0,0 Number of digits: 4 Formula returned: 3 Number 128 in base 2 : 1,0,0,0,0,0,0,0 Number of digits: 8 Formula returned: 7 Number 216 in base 6 : 1,0,0,0 Number of digits: 4 Formula returned: 3 Number 243 in base 3 : 1,0,0,0,0,0 Number of digits: 6 Formula returned: 5 Number 343 in base 7 : 1,0,0,0 Number of digits: 4 Formula returned: 3 So the error is by 1 digit.I just want somebody to help me to correct the formula so that it work for every possible cases. Edit : As per the input specification I have to deal with cases like 10000000000, i.e 10^10,I don't think log10() in either C/C++ can handle such cases ? So any other procedure/formula for this problem will be highly appreciated.
There are fast floating operations in your compiler settings. You need precise floation operations. The thing is that log10(8)/log10(2) is always 3 in math. But may be your result is 2.99999, for expample. It is bad. You must add small additive, but not 0.5. It should be about .00001 or something like that. Almost true formula: int size = static_cast<int>((log10((double)num) / log10((double)base)) + 1.00000001); Really true solution You should check the result of your formula. Compexity is O(log log n) or O(log result)! int fast_power(int base, int s) { int res = 1; while (s) { if (s%2) { res*=base; s--; } else { s/=2; base*=base; } } return res; } int digits_size(int n, int base) { int s = int(log10(1.0*n)/log10(1.0*base)) + 1; return fast_power(base, s) > n ? s : s+1; } This check is better than Brute-force test with base multiplications.
1,847,196
1,847,218
Efficient switch statement
In the following two versions of switch case, I am wondering which version is efficient. 1: string* convertToString(int i) { switch(i) { case 1: return new string("one"); case 2: return new string("two"); case 3: return new string("three"); . . default: return new string("error"); } } 2: string* convertToString(int i) { string *intAsString; switch(i) { case 1: intAsString = new string("one"); break; case 2: intAsString = new string("two"); break; case 3: intAsString = new string("three"); break; . . default: intAsString = new string("error"); break; } return intAsString; } 1: has multiple return statements will it cause compiler to generate extra code?
This is a premature optimization worry. The former form is clearer and has fewer source lines, that is a compelling reason to chose it (in my opinion), of course. You should (as usual) profile your program to determine if this function is even on the "hot list" for optimization. This will tell you if there is a performance penalty for using break. As was pointed out in the comments, it's very possible that the main performance culprit of this code is the dynamically allocated strings. Generally, when implementing this kind of "integer to string" mapping function, you should return string constants.
1,847,410
3,039,857
crypto++ RSA and "invalid ciphertext"
Well, I've been going through my personal hell these days I am having some trouble decrypting a message that was encrypted using RSA and I'm always failing with a "RSA/OAEP-MGF1(SHA-1): invalid ciphertext" I have a private key encoded in base64 and I load it: RSA::PrivateKey private_key; StringSource file_pk(PK,true,new Base64Decoder); private_key.Load( file_pk ); I then proceed to decode the message by doing: RSAES_OAEP_SHA_Decryptor decryptor(private_key); AutoSeededRandomPool rng; string result; StringSource(ciphertext, true, new PK_DecryptorFilter(rng, decryptor, new StringSink(result) ) ); As far as I can tell, the message should be being parsed without any problems. ciphertext is an std::string, so no \0 at the end that could do something unexpected. I just though of something, and what if the private key is incorrect but can be loaded anyway without throwing a BER decode error. What would that throw when decrypting? Hope that anyone can shed some light on this. Cheers
If the key was actually corrupted, the Load function should have failed. However you can ask the key to self-test itself, which should detect any corruption, by calling Validate, like: bool key_ok = private_key.Validate(rng, 3); The second parameter (here, 3) specifies how much checking to be done. For RSA, this will cause it to run all available tests, even the slow/expensive ones. Another reason the decoding might fail is if the key simply is not the one that was used to encrypt the original message. Obviously the ciphertext input must be completely identical to what was originally produced on the encrypting side. For debugging, one good way to check this would be to feed the ciphertext at both sides into a hash function (conveniently already available to you, of course) and comparing the outputs. If you hex or base64 encoded the ciphertext for transmission you must undo that before you give it to the RSA decryptor.
1,847,478
1,847,540
Protecting class from getting instantiated before main()
I want to ensure that my C++ class is never instantiated before main() is entered. Is there any way to achieve this? -- Some clarification: I am writing an embedded application. My class must be static (reside in the BSS), but at instantiation it requires some resources that aren't available before certain things has been initialized in start of main(). So I want to make it a Meyers singleton. Ideally I would like to make some kind of assert that ensures that MyClass::instance() is never called before main().
One thing you can do is have a static method like MyClass::enableConstruction() which turns on a static flag in the class. If the c'tor is called when this flag is false then it throws an exception. This way you'll alteast have some run-time indication that someone is breaking the rules. Notice that you should be careful with the initialization of that static flag. To avoid any construction order problems it would probably be best to make it a singleton that is initialized when first accessed.
1,847,640
1,849,152
COleDataSource - setting drag & drop data between applications
Some code I am working on uses COleDataSource::CacheGlobalData, passing as CF_TEXT an HGLOBAL pointing to some memory allocated for the text. I want to also add a numeric value, so ythe drop-target can access either the text or numeric values. How can this easily be done? Can a 2nd CacheGlobalData call be made with a different CF_ value? And since I only want to pass an integer (DWORD) can I avoid having to allocate a messy HGLOBAL? Or do I have to encode all the data i want to send into a single chunk of memory? Does CacheGlobalData only let be attach one object to the drag event?
You can call CacheGlobalData multiple times. For each clipboard format, the clipboard stores the last value set by CacheGlobalData. For example, IE stores data in CF_UNICODETEXT, CF_TEXT and CF_HTML formats when you drag a paragraph of text. Generally an application should provide data in as many formats as possible so more applications can recognize the data. To avoid data lose in round trips, clipboard formats that contain the most information should be placed on the clipboard first, followed by less descriptive formats. For example, CF_HTML first, CF_UNICODETEXT second and CF_TEXT last. You probably need to register your own format for the numeric value and modify your drop target application that can understand your own format. None of the standard formats take a numeric value. Clipboard data must be stored in global memory. If you don't like that, you can pass NULL and handle WM_RENDERFORMAT or WM_RENDERALLFORMATS messages to provide data when needed, but for a DWORD it is not worth the effort.
1,847,661
1,847,697
Calling a Child class' method when processing a list of Parent class objects
This question seems like it might be somewhat common, but I didn't find anything when scowering StackOverflow or the interwebs. I came across a method in a C++ class that takes a list of (for example) Parent objects. For this example, assume that there are two classes that derive from Parent: Child1 and Child2. For each object in the list, the method checks if the object is of type Child2 (via a IsOfType() method that each class implements), and if so, it calls a method that is only provided by the Child2 class. Is this an issue in that the list-processing method cannot treat each object the same? I've seen this done in other places as well, so it seems it might be a common practice to some degree. One option might be to declare the Child2 method in the Parent class so that all Parent objects implement it. However, in this case, only the Child2 class would actually implement any behavior when overriding the method. Your thoughts? Thanks in advance!
If your IsOfType() test passes, you can cast the (pointer to the) parent object to a Child2 object and access its specific member functions. EDIT: This depends on your design and on how strict you ensure the IsOfType() implementation will give correct answers (i.e. it also works when you add new subclasses in a week). It might be safer to make use of the builtin Typeid instead. Implementing every possible method any child would ever have in the parent would be difficult, so upcasting is ok when the method is really semantically specific to the Child2 class.
1,847,717
1,847,770
Does CAtlList::RemoveAt invalidate existing POSITIONS?
I'm looking at this, where m_Rows is a CAtlList: void CData::RemoveAll() { size_t cItems = m_Rows.GetCount(); POSITION Pos = m_Rows.GetHeadPosition(); while(Pos != 0) { CItem* pItem = m_Rows.GetAt(Pos); if (pItem != 0) delete pItem; POSITION RemoveablePos = Pos; pItem = m_Rows.GetNext(Pos); m_Rows.RemoveAt(RemoveablePos); } } and am wondering if there's potential that the RemoveAt call may invalidate Pos?
According to the documentation, CAtlList behaves like a double linked list, so removing one list item should not invalidate the pointers to other items. The POSITION type references the memory location of a list item directly: Most of the CAtlList methods make use of a position value. This value is used by the methods to reference the actual memory location where the elements are stored, and should not be calculated or predicted directly. It seems this is not the case in atlcoll.h: template< typename E, class ETraits > void CAtlList< E, ETraits >::RemoveAt( POSITION pos ) { ATLASSERT_VALID(this); ATLENSURE( pos != NULL ); CNode* pOldNode = (CNode*)pos; // remove pOldNode from list if( pOldNode == m_pHead ) { m_pHead = pOldNode->m_pNext; } else { ATLASSERT( AtlIsValidAddress( pOldNode->m_pPrev, sizeof(CNode) )); pOldNode->m_pPrev->m_pNext = pOldNode->m_pNext; } if( pOldNode == m_pTail ) { m_pTail = pOldNode->m_pPrev; } else { ATLASSERT( AtlIsValidAddress( pOldNode->m_pNext, sizeof(CNode) )); pOldNode->m_pNext->m_pPrev = pOldNode->m_pPrev; } FreeNode( pOldNode ); }
1,847,822
1,848,418
name collision in C++
While writing some code i came across this issue: #include <iostream> class random { public: random(){ std::cout << "yay!! i am called \n" ;} }; random r1 ; int main() { std::cout << "entry!!\n" ; static random r2; std::cout << "done!!\n" ; return 0 ; } When i try to compile this code i get the error error: ârandomâ does not name a type. When I use some different name for the class the code works fine. Seems like random is defined somewhere else(although the compiler message is not very informative). My question is how can i assure that a name i am using doesn't collides with a name used in included files. I have tried using namespaces but that leads to ambiguity at the time of call. Any insights? [EDIT] I used namespaces as using namespace myNSpace But when i used it as use myNSpace::random it worked fine.
Why does your using namespace... not work, while your using ... works? First i want to show you another way to solve it by use of an elaborated type specifier: int main() { // ... static class random r2; // notice "class" here // ... } That works because "class some_class" is an elaborated type specifier, which will ignore any non-type declarations when looking up the name you specify, so the POSIX function at global scope, which has the same name, will not hide the class name. You tried two other ways to solve it: Using directives and using declarations: Then, you tried to stick the type into a namespace, and tried using namespace foo; in main - why did it not work? namespace foo { class random { public: random(){ std::cout << "yay!! i am called \n" ;} }; } int main() { using namespace foo; static random r2; // ambiguity! return 0 ; } You might wonder why that is so, because you might have thought that the using directive declares the names of foo into the local scope of main - but that's not the case. It's not declaring any name, actually it's just a link to another namespace. It's making a name visible during unqualified name lookup in that case - but the name is made visible as a member of the namespace enclosing both the using-directive and the denoted namespace (foo). That enclosing namespace is the global namespace here. So what happens is that name lookup will find two declarations of that name - the global POSIX random declaration, and the class declaration within foo. The declarations were not made in the same scope (declarative region), and so the function name doesn't hide the class name as usual (see man stat for an example where it does), but the result is an ambiguity. A using declaration however declares one name as a member of the declarative region that it appears in. So, when random is looked up starting from main, it will first find a name that refers to the declaration of random in foo, and this will effectively hide the global POSIX function. So the following works namespace foo { class random { public: random(){ std::cout << "yay!! i am called \n" ;} }; } int main() { using foo::random; static random r2; // works! return 0 ; }
1,847,846
1,849,280
Pass by value or reference, to a C++ constructor that needs to store a copy?
Should a C++ (implicit or explicit) value constructor accept its parameter(s) by value or reference-to-const, when it needs to store a copy of the argument(s) in its object either way? Here is the shortest example I can think of: struct foo { bar _b; foo(bar [const&] b) // pass by value or reference-to-const? : _b(b) { } }; The idea here is that I want to minimize the calls to bar's copy constructor when a foo object is created, in any of the various ways in which a foo object might get created. Please note that I do know a little bit about copy elision and (Named) Return Value Optimization, and I have read "Want Speed? Pass by Value", however I don't think the article directly addresses this use case. Edit: I should be more specific. Assume that I can't know the sizeof(bar), or whether or not bar is a fundamental, built-in type (bar may be a template parameter, and foo may be a class template instead of a class). Also, don't assume that foo's constructor can be inlined (or bar's, for that matter). Do assume that I at least might be using a compiler that implements RVO. What I would like is for there to be a possibility (given compiler optimizations) that a call like this will invoke no calls to bar's copy constructor whatsoever (even when executing _b(b) in foo's initialization list): foo f = function_that_creates_and_returns_a_bar_object_using_rvo(); Is there any possibility (given the C++98 standard) that this can be done, and if so, is it more or less likely to work if foo accepts its parameter by reference-to-const instead of by value?
In C++98 and C++03, you should pass const& bar and then copy. In C++0x, you should pass bar and then do a move (provided bar has a move constructor). #include <utility> struct foo { bar _b; foo(bar b) : _b(std::move(b)) {} }; If you construct foo with an lvalue parameter, the copy constructor will be called to create a copy b, and that copy will be moved into _b. If you construct foo with an rvalue parameter, bar's move constructor will be called to move into b, and then it will be moved again into _b.
1,847,860
1,847,949
Why is there a performance warning on casting pointer to bool?
This question extends Why use !! when converting int to bool?. I thought I was being cool when I did something like: bool hasParent() { return this->parentNode; } Where this->parentNode is NULL when there is no parent node. But I'm getting: warning C4800: 'Node *' : forcing value to bool 'true' or 'false' (performance warning) Even with a (bool) cast, the warning still doesn't go away. What's the deal, yo? Why is that a performance warning? I thought it'd be less efficient to write something like: bool hasParent() { if (this->parentNode) return true; else return false; } But the second version generates no warnings and the compiler seems a lot happier. Which is faster though?
There's a discussion on Microsoft Connect about this (What is the performance implication of converting to bool in C++?). The example given to Microsoft is: $ cat -n t.cpp && cl -c -W3 -O2 -nologo -Fa t.cpp 1 bool f1 (int i) 2 { 3 return i & 2; 4 } 5 6 bool f2 (int i) 7 { 8 const bool b = i & 2; 9 return b; 10 } 11 12 bool f3 (int i) 13 { 14 const bool b = 0 != (i & 2); 15 return b; 16 } t.cpp t.cpp(3) : warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning) t.cpp(8) : warning C4800: 'int' : forcing value to bool 'true' or 'false' (performance warning) And Microsoft's response (from the developer responsible for the warning) is: This warning is surprisingly helpful, and found a bug in my code just yesterday. I think Martin is taking "performance warning" out of context. It's not about the generated code, it's about whether or not the programmer has signalled an intent to change a value from int to bool. There is a penalty for that, and the user has the choice to use "int" instead of "bool" consistently (or more likely vice versa) to avoid the "boolifying" codegen. The warning is suppressed in the third case below because he's clearly signalled his intent to accept the int->bool transition. It is an old warning, and may have outlived its purpose, but it's behaving as designed here So basically the MS developer seems to be saying that if you want to 'cast' an int to bool you should more properly do it by using "return this->parentNode != 0" instead of an implicit or explicit cast. Personally, I'd be interested to know more about what kind of bugs the warning uncovers. I'd think that this warning wouldn't have a whole lot of value.
1,848,136
1,848,248
What is the reason for not allowing in C++ a default value for a variable to be a non-static method or member of a class?
I wanted to know why the default value for a variable for a method of a class, cannot be a non-static method or member of the same class. Is there a reason for that ? Could not the compiler provide to the method the position in the class of the non-static default value ? I tried to google quickly for an answer but I could not come up with a good answer. EDIT: here is an example. This is legal: class ClassTemp { static int s_member; int MagicOperation(int defaultValue = s_member) { return defaultValue; } }; But this is not: class ClassTemp { int m_member; int MagicOperation(int defaultValue = m_member) { return defaultValue; } };
Default arguments are evaluated in the context of the caller (which is why they are usually called "arguments", not "parameters"), not in the context of the class method. This means that in order to evaluate these non-static arguments the compiler would need to know the specific class instance from which to take these default values. Of course, it is possible in theory to allow using non-static members as default parameters and make compilers use the class instance that is specified in the member call. But that does not sound like "C++ way" of doing things to me. Also, it might lead to rather convoluted and inelegant specification in some more complicated cases, for example, when the method is virtual.
1,848,286
1,848,301
Why does `include <iostream>` end up including so *many* files?
Follow up of this question: When I do include <iostream>. It happens that it includes many files from /usr/include .A grep "\usr\include" over g++ -E prog.cpp counted to about 1260 entries ;). Is their a way to control including various files? Platform: Linux G++ version: 4.2.4
No, <iostream> includes them because it depends on them directly, or it's dependancies depend on them. Ain't nothing you can do about it. You can (depending on your compiler) limit the effect this has on compilation times by using Precompiled Headers
1,848,479
1,849,327
In windbg, How to set breakpoint on all functions in kernel32.dll?
I want figure out the call sequence and functions to kernel32.dll in a function example() in example.DLL. In windbg, how to set breakpoint on all functions in kernel32.dll? I tried bm kernel32!* , but seems not work.
I would not do just as stated. Of course it is possible, but if done with bm /a kernel32!* you inadvertently set bps also on data symbols (as opposed to actual functions). In your case wt - trace and watch data (you can look it up in the debugger.chm provided with your windbg package) might be what you're after.
1,848,585
1,848,598
What is the best way for two programs on the same machine to communicate with each other
I need to pass some data (integers) from one (C++) program to another (C#). What is the fastest way to do this? P.S.: OS: Windows XP
My personal preference for this, given that you're using C++ and C# both, and it's on the same system, would be to use Pipes. They work very well from native code (C++) as well as from C# via NamedPipeClientStream and NamedPipeServerStream. However, there are other options for Interprocess Communication, any of which would work.
1,848,730
1,848,769
c++ read from file redirection and also keyboard
My program reads a list of integers from user input [ keyboard] and calculates some statistics The user enters 'x' to terminate the input process. So for example, Enter integers separated by space ( enter x to quit) : 1 2 3 4 5 x But now I want to include the inputs to be read from file redirection also. So if the numbers followed by x is in a data file, the program should take it from there if not then prompt the user
use isatty for your file descriptor (0 for standard input) example: #include <unistd.h> main(){ if(isatty(0)) puts("tty"); // print some prompt else puts("pipe"); // not really needed in your case }
1,849,447
1,849,487
How can you detect if two regular expressions overlap in the strings they can match?
I have a container of regular expressions. I'd like to analyze them to determine if it's possible to generate a string that matches more than 1 of them. Short of writing my own regex engine with this use case in mind, is there an easy way in C++ or Python to solve this problem?
There's no easy way. As long as your regular expressions use only standard features (Perl lets you embed arbitrary code in matching, I think), you can produce from each one a nondeterministic finite-state automaton (NFA) that compactly encodes all the strings that the RE matches. Given any pair of NFA, it's decidable whether their intersection is empty. If the intersection isn't empty, then some string matches both REs in the pair (and conversely). The standard decidability proof is to determinize them into DFAs first, and then construct a new DFA whose states are pairs of the two DFAs' states, and whose final states are exactly those in which both states in the pair are final in their original DFA. Alternatively, if you've already shown how to compute the complement of a NFA, then you can (DeMorgan's law style) get the intersection by complement(union(complement(A),complement(B))). Unfortunately, NFA->DFA involves a potentially exponential size explosion (because states in the DFA are subsets of states in the NFA). From Wikipedia: Some classes of regular languages can only be described by deterministic finite automata whose size grows exponentially in the size of the shortest equivalent regular expressions. The standard example are here the languages L_k consisting of all strings over the alphabet {a,b} whose kth-last letter equals a. By the way, you should definitely use OpenFST. You can create automata as text files and play around with operations like minimization, intersection, etc. in order to see how efficient they are for your problem. There already exist open source regexp->nfa->dfa compilers (I remember a Perl module); modify one to output OpenFST automata files and play around. Fortunately, it's possible to avoid the subset-of-states explosion, and intersect two NFA directly using the same construction as for DFA: if A ->a B (in one NFA, you can go from state A to B outputting the letter 'a') and X ->a Y (in the other NFA) then (A,X) ->a (B,Y) in the intersection (C,Z) is final iff C is final in the one NFA and Z is final in the other. To start the process off, you start in the pair of start states for the two NFAs e.g. (A,X) - this is the start state of the intersection-NFA. Each time you first visit a state, generate an arc by the above rule for every pair of arcs leaving the two states, and then visit all the (new) states those arcs reach. You'd store the fact that you expanded a state's arcs (e.g. in a hash table) and end up exploring all the states reachable from the start. If you allow epsilon transitions (that don't output a letter), that's fine: if A ->epsilon B in the first NFA, then for every state (A,Y) you reach, add the arc (A,Y) ->epsilon (B,Y) and similarly for epsilons in the second-position NFA. Epsilon transitions are useful (but not necessary) in taking the union of two NFAs when translating a regexp to an NFA; whenever you have alternation regexp1|regexp2|regexp3, you take the union: an NFA whose start state has an epsilon transition to each of the NFAs representing the regexps in the alternation. Deciding emptiness for an NFA is easy: if you ever reach a final state in doing a depth-first-search from the start state, it's not empty. This NFA-intersection is similar to finite state transducer composition (a transducer is an NFA that outputs pairs of symbols, that are concatenated pairwise to match both an input and output string, or to transform a given input to an output).
1,849,490
1,849,508
C++ - Arguments for Exceptions over Return Codes
I'm having a discussion about which way to go in a new C++ project. I favor exceptions over return codes (for exceptional cases only) for the following reasons - Constructors can't give a return code Decouples the failure path (which should be very rare) from the logical code which is cleaner Faster in the non-exceptional case (no checking if/else hundreds of thousands of times) If someone screws up the return code settings (forgets to return FAIL) it can take a very long time to track down. Better information from the message contained in the error. (It was pointed out to me that a return enum could do the same for error codes) From Jared Par Impossible to ignore without code to specifically designed to handle it These are the points I've come up with from thinking about it and from google searches. I must admit to being predisposed to exceptions having worked in C# for the past couple of years. Please post further reasons for using exceptions over return codes. For those who prefer return codes, I would also be willing to listen to your reasoning. Thanks
I think this article sums it up. Arguments for Using Exceptions Exceptions separate error-handling code from the normal program flow and thus make the code more readable, robust and extensible. Throwing an exception is the only clean way to report an error from a constructor. Exceptions are hard to ignore, unlike error codes. Exceptions are easily propagated from deeply nested functions. Exceptions can be, and often are, user defined types that carry much more information than an error code. Exception objects are matched to the handlers by using the type system. Arguments against Using Exceptions Exceptions break code structure by creating multiple invisible exit points that make code hard to read and inspect. Exceptions easily lead to resource leaks, especially in a language that has no built-in garbage collector and finally blocks. Learning to write exception safe code is hard. Exceptions are expensive and break the promise to pay only for what we use. Exceptions are hard to introduce to legacy code. Exceptions are easily abused for performing tasks that belong to normal program flow.
1,849,558
1,850,059
How do I use QTextBlock?
I'm completely new to C++ and Qt. I want to populate a QTextEdit object with QTextBlocks, how do I do that? e.g. If I have the sentence "the fish are coming" how would I put each word into its own QTextBlock and add that block to QTextEdit, or have I misunderstood how QTextBlock actually works?
QTextEdit will let you add your contents via a QString: QTextEdit myEdit("the fish are coming"); It also allows you to use a QTextDocument, which holds blocks of text. The QTextDocument itself also can accept a QString: QTextEdit myEdit; QTextDocument* myDocument = new QTextDocument("the fish are coming", &myEdit); myEdit.setDocument(myDocument); However, "If you need to create a new text block, or modify the contents of a document while examining its contents, use the cursor-based interface provided by QTextCursor instead." (Qt documentation) (Note, I added the QTextBlockFormat lines to make it explicit where the blocks are.) QTextEdit myEdit; QTextDocument* myDocument = new QTextDocument(&myEdit); myEdit.setDocument(myDocument); QTextCursor* myCursor = new QTextCursor(myDocument); QTextBlockFormat format; format.setBackground(Qt::red); myCursor->setBlockFormat(format); myCursor->insertText("the "); format.setBackground(Qt::green); myCursor->insertBlock(format); myCursor->insertText("fish "); format.setBackground(Qt::yellow); myCursor->insertBlock(format); myCursor->insertText("are "); format.setBackground(Qt::red); myCursor->insertBlock(format); myCursor->insertText("coming!"); format.setBackground(Qt::green); myCursor->insertBlock(format); myCursor->insertText(QString(%1 blocks").arg(myDocument->blockCount())); myEdit.show(); Seems like a lot of effort to go through to me. Can you give any additional information on why you feel you need to use QTextBlocks?
1,849,571
1,849,629
Calling pointer-to-member function in call for a function passed to a template function
This is the provided function template I'm trying to use: template <class Process, class BTNode> void postorder(Process f, BTNode* node_ptr) { if (node_ptr != 0) { postorder( f, node_ptr->left() ); postorder( f, node_ptr->right() ); f( node_ptr->data() ); } } This is my call, and the function I'm passing: void city_db::print_bst() { postorder(&city_db::print, head); } void city_db::print(city_record target) { std::cout << target.get_code(); } This is the compile time (G++) error I get: CityDb.cpp:85: instantiated from here BinTree.template:80: error: must use ‘.’ or ‘->’ to call pointer-to-member function in ‘f (...)’ make: *** [CityDb.o] Error 1 This is in reference to the line f( node_ptr->data() ); in the function template. This is for a Data Structures project. The assignment was modified so we don't need to pass a function to a function, but I've been interested in this for quite some time, and I feel like I almost have it here. I've exhausted Google and Lab TA's, so if StackOverflow has ideas, they would be greatly appreciated.
Your problem is that postorder accepts a function object that must be called this way: f(arg); You are passing in a pointer to member function. You should first call mem_fun to make a function object from the pointer to member: std::mem_fun(&city_db::print) The returned function object takes two arguments: the pointer to a city_db (the implicit this pointer), and the object to be printed. You can bind the first to this with bind1st, like this: std::bind1st(std::mem_fun(&city_db::print), this) And now you should be able to call postorder on it: postorder(std::bind1st(std::mem_fun(&city_db::print), this), head);
1,849,608
1,849,648
Unix C++ simple server question: sending data back to browser
I am creating a simple Unix server written in C++ that simply waits for incoming connections, and then when a connection is established, it sends the requested data back to the client's browser to be displayed. I have everything working except for the sending of the data to the client. This is how it should work: I start server and set port number (for this example i'll use 8181). Client opens browser and connects to my server located at http://server.mysite.com:8181/test.txt and attempts to retrieve test.txt for viewing. Server accepts incoming connection. It checks to see if file exists. If file exists, it sends the file to the browser to be viewed. My problem is that I'm not sure how to send the data back to the browser to be viewed. I'm trying to use Unix system calls to get this accomplished, as I believe that's all that should be needed to get the data back. Right now all I'm doing is read()ing in from the file into a char array buffer and then feeding that into the write(socketID, buffer, strlen(buffer)) command. When I test it, the server correctly finds the file and reads the data into the char array buffer, but the write() command is returning a -1 error value every time. I would like to get it to where the browser connects and then is able to view the text.txt in the browser as well as browser-supported picture formats. Is there some way to workaround the "reading in to a buffer then writing that buffer to a socket" part and just somehow send the file directly to the browser? Here is part of the code I'm working with now. I just commented in other parts of code. //create and bind socket. call listen()... conn_socket = accept(socketInt, (struct sockaddr *)&caddr, (socklen_t *) &caddrLength); recvInt = recv(conn_socket, requestedFileBuffer, 1023, 0); if(recvInt > 0){ //checks to see that the requestd file exists and correctly //reads that file into char array "buffer" int writeInt = write(recvInt, buffer, strlen(buffer));//This is not working cout << "writeInt is: " << writeInt << endl;// returns -1 }//end if Anyone have any suggestions? If you need me to post more code I'd be happy to do so, but I believe the problem lies in the above code. Thanks for your time.
When you say: int writeInt = write(recvInt, buffer, strlen(buffer)); the first parameter of write() should be the socket to write to - you are passing it the count of characters returned by recv()
1,849,738
1,849,769
including .h file from a different application/directory
I have some .h files as follows (on Linux) Source/Server/connect.h Source/Server/message.h ... I am developing another application that needs the two .h files but is in a different directory Source/App2/.. How can I include the connect.h file in the App2 application, considering that I use perforce and everyone else working on the application would have their own copy so adding an absolute path to the include library might not be a good idea but im not sure. EDIT: I use a proprietary build mechanism for building the code so will not be able to specify gcc options directly.
You can #include a relative path to the files: #include "../Server/connect.h" or you can add a flag to tell the compiler to look in the other directory. For gcc you can use -I../Server; for Visual C++ you can use /I"../Server"; other compilers, I'm sure, have their own flags for this purpose. I think the second is better in most cases, since it allows you to move your projects around while only requiring you to modify the include path in one place (the makefiles or property sheets).
1,849,918
1,851,489
Pipe communication C++
I´m writing two litle c++ apps that must communicate. First one will be a service which, every once in a while, must alert the user for something. Since a service cannot create windows I designed the app to be two separate executables. The service will use a notifier to communicate. The service needs only to send text messages to the notifier wich will show up a balloon at system tray. I´m trying to use named pipes and I think I´m almost there, but not quite there. What I have so far is: At the notifier side: m_hInPipe = CreateNamedPipe(L"\\\\.\\pipe\\nhsupspipe", PIPE_ACCESS_INBOUND, PIPE_WAIT, 1, 1024, 1024, 60, NULL); Meaning I created a pipe named nhsupspipe, an inbound pipe. At the service side: if (!WriteFile(m_hOutPipe, "My message to the user?", 23, &escritos, &o)) std::cout << "ERROR: " << GetLastError(); Debugging I can see that it is all ok, the pipe is created and the WriteFile writes my 23 bytes to the pipe. My question is: How, in the notifier side I´ll be able to read these bytes? Is there any message sent to the process? Do I have to write a handler for the pipe? Anything?
Some simple snippets from the client (your service) & the server (the notifier) [Note: This is adapted from a project I've done a while ago which in turn was heavily "influenced" by the MSDN samples from CreateNamedPipe & co]: Server side: HANDLE hPipe = INVALID_HANDLE_VALUE; bool bConnected = false; hPipe = CreateNamedPipe( L"\\\\.\\pipe\\nhsupspipe", PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, sizeof( Message ), 0, 0, NULL ); // failed to create pipe? if( hPipe == INVALID_HANDLE_VALUE ){ return -1; } // Wait for the client to connect; if it succeeds, // the function returns a nonzero value. If the function // returns zero, GetLastError returns ERROR_PIPE_CONNECTED. bConnected = ConnectNamedPipe( hPipe, NULL ) ? true : ( GetLastError() == ERROR_PIPE_CONNECTED ); if( bConnected ){ while( true ){ unsigned long ulBytesRead = 0; // read client requests from the pipe. bool bReadOk = ReadFile( hPipe, &message, sizeof( message ), &ulBytesRead, NULL ); // bail if read failed [error or client closed connection] if( !bReadOk || ulBytesRead == 0 ) break; // all ok, process the message received } } else{ // the client could not connect, so close the pipe. CloseHandle( hPipe ); } return 0; The client: HANDLE hPipe = INVALID_HANDLE_VALUE; // create the named pipe handle hPipe = CreateFile( L"\\\\.\\pipe\\nhsupspipe", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL ); // if everything ok set mode to message mode if( INVALID_HANDLE_VALUE != hPipe ){ DWORD dwMode = PIPE_READMODE_MESSAGE; // if this fails bail out if( !SetNamedPipeHandleState( hPipe, &dwMode, NULL, NULL ) ){ CloseHandle( hPipe ); return -1; } } unsigned long ulBytesWritten = 0; bool bWriteOk = WriteFile( hPipe, ( LPCVOID )&message, sizeof( Message ), &ulBytesWritten, NULL ); // check if the writing was ok if( !bWriteOk || ulBytesWritten < sizeof( Message ) ){ return -1; } // written ok return 0; The Message mentioned above is a structure that will be your message, which you will probably want to pack. Since in your scenario the client (the service) will probably be up & running before the server (the notifier) you'll need to have in place some kind of reconnection strategy on the client side. And on a slightly different note you should consider carefully what Mr. Osterman said in his reply (even for nothing else but because he's Larry Osterman).