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,454,268
1,459,974
What is the reason for a segmentation fault with this C++ code using lists?
I have some complicated C++ code but the problem narrows down to doing a push_back on a list of structures: list<cache_page> cachedPages; void f() { cache_page cpage(a,b); cachedPages.push_back(cpage); } I have commented all the data members of the struct cache_page and still the error persists. If I comment the push_back line, there is no error. What could be the reason? I have tried using GDB and the error occurs in _List_Node_base::hook() function. template < class T > class A { T x; public: void func() { x->f(); } }; class B : public A < B* > { list<cache_page> cachedPages; public: void f() { cache_page cpage; cachedPages.push_back(cpage); } }; I have a do nothing copy constructor. I have no data members in cache_page.
You're crossing the streams. Haven't you seen Ghostbusters? Don't cross the streams. You're crossing the streams here: class B : public A < B *> I don't understand the point of this. What are you trying to do? CRTP? This is not the way it's done. The problem is not in the push back, the problem is, "this" being invalid. When you have void f() { cache_page cpage; } It's compiled to a NOP. this is not acceded everything is fine. void f() { cache_page cpage; // oops this access this->cachedPages.push_back(cpage); } Except it's called in the context of A. What is the value of this ? It's not initialized anywhere. So this is equal to whatever is in memory, where a happy uninitialized list is waiting. The fix? template < class T > class A { T * _x; public: explicit A(T * x) : _x(x) {} void func() { _x->f(); } }; class B : public A < B > { list<cache_page> cachedPages; public: B(void) : A<B>(this) {} void f() { cache_page cpage; cachedPages.push_back(cpage); } }; This should work better. But what about... template < class T > class A { public: void func() { static_cast<T>(this)->f(); } }; class B : public A<B> { list<cache_page> cachedPages; public: void f() { cache_page cpage; cachedPages.push_back(cpage); } }; That's the way CRTP is done.
1,454,344
1,454,373
C++ - cloning base class
I have something like that: Class Foo : Base {.."my stuph" ..}; int main() { Base *b = new Base; Foo f (b); <== **error** "invalid conversion from Base to Foo." .. } How can I clone b to f? In "my stuph" I have functions which make workout between Foo and Base. I can't change Base to much while it's written by others. Thanks
You can't automatically make a derived class out of base one. You can do vice versa and create a base class out of the derived, however, and this might confuse you. To do what you want, you should add proper constructor to Foo and think how you will actually create information missing in a Base instance to constitute a fully-functional Foo instance. The constructor may look like this: Foo(Base const& b) : Base(b) { /* construct info specific to Foo (absent in Bar) */ }
1,454,455
1,454,688
Event-Driven Client/Server Design with C++
I am designing a game server with scripting capabilities. The general design goes like this: Client connects to Server, Server initializes Client, Server sends Client to EventManager (separate thread, uses libevent), EventManager receives receive Event from Client socket, Client manages what it received via callbacks. Now the last part is what's the most tricky for me now. Currently my design allows me for a class which inherits Client to create callbacks to specific received events. These callbacks are managed in a list and the received buffer goes through a parsing process each time something is received. If the buffer is valid, the callback is called where it is act upon what is in the buffer. One thing to note is that the callbacks can go down to the scripting engine, at which point nothing is sure what can happen. Each time a callback finishes, the current receive buffer has to be reset etc. Callbacks currently have no capability of returning a value, because as stated before, anything can happen. What happens is that when somewhere in the callback something says this->disconnect(), I want to immediately disconnect the Client, remove it from the EventManager, and lastly remove it from the Server, where it also should get finally destructed and free memory. However, I still have some Code running after the callback finishes in the Client, thus I can't free memory. What should I change in the design? Should I have some timed event in the Server which checks which Clients are free to destroy? Would that create additional overhead I don't need? Would it still be okay after the callback finishes to run minimal code on the stack (return -1;) or not? I have no idea what to do, but I am open for complete design revamps. Thanks in advance.
You can use a reference counted pointer like boost::shared_ptr<> to simplify memory management. If the manager's client list uses shared_ptrs and the code that calls the callbacks creates a local copy of the shared_ptr the callback is called on, the object will stay alive until it is removed from the manager and the callback function is complete: class EventManager { std::vector< boost::shared_ptr<Client> > clients; void handle_event(Event &event) { // local |handler| pointer keeps object alive until end of function, even // if it removes itselfe from |clients| boost::shared_ptr<Client> handler = ...; handler->process(event); } }; class Client { void process(Event &event) { manager->disconnect(this); // the caller still holds a reference, so the object lives on } } The Client object will automatically be deleted once the last shared_ptr to it goes out of scope, but not before. So creating a local copy of the shared_ptr before a function call makes sure the object is not deleted unexpectedly.
1,454,843
1,454,864
variable length array of classes
I have some code which is effectively this: class dummie_type { public: int a; void do_stuff() { // blah } }; class dummie_type dummie[10]; void main() { subroutine(); } void subroutine() { dummie[3].a = 27; // etc... dummie[5].do_stuff(); } Note that the array of classes is global, and I need it to remain so (its a long story). I need to change this code so that the array of classes is of variable length. I know that this will involve making a global pointer, and then setting that to point to a block of memory that gets malloc'ed or new'ed in main and I know that I will have to change the "." characters to "->" but other than that I keep failing to produce something that my compiler will accept. I'm particularly uncertain about the declaration of a global pointer to an array of classes. Edit: Sorry I should have said earlier, the array size will be calculated once near the start of main() and will remain unchanged from then on.
I know that this will involve making a global pointer, and then setting that to point to a block of memory that gets malloc'ed or new'ed in main and I know that I will have to change the "." characters to "->" but other than that I keep failing to produce something that my compiler will accept. I'm particularly uncertain about the declaration of a global pointer to an array of classes. That's basically all there is to it. You declare dummie as dummie_type * dummie; and then you do dummie = new dummie_type[size]; in main. And no, you don't need to change . to ->.
1,454,949
1,455,020
How do I test features that are not in the public interface?
I'm designing a library for myself that allows the chaining of streams of data. Let me paint the scenario: I create a SerialDatastream which is the bottom layer and reads from and writes to a COM port. I pass a pointer to this to the constructor of a ProtocolDatastream, which interprets the bytes when read from the serial datastream (although it only has knowledge that it fulfills my Datastream interface), and returns them as protocol data units. Now let's say I want to take the information from the serial port and also log it byte for byte. I insert a TeeDatastream in the middle which reads from one source, but outputs to two destinations: +-----> Log | Serial ----> Tee ----> Protocol TeeDatastream is implemented in the following way: when a read operation is performed from one branch, it buffers the data into a member variable. Then, when a read operation is performed on the other branch, it reads the already-buffered data. (this works fine, by the way) What this means is that, after each operation, the class must check to see if there exists data that has been read from both branches. This data can then be discarded and so the buffer shrinks as well as growing. However, this is completely invisible to any client of the class. So my question is: what pattern should be used to test invisible but necessary parts of an implementation?
What you need are unit tests for Tee itself; independent of its use later in other unit tests as part of the plumbing. For these new unit tests, the "invisible part" is actually what they must cover. This is no longer a hidden feature but part of the API of Tee. Later, when you're sure that Tee works correctly (and have the necessary tests to make sure it stays that way), you can use it and be oblivious to the fact how it works.
1,455,190
1,456,878
How to access MySQL from multiple threads concurrently
We're doing a small benchmark of MySQL where we want to see how it performs for our data. Part of that test is to see how it works when multiple concurrent threads hammers the server with various queries. The MySQL documentation (5.0) isn't really clear about multi threaded clients. I should point out that I do link against the thread safe library (libmysqlclient_r.so) I'm using prepared statements and do both read (SELECT) and write (UPDATE, INSERT, DELETE). Should I open one connection per thread? And if so: how do I even do this.. it seems mysql_real_connect() returns the original DB handle which I got when I called mysql_init()) If not: how do I make sure results and methods such as mysql_affected_rows returns the correct value instead of colliding with other thread's calls (mutex/locks could work, but it feels wrong)
As maintainer of a fairly large C application that makes MySQL calls from multiple threads, I can say I've had no problems with simply making a new connection in each thread. Some caveats that I've come across: Edit: it seems this bullet only applies to versions < 5.5; see this page for your appropriate version: Like you say you're already doing, link against libmysqlclient_r. Call mysql_library_init() (once, from main()). Read the docs about use in multithreaded environments to see why it's necessary. Make a new MYSQL structure using mysql_init() in each thread. This has the side effect of calling mysql_thread_init() for you. mysql_real_connect() as usual inside each thread, with its thread-specific MYSQL struct. If you're creating/destroying lots of threads, you'll want to use mysql_thread_end() at the end of each thread (and mysql_library_end() at the end of main()). It's good practice anyway. Basically, don't share MYSQL structs or anything created specific to that struct (i.e. MYSQL_STMTs) and it'll work as you expect. This seems like less work than making a connection pool to me.
1,455,320
1,549,100
How to get the cpu usage per thread on Mac OSX
I am looking for an OS level API to account for cycles consumed by a specific thread in OSX. This is similar to this question (and answer) but in OSX.
You should be able to get this info from the thread_basic_info structure, returned by a call to thread_info.
1,455,333
1,455,384
how to use binder and bind2nd functors?
How to use binder2nd, bind2nd, and bind1st? More specifically when to use them and are they necessary? Also, I'm looking for some examples.
They're never, strictly speaking, necessary, as you could always define your own custom functor object; but they're very convenient exactly in order to avoid having to define custom functors in simple cases. For example, say you want to count the items in a std::vector<int> that are > 10. You COULD of course code...: std::count_if(v.begin(), v.end(), gt10()) after defining: class gt10: std::unary_function<int, bool> { public: result_type operator()(argument_type i) { return (result_type)(i > 10); } }; but consider how much more convenient it is to code, instead: std::count_if(v.begin(), v.end(), std::bind1st(std::less<int>(), 10)) without any auxiliary functor class needing to be defined!-)
1,455,401
1,455,420
Redefine a derived class' variable
Is the following valid? Or how can I get something close to this. template<class T_> class Template { //something }; class Parent { public: Template<Parent> variable; Parent() : variable(this) { } }; class Derived : public Parent { public: Template<Derived> variable; Derived() : Parent() { } } Thanks in advance.
It's technically "valid" in that your compiler has to accept it (it may warn you, and IMHO it should), but it doesn't do what you think it does: Derived's variable is separate from Parent's, and is not getting explicitly initialized (so it uses the default ctor for Template<>).
1,455,600
1,460,184
MySQL Connector C++ - make Error 1
I'm writing an application in C++ (using Eclipse with Linux GCC) that's supposed to interact with my MySQL server. I've downloaded the MySQL Connector C++ a, precompiled, and copied the files into the directories (/usr/lib, /usr/include). I've referenced in in the GCC C++ Linker Section of the Project Properties in Eclipse ( "mysqlcppconn"). My code comes directly from the MySQL Reference (Hello World) except I removed error handling and the delete statements at the end (I'm not even getting there so whats the point) #include <stdlib.h> #include <iostream> #include "mysql_connection.h" #include "mysql_driver.h" #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> using namespace std; int main(void) { sql::Driver *driver; sql::Connection *con; sql::Statement *stmt; sql::ResultSet *res; driver = get_driver_instance(); con = driver->connect("tcp://127.0.0.1:3306", "root", "root"); con->setSchema("test"); stmt = con->createStatement(); res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); while (res->next()) { cout << "\t... MySQL replies: "; cout << res->getString("_message") << endl; cout << "\t... MySQL says it again: "; cout << res->getString(1) << endl; } return EXIT_SUCCESS; } now when I compile this, It gives me a make error 1, which the man page says means I need to recompile my packages. I've tried it, it doesn't work. I seem to have hit dead ends everywhere. Can anyone tell me how to fix this problem? (make could really tell me what I should recompile.) Anyone have any tips/suggestions/ideas where I went wrong? Edit - Chagned the code a bit, but the general idea is the same. Update - If I use the terminal instead of exlipse to make, it tells me that the problem is obviously that the connector wants libstdc++.so.5 whilst I have libstdc++.so.6.
The Solution is quite simple - compile your own Connector. I did it with the 1.0.5 version of the Connector. to do it, you need to install the package via sudo apt-get install mysql-client In the directory of the source package you downloaded (and extracted), type cmake . apparently, in three files of the driver, references are made to snprintf and printf, without including the stdio.h header. I added #include <stdio.h> to each file and then, in the terminal, typed make then, I copied the Files to my lib directory sudo cp path/to/driver/libmysqlcppconn* /usr/lib/ and everythign worked a charm.
1,456,225
1,456,261
Spinlocks, How Useful Are They?
How often do you find yourself actually using spinlocks in your code? How common is it to come across a situation where using a busy loop actually outperforms the usage of locks? Personally, when I write some sort of code that requires thread safety, I tend to benchmark it with different synchronization primitives, and as far as it goes, it seems like using locks gives better performance than using spinlocks. No matter for how little time I actually hold the lock, the amount of contention I receive when using spinlocks is far greater than the amount I get from using locks (of course, I run my tests on a multiprocessor machine). I realize that it's more likely to come across a spinlock in "low-level" code, but I'm interested to know whether you find it useful in even a more high-level kind of programming?
It depends on what you're doing. In general application code, you'll want to avoid spinlocks. In low-level stuff where you'll only hold the lock for a couple of instructions, and latency is important, a spinlock mat be a better solution than a lock. But those cases are rare, especially in the kind of applications where C# is typically used.
1,456,342
1,456,586
Are there any free tools to help with automatic code generation?
A few semesters back I had a class where we wrote a very rudimentary scheme parser and eventually an interpreter. After the class, I converted my parser into a C++ parser that did a reasonably good job of parsing C++ as long as I didn't do anything fancy with the preprocessor or macros. I could use it to read over my classes and functions and do neat things like automatically generate class readers or writers or set up function callbacks from a text file. However, my program is pretty limited. I'm sure I could spend some time to make it more robust and do more neat things, but I don't want to spend the time and effort if there are already more robust tools available that do the same thing. I figure there has to be something like this out there since parsers are an essential part of compilers, but I haven't seen tools specifically for automatic code generation that make it easy to go through and play with data structures that represent classes, functions and variables for C++ specifically. Are there tools that do this? Edit: Hopefully this will clarify a little bit of what I'm looking for. The program I have runs as a prebuild step in visual studio. It reads over my source files, makes a list of classes, their members, their functions, etc. which is then used to generate new code. Currently I just use it to make it easy to read and write my data structures to a plain text file, but I could do other things as well. The file readers and writers are output into plain .cpp and .h files which I include in the rest of my project just as I would any other file. What I'm looking for are tools that do similar things so I can decide if I should continue to use my own or switch to a some better solution. I'm not looking for anything that generates machine code or edits code that I've written.
A complete parser-building tool like ANTLR or YACC is necessary if you want to parse C++ from scratch, but it's overkill for your purposes. It reads over my source files, makes a list of classes, their members, their functions, etc. which is then used to generate new code. Two main options: GCC-XML can generate a list of classes, members, and functions. The distribution version on their web site is quite old; try the CVS version instead. I don't know about the availability of a Windows port. Doxygen is designed for producing documentation, but it can also produce an XML output, which you should be able to use to do what you want. Currently I just use it to make it easy to read and write my data structures to a plain text file... This is known as serialization. Try Boost.Serialization or maybe libs11n or Google Protocol Buffers. Stack Overflow has further discussion. ...but I could do other things as well. Other cool applications of this kind of automatic code generation include reflection (inspecting your objects' members at runtime, using duck typing with C++, etc.) and generating wrappers for calling C++ from scripting languages. For a C++ reflection library, see Reflex. For an example of generating wrappers for scripting languages, see Boost.Python or SWIG.
1,456,706
1,456,972
Error linking with 3rd party static library built with previous version of Visual Studio
I am working on a project that links to a 3rd party static library (herin refered to as EXTERNALLIB). In Visual Studio 2005 I was able to link to EXTERNALLIB and create a usable executable. Now we are using Visual Studio 2008 and I am receiving the following error: fatal error C1047: The object or library file EXTERNALLIB was created with an older compiler than other objects; rebuild old objects and libraries. Is there a way for me to tell the compiler to correctly link to EXTERNALLIB? I believe the problem may be related to specific calling conventions (__stdcall, __cdecl, __clrcall, __thiscall). Can I indicate in the new program the correct calling convention for the old library? Is there specific feedback that I can give to our vendor (such as using APIENTRY in the header files) such that this problem does not occur with future compiler upgrades? The code is writen in C++. I do not have access to the code for EXTERNALLIB and thus I am unable to rebuild it myself.
You problem is likely to result from "the code is written in C++". The ABI for C++ linkage is essentially completely unspecified by any standard, and is notoriously changeable from compiler to compiler. I suspect that VS is trying to tell you that the ABI has changed again, and that as a result it cannot link directly to the library. This problem is often exacerbated by wanting to implement C++ objects in a DLL, but luckily you don't have that problem here. One approach to a solution that should work is to skin the published API of EXTERNALLIB with a C-callable adaptor, and to link that whole thing into a DLL. Build the skin with the older VS version (at worst, the free edition should still be findable). Make sure that only extern "C" functions are exposed. Especially make sure that no global objects are exposed from the DLL (although they may need to exist within your skin). The best answer is go back to the supplier of EXTERNALLIB and politely report the failure to link with the current VS as a bug and request a rebuilt version.
1,456,840
1,456,850
Why is it called 'wchar_t' and not simply 'wchar'?
I've often wondered why C++ went with the name wchar_t instead of simply wchar, and I've never been able to find an answer. Search engines are no help because they think I'm asking about Windows' WCHAR type. Any ideas?
That's a legacy from C, where wchar_t is a typedef, and typedefs have that suffix in the C Standard Library.
1,457,184
1,462,498
MouseProc hook and WM_LBUTTONDBLCLK
I have a hook setup for getting mouse events in a plugin I develop. I need to get the WM_LBUTTONDBLCLK, and I expect the message flow to be: WM_LBUTTONDOWN, WM_LBUTTONUP, WM_LBUTTONDBLCLK If I call the next hook when dealing with the first WM_LBUTTONDOWN, then the flow is as expected. However, if I return my own result, then the expected double click comes as a mouse down message. Any idea why this is happening? I need the message to stop after I handle it, and not have it passed to the next hook.
After having done a little reading over at the MSDN, I think the explanation of this behaviour lies in this remark on the WM_LBUTTONDBLCLK page: Only windows that have the CS_DBLCLKS style can receive WM_LBUTTONDBLCLK messages, which the system generates whenever the user presses, releases, and again presses the left mouse button within the system's double-click time limit. If your program is returning a nonzero value when it handles WM_LBUTTONDOWN or WM_LBUTTONUP, then those messages aren't sent to the target window -- as expected. However, my inference, based on the above quote, is that since no window with the CS_DBLCLKS style is therefore receiving the messages (since the hook prevents any window from receiving the messages), the system therefore doesn't feel like it needs to generate a WM_LBUTTONDBLCLK. To put it another way, the system only generates a WM_LBUTTONDBLCLK if and only if (a) a window receives the previous WM_LBUTTONDOWN/WM_LBUTTONUP messages and (b) that window has the CS_DBLCLKS style. Since your hook prevents condition (a) from being satisfied, WM_LBUTTONDBLCLK is never generated and so a WM_LBUTTONDOWN message is sent instead. As to a workaround, I doubt there's a perfect solution. I assume the reason why you want to receive the WM_LBUTTONDBLCLK message is so your hook knows whether or not a regular WM_LBUTTONDOWN message represents the second click of a double-click, right? In that case, what you could do is read the double-click time from the registry as Faisal suggests and have your hook measure the time between WM_LBUTTONDOWN messages, however there's a large chance that you will get inaccurate results (due to the lag time between the messages being sent). Alternatively if there's some way you could instead redirect the WM_LBUTTONDOWN/WM_LBUTTONUP messages to maybe a hidden window that your hook owns (which has the CS_DBLCLKS style), the system may end up generating a WM_LBUTTONDBLCLK message and sending it to your hidden window, which you can then process in that window's WndProc (though I don't have a lot of experience with hooking so I don't know if this is possible).
1,457,319
1,457,483
Trying to choose SQL API library
I am just beginning to learn how to write software that accesses an SQL server. It seems that each server implementation (Postgres, MySQL, etc.) offers API libraries for various languages (my code is in C and C++, though solutions for Java and Python would also interest me). I'm a little wary of depending on these libraries, however, because I'd prefer a vendor-neutral solution. As near as I can tell, Microsoft's ODBC API was meant to solve such problems for C/C++ (and JDBC for Java); unixODBC seems to be one popular implementation. Am I right even so far? Moreover, do any such libraries provide an object-oriented interface? It would be nice to not simply embed SQL queries into another, more featureful language; I'd like to have a wrapper that mimics the style of the rest of the language, too. So is there a preferred solution along those lines? Am I asking for something weird?
Indeed, ODBC/JDBC are libraries that help make the calling interface standard between vendors, but you're right that each respective RDBMS has its own flavor of SQL. ODBC/JDBC doesn't help abstract the SQL syntax. One solution to move literal SQL out of your application code is to implement queries in stored procedures that reside in each database back-end, and then use ODBC/JDBC to call the stored procedures. You can define stored procedures with similar names and calling interface for each flavor of RDBMS you use. But be aware that the stored procedure language is also variable from one vendor to the next. Another solution is to use an "object-relational mapping" technology such as Hibernate for Java, or NHibernate for .NET. These technologies can make it feel more "object-oriented" to work with databases, and free you from writing literal SQL in many cases. But most ORM tools tends to focus on very simple queries. If your query is at all complex (using a GROUP BY or a JOIN for instance), using the ORM tool is harder than using literal SQL. See also "Good ORM for C++ solutions?" If SQL troubles you that much, you're probably not going to be happy using an RDBMS at all. Some programmers don't see the value to the Rules of Normalization, for instance. If that's true for you, you might want to look into the emerging technologies for non-relational data stores, including: BerkeleyDB Project Voldemort CouchDB
1,457,431
1,457,545
C/C++: Size of builtin types for various compilers/platforms
Where can I go to get information about the size of, say, unsigned int compiling under gcc for Mac OS X (both 32 and 64 bits)? In general I'd love to have a resource I can go to with a compiler/settings/platform/type and be able to look up how big that type will be. Does anyone know of such a thing? Update: Thanks for all the responses. I was hoping to have something more along the lines of a static table somewhere instead of a piece of code I'd have to write and run on every machine.
If you can't write a program to find out, you should consult the ABI (Application Binary Interface) specification for the compiler/platform. It should document the sizes, alignments, endianness, etc. of the basic primitive types supported.
1,457,669
1,457,675
C++ Dynamic Array Access Violation
**** Sorry for the confusion regarding numCars in the original post. I modified the code to be consistent with the original ****** The following academic program is a simplified version of the original problem but it focuses on the issue that I have yet to resolve. There are 2 classes and a main method to this problem and the 2 classes consist of a Dealer class and a Car class. The Dealer class has a private Car* pointer that is initialized to a dynamic array in the Dealer's constructor. The error occurs in the main method when the Dealer's addCar method is invoked. In the main method I intentionally pass the Dealer variable to the addCar(Dealer& d) method to mimic the structure of the original application. The addCar method then invokes the Dealer's addCar(const Car& car) method where the access violation occurs when I execute cars[numCars++]=car; Can you explain why cars[numCars++]=car results in an access violation /**********************************Dealer.h**************************/ #include &lt;cstdlib&gt; #include "Car.h" using namespace std; class Dealer { public: Dealer(int maxCars = DEFAULT_MAX_CARS) :numCars(0) {cars = new Car[maxCars];} ~Dealer(){delete [] cars;} int getTotalCars() const { return numCars;} void addCar(const Car& car) { cars[numCars++] = car; // Access Violation } Car* begin(){return cars;}; Car* end(){ return cars + numCars;} setNumCars(int count){numCars = count;} private: static const int DEFAULT_MAX_CARS = 10; Car* cars; int numCars; }; /**********************************Car.h**********************/ #include &lt;cstdlib&gt; #include &lt;string&gt; using namespace std; class Car{ public: Car() : year(0), make(""), model("") {} Car(int year, string make, string model) : year(year), make(make), model(model) {} string getMake() const {return make;} void setMake(string make){this->make=make;} string getModel() const {return model;} void setModel(string model){this->model=model;} int getYear() const {return year;} void setYear(int year){this->year=year;} private: int year; string make; string model; }; ostream& operator<< (ostream& out, const Car& car) { out << car.getYear() << " " << car.getMake() << " " << car.getModel(); return out; } /**********************************Main.cpp**********************/ #include &lt;cstdlib&gt; #include &lt;iostream&gt; #include "Dealer.h" using namespace std; void addCar(Dealer& d); int main(int argc, char *argv[]) { Dealer d; addCar(d); system("PAUSE"); return EXIT_SUCCESS; } void addCar(Dealer& d) { d = Dealer(); d.addCar(Car(2007, "Honda", "Civic")); cout << d.getTotalCars() << " total cars" << endl; }
void addCar(const Car& car) { cars[numCars++] = car; // Access Violation } You never initialize numCars - it contains some value from the heap which is almost definitely non-zero. This causes you to read beyond the end of the cars array and into inaccessible memory. You should set numCars to 0 in your constructor. On top of this, you should have some checks in addCar so that you don't overrun the cars array. EDIT: There are some other issues with the code - for instance, "d = Dealer();" creates a new Dealer and overwrites the one you pass by reference to addCars which doesn't seem to be what you want to do. Try adding some additional tracing to the constructor/destructors to verify that the constructors you think are being called actually are - it appears that Dealer() should be invoking the constructor with a default argument you specified, but if not it is getting the default constructor.
1,457,842
1,457,873
Is this good code? (copy constructor and assignment operator )
For one reason or another, I'm forced to provide both a copy constructor and an operator= for my class. I thought I didn't need operator= if I defined a copy ctor, but QList wants one. Putting that aside, I hate code duplication, so is there anything wrong with doing it this way? Fixture::Fixture(const Fixture& f) { *this = f; } Fixture& Fixture::operator=(const Fixture& f) { m_shape = f.m_shape; m_friction = f.m_friction; m_restitution = f.m_restitution; m_density = f.m_density; m_isSensor = f.m_isSensor; return *this; } And just out of curiosity, there's no way to switch it so that the bulk of the code is in the copy ctor and operator= somehow utilizes it? I tried return Fixture(f); but it didn't like that. It appears I need to make it more clear that the copy constructor and assignment operator have been implicitly disabled by the class I am inheriting from. Why? Because it's an abstract base class that shouldn't be instantiated on its own. This class, however, is meant to stand alone.
This is bad, because the operator= can't rely on a set-up object anymore. You should do it the other way around, and can use the copy-swap idiom. In the case where you just have to copy over all elements, you can use the implicitly generated assignment operator. In other cases, you will have to do something in addition, mostly freeing and copying memory. This is where the copy-swap idiom is good for. Not only is it elegant, but it also provide so an assignment doesn't throw exceptions if it only swaps primitives. Let's a class pointing to a buffer that you need to copy: Fixture::Fixture():m_data(), m_size() { } Fixture::Fixture(const Fixture& f) { m_data = new item[f.size()]; m_size = f.size(); std::copy(f.data(), f.data() + f.size(), m_data); } Fixture::~Fixture() { delete[] m_data; } // note: the parameter is already the copy we would // need to create anyway. Fixture& Fixture::operator=(Fixture f) { this->swap(f); return *this; } // efficient swap - exchanging pointers. void Fixture::swap(Fixture &f) { using std::swap; swap(m_data, f.m_data); swap(m_size, f.m_size); } // keep this in Fixture's namespace. Code doing swap(a, b) // on two Fixtures will end up calling it. void swap(Fixture &a, Fixture &b) { a.swap(b); } That's how i write the assignment operator usually. Read Want speed? Pass by value about the unusual assignment operator signature (pass by value).
1,458,180
1,458,182
vtable for .. referenced from compile error xcode
I was getting the following error compiling an iPhone project: "vtable for oned::MultiFormatUPCEANReader", referenced from: __ZTVN4oned23MultiFormatUPCEANReaderE$non_lazy_ptr in MultiFormatUPCEANReader.o ld: symbol(s) not found collect2: ld returned 1 exit status Anybody know how I may fix it?
The problem seemed to be that in the class MultiFormatUPCEANReader I had declared a constructor and destructor, but had not written a body for the destructor, this was causing this annoying problem. Hope this helps somebody solve their compile error. This is a terrible compiler error with little information!
1,459,001
1,459,062
In C++, passing a pointer still copies the object?
I've been reading for an hour now and still don't get what is going on with my application. Since I am using instances of object with new and delete, I need to manage the memory myself. My application needs to have long uptimes and therefore properly managing the memory consumption is very crucial for me. Here's the static function I use to dump the datapacket, which is transfered between a PC and the I/O board in both directions. The datapacket is an array of BYTEs and is encapsulated into an object, either DCCmd or DCReply (both are implementation of an abstract DCMessage class). void DebugTools::dumpBytes(BYTE* bytes, short length) { printf(" |---DUMPING DATAPACKET refId: %d ....\n", &bytes); for(short i=0; i<length; i++){ printf(" | B%d | %.2X\n", i, bytes[i]); } printf(" |---END DUMP refId: %d ....\n", &bytes); } Then there's this use case: I create a DCCmd object and add it to the outgoing message queue to be sent. The "pump" (an infinite loop) checks the outbox and passes any candidates to a IOConnector singleton object. DCCmd* cmd = new DCCmd(DIG_CMD_SELFTEST_RES); cmd->add(param); printf("cmdSelfTest()\n"); //HACK BYTE* cmda = cmd->getBytes(); //HACK DebugTools::dumpBytes(cmda, cmd->getLength()); //HACK sendMsg(cmd); ... and adding to the queue: bool DC::sendMsg(DCMessage* msg) { if(isOnline()){ outbox->add(msg); return true; } else { return false; } } Adding to the queue is done with void add(DCMessage* msg); (In the connector class there's another of those dumpBytes() to see what is really going to be sent) But here's the output: TESTING MESSAGE QUEUES .... cmdSelfTest() |---DUMPING DATAPACKET refId: 2489136 .... | B0 | C6 | B1 | A1 | B2 | 00 | B3 | 01 | B4 | 10 | B5 | 00 | B6 | 01 | B7 | 78 |---END DUMP refId: 2489136 .... adding to queue: 2488884 queues: inbox (0), outbox (1) send: sending candidates.... sending 2489164 .... >->-> ... |---DUMPING DATAPACKET refId: 2488704 .... | B0 | C6 | B1 | A1 | B2 | 00 | B3 | 01 | B4 | 10 | B5 | 00 | B6 | 01 | B7 | 78 |---END DUMP refId: 2488704 .... Packet sent! . ((second iteration of the pump)) queues: inbox (0), outbox (1) send: sending candidates.... sending 2489164 .... >->-> ... |---DUMPING DATAPACKET refId: 2488704 .... | B0 | C6 | B1 | A1 | B2 | 00 | B3 | 01 | B4 | 10 | B5 | 00 | B6 | 01 | B7 | 78 |---END DUMP refId: 2488704 .... Packet sent! Can someone please shed some light why the references are different each time I pass from one block to the other? What does this mean to the memory consumption? How can I make sure I am not duplicating memory? Thanks.
The variable bytes is the pointer to the data, i.e. the memory location of the data. But that is not what you are printing, you are printing out the address where this pointer is located, i.e. the address on the stack where the pointer is passed. So printf(" |---DUMPING DATAPACKET refId: %d ....\n", &bytes); should just be printf(" |---DUMPING DATAPACKET refId: %d ....\n", bytes);
1,459,045
1,461,225
Combining Bitmaps / ImageLists (Win32)
Is it possible to create an image list from multiple bitmaps, or to combine multiple image lists into one. For sake of simplicity, same element dimensions and transparent color could be assumed. Reason: I am currently dealing with a very long image list containing four groups of icons and notable "reserved" areas between them. For editing it would be easier to split into four bitmaps, combine them on the fly and calculate icon indices dynamically.
ImageList_Add can add a bitmap with several images to an existing image list. Is that what you're looking for?
1,459,257
1,459,423
C++ and Smart Pointers - how would smart pointers help in this situation?
Much to my shame, I haven't had the chance to use smart pointers in actual development (the supervisior deems it too 'complex' and a waste of time). However, I planned to use them for my own stuff... I have situations regarding de-initing a module after they are done, or when new data is loaded in. As I am using pointers, I find my code littered with check for null such as this... // TODO: Reset all opened windows // Deinit track result player if (trackResultPlayer_) trackResultPlayer_->reset(); // disconnect track result player disconnect(trackResultPlayer_); disconnect(trackResultAnimator_); } if (videoPlayerWindow_) { videoPlayerWindow_->reset(); // Disconnect the video player window from source movie data disconnect(videoPlayerWindow_); } // Disconnect this module from its children as they would be connected again disconnect(this); If I am to use smart pointers, instead of raw pointers, how could this problem be alleviated?
Make each of your classes implement a destructor which performs all the cleanup/deinitialization you need for that class. Create an instance of the class, and wrap it in a boost::shared_ptr. Then pass copies of that to every function which needs access to the instance. And the smart pointer will ensure that once the object is no longer used (when all the shared pointers have been destroyed), the object they point to is destroyed. its destructor is run, and all the cleanup is executed. As always in C++, use RAII whenever possible. Whenever you have code like x.reset() or disconnect(x), the first thing you should do is ask yourself "doesn't this belong in a destructor?" Further, whenever you use x->y() you should ask yourself: Why is this a pointer? Couldn't I make do with a single instance allocated on the stack, and perhaps a few references to it? If it has to be a pointer, why isn't it a smart pointer?
1,459,344
1,459,376
Qt and serial port programming
Is there any serial port facilities in Qt ? If not, which crossplatform (desirable) libraries (for working with serial port and, maybe, with other I/O ports), do you recommend ?
Take a look at the Project QextSerialPort.
1,459,443
1,459,450
output a list of functions called by a source file
Is there a flag I can set so that the compiler (linker?) will output a list of all the functions called by (not just defined in) each separate source file during the compilation(linking) process? Thanks,
I don't know if VS can do that, but you can use doxygen to generate a call graph for each function.
1,459,808
1,460,042
Global (process wide) properties in Win32
I am trying to share some data across DLLs in a project which has an extremely complicated dependency structure (numberous DLLs). I want to be able to associate a key with some data in one part of the application, and then extract that data by supplying the appropriate key in some other part of the app. In a way, one can say that I looking for something that is similar to Java's System.setProperty()/getProperty(). I was sure that the Process APIs would give me some access to a process-wide buffer, but I had no luck. Any ideas? (I know that the clean solution is to introduce a new DLL and to link it properly to the existing DLLs. Unfortunately, this type of solution is beyond the mandate of my team).
To be clear here there is one exe with multiple DLL's in only one process but multiple modules. So you aren't looking for inter-process communications. In answer I see two strategies: use Windows API atoms which are slightly limited (basically only string data) which can work within or between processes. If you write a DLL which contains your speculated SetProperty/getproperty functionality you don't have to compile ALL the other DLL's again (which is presumably what is beyond your team's specification) - you only need to recompile those DLL's which are currently using your new features (set/getproperty) (which is presumably within your teams power). So this seems a direct and powerful solution.
1,459,865
1,463,215
IWebBrowser2 issues - how to open documents in new windows?
I have IWebBrowser2 ctrl embedded into my own dialog. I want to simply display a promo banner within it from my url. How to disable all popup menu items from the control and force it to open links in new window (currently when I click on link in the banner, it is being opened within the same control). Regards Dominik
Have a look at the following article: WebBrowser Customization
1,460,007
1,460,097
WAV file from captured PCM sample data
I have several Gb of sample data captured 'in-the-field' at 48ksps using an NI Data Acquisition module. I would like to create a WAV file from this data. I have done this previously using MATLAB to load the data, normalise it to the 16bit PCM range, and then write it out as a WAV file. However MATLAB baulks at the file size as it does everything 'in-memory'. I would ideally do this in C++ or C, (C# is an option), or if there is an existing utility I'd use that. Is there a simple way (i.e. an existing library) to take a raw PCM buffer, specify the sample rate, bit depth, and package it into a WAV file? To handle the large data set, it would need to be able to append data in chunks as it would not necessarily be possible to read the whole set into memory. I understand that I could do this from scratch using the format specification, but I do not want to re-invent the wheel, or spend time fixing bugs on this if I can help it.
I think you can use libsox for this.
1,460,010
1,479,465
Best C++ RTP/RTSP library
I'm looking for a RTP/RTSP library in C++. I found pjsip but it is more C-style. I'm looking for more OO library.
JRTPLIB is very nice, and used in well-known projects such as SightSpeed (and lots of little ones). Pretty well-designed, very flexible license; pretty easy to get things right with it.
1,460,185
1,470,028
Use Pantheios logging framework from a dll
Im a trying to use pantheios logging framework from inside a c++ dll. I have successfully built the dll and it executes through my test application (C++ MFC Application). I have used implicit linking with the following includes: #include <pantheios/implicit_link/core.h> #include <pantheios/implicit_link/fe.simple.h> #include <pantheios/implicit_link/be.console.h> My DllMain initializes pantheios with the following calls: extern "C" const char PANTHEIOS_FE_PROCESS_IDENTITY[] = "FinishingLineController"; BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { int panres = pantheios::pantheios_init(); if(panres < 0) { fprintf(stderr, "Failed to initialise the Pantheios libraries: %s\n", pantheios::pantheios_getInitErrorString(panres)); return FALSE; } } break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: pantheios::pantheios_uninit(); break; } return TRUE; } When I execute the following code I get an Microsoft C++ exception: stlsoft::winstl_project::windows_exception at memory location 0x0013da84 pantheios::log_DEBUG("Test logging"); I have tried to use explicit linking instead without any result.
Some further tests showed that the logging from the dll works if I link it to a console application instead of a windows application. And if I change the backend to "file" instead of "console" the windows application do log correctly to the file. So the problem seem to be that the windows application doesn't have a "console". The solution was to redirect standard output/input pipes to a new console. This has to be done for a win32 application since a console is not created by default. void RedirectIOToConsole() { int hConHandle; long lStdHandle; CONSOLE_SCREEN_BUFFER_INFO coninfo; FILE *fp; // allocate a console for this app AllocConsole(); // set the screen buffer to be big enough to let us scroll text GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo); coninfo.dwSize.Y = MAX_CONSOLE_LINES; SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize); // redirect unbuffered STDOUT to the console lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w" ); *stdout = *fp; setvbuf( stdout, NULL, _IONBF, 0 ); // redirect unbuffered STDIN to the console lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "r" ); *stdin = *fp; setvbuf( stdin, NULL, _IONBF, 0 ); // redirect unbuffered STDERR to the console lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w" ); *stderr = *fp; setvbuf( stderr, NULL, _IONBF, 0 ); // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog // point to console as well std::ios::sync_with_stdio(); } And then call this function from DllMain. BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: { RedirectIOToConsole(); int panres = pantheios::pantheios_init(); if(panres < 0) { fprintf(stderr, "Failed to initialise the Pantheios libraries: %s\n", pantheios::pantheios_getInitErrorString(panres)); return FALSE; } // Set the file name for all back-ends. //pantheios_be_file_setFilePath("output.log"); } break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: pantheios::pantheios_uninit(); break; } return TRUE; }
1,460,361
1,460,372
How to set application icon in a Qt-based project?
How do you set application icon for application made using Qt? Is there some easy way? It's a qmake-based project.
For Qt 5, this process is automated by qmake. Just add the following to the project file: win32:RC_ICONS += your_icon.ico The automated resource file generation also uses the values of the following qmake variables: VERSION, QMAKE_TARGET_COMPANY, QMAKE_TARGET_DESCRIPTION, QMAKE_TARGET_COPYRIGHT, QMAKE_TARGET_PRODUCT, RC_LANG, RC_CODEPAGE. For Qt 4, you need to do it manually. On Windows, you need to create a .rc file and add it to your project (.pro). The RC file should look like this: IDI_ICON1 ICON DISCARDABLE "path_to_you_icon.ico" The .pro entry should also be win32 specific, e.g.: win32:RC_FILE += MyApplication.rc
1,460,377
1,460,416
How to detect an overflow in C++?
I just wonder if there is some convenient way to detect if overflow happens to any variable of any default data type used in a C++ program during runtime? By convenient, I mean no need to write code to follow each variable if it is in the range of its data type every time its value changes. Or if it is impossible to achieve this, how would you do? For example, float f1=FLT_MAX+1; cout << f1 << endl; doesn't give any error or warning in either compilation with "gcc -W -Wall" or running. Thanks and regards!
Consider using boosts numeric conversion which gives you negative_overflow and positive_overflow exceptions (examples).
1,460,703
2,797,990
Comparison of arrays in google test?
I am looking to compare two arrays in google test. In UnitTest++ this is done through CHECK_ARRAY_EQUAL. How do you do it in google test?
I would really suggest looking at Google C++ Mocking Framework. Even if you don't want to mock anything, it allows you to write rather complicated assertions with ease. For example //checks that vector v is {5, 10, 15} ASSERT_THAT(v, ElementsAre(5, 10, 15)); //checks that map m only have elements 1 => 10, 2 => 20 ASSERT_THAT(m, ElementsAre(Pair(1, 10), Pair(2, 20))); //checks that in vector v all the elements are greater than 10 and less than 20 ASSERT_THAT(v, Each(AllOf(Gt(10), Lt(20)))); //checks that vector v consist of // 5, number greater than 10, anything. ASSERT_THAT(v, ElementsAre(5, Gt(10), _)); There's plenty of matchers for every possible situations, and you can combine them to achieve almost anything. Did I tell you that ElementsAre needs only iterators and size() method on a class to work? So it not only works with any container from STL but with custom containers also. Google Mock claims to be almost as portable as Google Test and frankly I don't see why you wouldn't use it. It is just purely awesome.
1,460,719
1,460,815
determine value range of template type in C++
In a template function, I like to determine the range for the value of its template type. For specific type, like int, INT_MAX and INT_MIN are what I want. But how to do the same for a template type? Thanks and regards!
For numeric types, you can use the std::numeric_limits class template in the <limits> header.
1,460,863
1,463,072
Windows Mobile Sockets SSL Communication library
I have a Win32 application that uses boost::asio and openssl library but it seems that they are not supported under WM, am I correct? Can anyone suggest WM API/library for WM Sockets, I need to connect to a server through SSL connection. Is the only option for me WinSocks + OpenSSL?
While I don't know of any other libraries for WM that provide socket and ssl connectivity, I can confirm that sockets and OpenSSL do work fine on WM5 and above devices. You have to jump through a few hoops to get openssl built for wm5 and ARM, as there are some parts of the c runtime missing, these are plugged with this Also this post was useful, as you have to build it on the command line, rather than in visual studio.
1,460,936
1,461,008
Why STL implementation is so unreadable? How C++ could have been improved here?
For instance why does most members in STL implementation have _M_ or _ or __ prefix? Why there is so much boilerplate code ? What features C++ is lacking that would allow make vector (for instance) implementation clear and more concise?
Implementations use names starting with an underscore followed by an uppercase letter or two underscores to avoid conflicts with user-defined macros. Such names are reserved in C++. For example, one could define a macro called Type and then #include <vector>. If vector implementations used Type as a template parameter name, it would break. However, one is not allowed to define macros called _Type (or __type, type__ etc.). Therefore, vector can safely use such names.
1,460,949
1,461,046
C++ logical operators return value
Here is some code I'm writing in C++. There's a call to an addAVP() function dMessage.addAVP(AVP_DESTINATION_HOST, peer->getDestinationHost() || peer->getHost()); which has two versions: one overloaded in the second parameter to addAVP(int, char*) and another to addAVP(int, int). I find the C++ compiler I use calls the addAVP(int, int) version which is not what I wanted since getDestinationHost() and getHost() both return char*. Nonetheless the || operator is defined to return bool so I can see where my error is. Bool somehow counts as an integer and this compiles cleanly and calls the second addAVP(). Lately I'm using a lot of dynamically typed languages, i.e. lisp, where the above code is correct can be written without worries. Clearly, clearly the above code in C++ is a big error, but still have some questions: Should I be using this kind of shortcut, i.e. using the ||-operator's return value, at all in C++. Is this compiler dependent? Imagine that I really, really had to write the nice a || b syntax, could this be done cleanly in C++? By writing an operator redefinition? Without losing performance? As a followup to my original request, or my own answer to 2 :-) I was thinking along the lines of using a class to encapsulate the (evil?) rawpointer: class char_ptr_w { const char* wrapped_; public: char_ptr_w(const char* wrapped) : wrapped_(wrapped) {} char_ptr_w(char_ptr_w const& orig) { wrapped_=orig.wrapped(); } ~char_ptr_w() {} inline const char* wrapped() const { return wrapped_; } }; inline char_ptr_w operator||(char_ptr_w &lhs, char_ptr_w& rhs) { if (lhs.wrapped() != NULL) return char_ptr_w(lhs.wrapped()); else return char_ptr_w(rhs.wrapped()); }; Then I could use: char_ptr_w a(getDestinationHost()); char_ptr_w b(getHost()); addAVP(AVP_DESTINATION_HOST, a || b); In which this addAVP would be overloaded for char_ptr_w. According to my tests, this generates at most the same assembly code as ternary a?b:c solution, particularly because of the NRVO optimization in the operator, which does not, in most compilers, call the copy-constructor (although you have to include it). Naturally, in this particular example I agree that the ternary solution is the best. I also agree that operator redefinition is something to be taken with care, and not always beneficial. But is there anything conceptually wrong, in a C++ sense, with the above solution?
It is legal in C++ to overload the logic operators, but only if one or both of the arguments are of a class type, and anyway it's a very bad idea. Overloaded logic operators do not short circuit, so this may cause apparently valid code elsewhere in your program to crash. return p && p->q; // this can't possibly dereference a null pointer... can it?
1,461,064
1,461,071
Are member variables of an object that is on the heap also automatically on the heap?
class A { public: A(); ~A(); int X; }; A::A() { X = 5; int Y = 4; } //..... in another file A * objectOnHeap = new A(); In this case, since "objectOnHeap" is on the heap, is X also on the heap even though it wasn't specifically new'd up? And in this case Y is allocated on the stack (and of course goes out of scope), correct? I am wondering if I have gotten my wires crossed when trying to envision how objects are stored in memory.
Yes. It's on the heap. Basically, the space allocated to an object on the heap is big enough to hold all its member variables.
1,461,145
1,461,213
Where can I find source of unhook function used in STL implementation provided with g++
It is used in /usr/include/c++/4.3/stl_list.h on my system (current Ubuntu).
http://gcc.gnu.org/ Have a look at the Download or "Live" Sources sections.
1,461,276
1,461,294
std::vector reserve() and push_back() is faster than resize() and array index, why?
I was doing a quick performance test on a block of code void ConvertToFloat( const std::vector< short >& audioBlock, std::vector< float >& out ) { const float rcpShortMax = 1.0f / (float)SHRT_MAX; out.resize( audioBlock.size() ); for( size_t i = 0; i < audioBlock.size(); i++ ) { out[i] = (float)audioBlock[i] * rcpShortMax; } } I was happy with the speed up over the original very naive implementation it takes just over 1 msec to process 65536 audio samples. However just for fun I tried the following void ConvertToFloat( const std::vector< short >& audioBlock, std::vector< float >& out ) { const float rcpShortMax = 1.0f / (float)SHRT_MAX; out.reserve( audioBlock.size() ); for( size_t i = 0; i < audioBlock.size(); i++ ) { out.push_back( (float)audioBlock[i] * rcpShortMax ); } } Now I fully expected this to give exactly the same performance as the original code. However suddenly the loop is now taking 900usec (i.e. it's 100usec faster than the other implementation). Can anyone explain why this would give better performance? Does resize() initialize the newly allocated vector where reserve just allocates but does not construct? This is the only thing I can think of. PS this was tested on a single core 2Ghz AMD Turion 64 ML-37.
Does resize initialize the newly allocated vector where reserve just allocates but does not construct? Yes.
1,461,331
1,469,750
Writing my own shell... stuck on pipes?
For the past few days I have been attempting to write my own shell implementation but I seem to have gotten stuck on getting pipes to work properly. I am able to parse a line and fork off the commands between the pipes (ex: ls | sort) individually but can't seem to get them to pipe input from one into the other. I think I just don't understand how to use dup2() and pipes properly. I've now included my code which is still failing... :( So stuck... void forkAndExecute( char* arrayOfWords[] , vector<pid_t> *vectorOfPIDs , bool hasNextCmd , bool hasPrevCmd) { int fd[ 2 ]; pid_t pid; if( hasNextCmd ){ pipe(fd); } pid = fork(); //error if PID < 0 if( pid < 0 ) { cerr << ">>> fork failed >>>" << endl; exit(-1); } //child process if PID == 0 else if( pid == 0 ) { if ( hasPrevCmd ){ dup2(fd[0] , 0); close(fd[0]); close(fd[1]); } if ( hasNextCmd ){ dup2(fd[1],1); close(fd[0]); close(fd[1]); } execvp( arrayOfWords[0] , arrayOfWords ); cout << ">>> command not found >>>" << endl; //if logic reaches here, exec failed exit(0); } //parent process else{ close(fd[0]); close(fd[1]); //if( ! isLastCmd ){ //} vectorOfPIDs->push_back(pid); } }
First suggestion: Symbolic constants are better than magic numbers. const int PIPE_READ = 0; const int PIPE_WRITE = 1; int fd[2]; pipe(fd); // Now you can refer to fd[PIPE_READ] and fd[PIPE_WRITE]. Second suggestion: Take a step back and think about what you're trying to accomplish. You want to spawn two processes, with the first process's stdout connected to the second process's stdin. Right? So, in C, this means that you need to take call pipe, pass fd[PIPE_WRITE] to the first child process, which will dup2 it to 1, and pass fd[PIPE_READ] to the second child process, which will dup2 it to 0. Simply looking at forkAndExecute's prototype shows that it can't do that: void forkAndExecute( char* arrayOfWords[] , vector *vectorOfPIDs , bool hasNextCmd , bool hasPrevCmd); It only handles a single command, and from looking at that argument list, unless it resorts to evil global variables, there's no way for it to receive a file descriptor from its PrevCmd or receive a file descriptor from its NextCmd. Think about how to manage the file descriptors that you need, and redesign forkAndExecute to be able to use these.
1,461,340
1,461,358
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Rectangle' (or there is no acceptable conversion)
I'm required to write a function to overload the ==operator to compare width, height and colour. I need to return 'Y' if its equal and 'N' if its not. This is my code which I think is correct, but keeps giving me the error: error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Rectangle' (or there is no acceptable conversion) I've searched for an answer and nothing came close to comparing 3 data as most examples are for comparing 2 datas. #include <iostream> #include <string> using namespace std; class Rectangle { private: float width; float height; char colour; public: Rectangle() { width=2; height=1; colour='Y'; } ~Rectangle(){} float getWidth() { return width; } float getHeight() { return height; } char getColour() { return colour; } Rectangle(float newWidth, float newHeight, char newColour) { width = newWidth; height = newHeight; colour = newColour; } char operator== (const Rectangle& p1){ if ((width==p1.width) && (height==p1.height) && (colour==p1.colour)) return 'Y'; else return 'N'; } }; int main(int argc, char* argv[]) { Rectangle rectA; Rectangle rectB(1,2,'R'); Rectangle rectC(3,4,'B'); cout << "width and height of rectangle A is := " << rectA.getWidth() << ", " << rectA.getHeight() << endl; cout << "Are B and C equal? Ans: " << rectB==rectC << endl; return 0; }
"<<" is higher precedence than "==". Put your comparison in parentheses: cout << "Are B and C equal? Ans: " << (rectB == rectC) << endl;
1,461,432
1,461,449
What is array to pointer decay?
What is array to pointer decay? Is there any relation to array pointers?
It's said that arrays "decay" into pointers. A C++ array declared as int numbers [5] cannot be re-pointed, i.e. you can't say numbers = 0x5a5aff23. More importantly the term decay signifies loss of type and dimension; numbers decay into int* by losing the dimension information (count 5) and the type is not int [5] any more. Look here for cases where the decay doesn't happen. If you're passing an array by value, what you're really doing is copying a pointer - a pointer to the array's first element is copied to the parameter (whose type should also be a pointer the array element's type). This works due to array's decaying nature; once decayed, sizeof no longer gives the complete array's size, because it essentially becomes a pointer. This is why it's preferred (among other reasons) to pass by reference or pointer. Three ways to pass in an array1: void by_value(const T* array) // const T array[] means the same void by_pointer(const T (*array)[U]) void by_reference(const T (&array)[U]) The last two will give proper sizeof info, while the first one won't since the array argument has decayed to be assigned to the parameter. 1 The constant U should be known at compile-time.
1,461,805
1,461,843
How can I compare similar codebases?
We have several C++ projects that were built from the same codebase. There's a lot of similarities and common code between them but they were developed independently; source was not shared in any way. Classes and files will have been renamed even if the underlying code hasn't changed and individual lines will have been tweaked, changed and replaced. I'd like to be able to compare the different codebases and find out how much of the code is still the same. It can be fairly high level - % of code that is the same is fine. I also need to be able to automate this process. Is there a tool that I can run on the codebases and get some sort of report/assessment of how much is common?
I don't have much experience with this sort of thing, but it made me think back to my school days when our University would run everyones code through a program to find cheaters. This brought me to the following link: Source Code Similarity Detection It names some open source and commercial software that should meet your needs.
1,461,832
1,461,938
overloading operator<< for use with ostream
I am using CPPUnit to test a class in my program. This class (SCriterionVal) is somewhat unique because it has conversion operators for a lot of types (it's essentially a dynamic type value class). When I compile test cases that test it using CPPUNIT_ASSERT_EQUAL(), I get compilation errors about "operator<< is ambiguous" from one of the CPPUnit header files. It appears that it is instantiating the assertion_traits struct with my type, and that struct has a toString() method that works by using operator<< on an OStringStream. I assume it's ambiguous instead of an error because of the various conversions available on SCriterionVal, some of which have defined operator<< (such as the built in types). In an attempt to rectify this situation, I created a non-member function in the header for SCriterionVal with this signature: ostream &operator<<(ostream &stream, SCriterionVal val); I figured because the signature should be an exact match, it will resolve the ambiguity. No such luck. What am I doing wrong here? I suppose I can specialize the template for assertion_traits for my type, but I was hoping to be able to solve the more general problem of providing a way to put my class into a stream, rather than just catering to the test framework.
Try defining operator<< as a friend inline function inside the class definition. I always find this way works the best, especially for templates. For example, Boost.Random defines operator<< inside exponential distribution's declaration: template<class CharT, class Traits> friend std::basic_ostream<CharT,Traits>& operator<<(std::basic_ostream<CharT,Traits>& os, const exponential_distribution& ed) { os << ed._lambda; return os; }
1,461,867
1,461,962
why does this work? (finding odd number in c++)
for (unsigned int i = 1; i <= 100; i++) { if (i & 0x00000001) { std::cout << i<<","; } } why does (and how): if( i & 0x00000001 ) figure out the odd number?
0x00000001 is 1 in binary, although it's written in hexadecimal (base-16) notation. That's the 0x part. & is the bit-wise 'AND' operator, which is used to do binary digit (bit) manipulations. i & 1 converts all of the binary digits of i to zero, except for the last one. It's straightforward to convert the resulting 1-bit number to a boolean, for evaluation by the if statement. The following chart shows the last 16 binary digits of i, and what happens to them. i: i in binary: i & 1 in binary: convert to boolean ---- ------------------- ------------------- --------------------- 1 0000000000000001 0000000000000001 true 2 0000000000000010 0000000000000000 false 3 0000000000000011 0000000000000001 true 4 0000000000000100 0000000000000000 false 5 0000000000000101 0000000000000001 true 6 0000000000000110 0000000000000000 false 7 0000000000000111 0000000000000001 true 8 0000000000001000 0000000000000000 false ... ... ... ... 99 0000000001100011 0000000000000001 true 100 0000000001100100 0000000000000000 false
1,462,078
1,474,071
Why won't Direct3D recover after unplugging a monitor in Windows XP?
An interesting bug came up that I'm having no luck with. In a windowed Direct3D9 program using native code, I handle a device lost using something similar to the following: void MyClass::RecoverFromDeviceLost(LPDIRECT3DDEVICE9 deviceToRecover, D3DPRESENT_PARAMETERS devicePresentParams ) { HRESULT hr = deviceToRecover->TestCooperativeLevel(); if(hr == D3DERR_DEVICELOST ) { //Code to shutdown all D3DPOOL_DEFAULT allocated objects }else if(hr == D3DERR_DEVICENOTRESET){ hr = deviceToRecover->Reset(&devicePresentParams); if(SUCCEEDED(hr)) { //Code to rebuild all D3DPOOL_DEFAULT objects } } } This works fine on Vista, but seems to have major problems on XP. If the monitor is unplugged, or switched away from the PC via a KVM, I never receive the D3DERR_DEVICELOST. The only return value from TestCooperativeLevel I ever receive is D3DERR_DEVICENOTRESET. And every call to Reset gives a D3DERR_INVALIDCALL. I tried forcing the program to use the shutdown code by doing this: ... else if(hr == D3DERR_DEVICENOTRESET){ hr = deviceToRecover->Reset(&devicePresentParams); if(SUCCEEDED(hr)) { //Code to rebuild all D3DPOOL_DEFAULT objects }else { //Duplicate of code to shutdown all D3DPOOL_DEFAULT objects } } ... But there was no change. This problem only seems to affect Windows XP (so far tested on SP2, SP3). I am using the August 2007 DXSDK, and can't update at this time. Has anyone seen this problem before, or have any idea why I can't reset my device? UPDATE: I believe I have found a solution, but am still perplexed by the failure of the second code segment listed above. After getting the DirectX Debug runtime to work over remote debugging, I realized the reason that the Reset function kept failing was because there were unreleased resources. However, the exact same release code, when applied as shown in the answer, resolved the issue. I did verify that the program was not creating D3DPOOL_DEFAULT objects between calls to the recover function. Is there something in the structure of Direct3D that could cause a problem if performing a reset as shown in the this question's code segments?
I ended up testing a different program that uses DirectX for graphics, just to see if the problem was just with the one program. The other application recovered with no problems from a monitor unplug or KVM switchover in Windows XP. The main difference between the two programs was that the working one used DXUT to manage the Direct3d, whereas I was doing all manual management in the one that didn't work. After combing through the DXUT source code, I noticed that they used a single step approach to device recovery that didn't rely on a D3DERR_DEVICELOST being returned from TestCooperativeLevel prior to the D3DERR_DEVICENOTRESET return value. The following code seems to have fixed the problem: void MyClass::RecoverFromDeviceLost(LPDIRECT3DDEVICE9 deviceToRecover, D3DPRESENT_PARAMETERS devicePresentParams ) { HRESULT hr = deviceToRecover->TestCooperativeLevel(); if(hr == D3DERR_DEVICELOST ) { //Device is lost and cannot be reset yet return; } //Code to shutdown all D3DPOOL_DEFAULT allocated objects hr=deviceToRecover->Reset(&devicePresentParams); if(SUCCEEDED(hr)){ //Code to rebuild all D3DPOOL_DEFAULT objects } } This code does have the side effect of resetting multiple times if the monitor is unplugged (or KVM switched) for an extended period of time.
1,462,341
1,462,350
"GetOrCreate" - does that idiom have an established name?
Ok, consider this common idiom that most of us have used many times (I assume): class FooBarDictionary { private Dictionary<String, FooBar> fooBars; ... FooBar GetOrCreate(String key) { FooBar fooBar; if (!fooBars.TryGetValue(key, out fooBar)) { fooBar = new FooBar(); fooBars.Add(key, fooBar); } return fooBar; } } Does it have any kind of established name? (Yes, it's written in C#, but it can be "easily" transferred to C++. Hence that tag.)
Lazy Loading http://en.wikipedia.org/wiki/Lazy_loading
1,462,359
1,472,117
How can I share data between C++ and Lua?
I have been looking for tutorials demonstrating how to share a C++ object with Lua using the API. Most tutorials just show how to export a class. I would like to start very simple and expose a variable (say int myVar = 5) in such a way that a change in Lua will be reflected in the C++ application. Does anyone know any good tutorials around which can show me how to do this?
As sbk mentioned, you'd access your variable as a member of a userdata: print(cside.myVar) -- 5 Here is some sample code to do this using the Lua API. Its straightforward, although tedious. You'll either want to make your own code generator or using something like swig or tolua++ /* gcc -o simple simple.c -llua -lm -ldl */ #include <stdio.h> #include "lua.h" #include "lauxlib.h" int myVar = 5; int l_set( lua_State *L ) { const char *key = luaL_checkstring(L, 2); int val = luaL_checkint(L, 3); if (strcmp(key, "myVar") == 0) myVar = val; } int l_get( lua_State *L ) { const char *key = luaL_checkstring(L, 2); if (strcmp(key, "myVar") == 0) { lua_pushinteger(L, myVar); return 1; } } int main(int argc, char *argv[]) { const struct luaL_Reg somemt[] = { { "__index", l_get }, { "__newindex", l_set }, { NULL, NULL } }; lua_State *L = luaL_newstate(); luaL_openlibs( L ); lua_newuserdata(L, sizeof(void *)); luaL_newmetatable(L, "somemt"); luaL_register( L, NULL, somemt ); lua_setmetatable(L, -2); lua_setglobal(L, "cside"); luaL_dostring(L, "print('from Lua:', cside.myVar)"); luaL_dostring(L, "cside.myVar = 200"); printf( "from C: myVar = %d\n", myVar ); }
1,462,599
1,464,515
Is there any memory browser in QtCreator?
I can't find it. In the watcher window I can manually type memory addresses but I'd like to see bigger chunks of memory... If this doesn't exist, is there any other free memory mapper for the Mac (except for XCode and Eclipse)? Thanks, rui
The only way to do this that I've found is to type gdb commands in to the debugger - you can get GDB to dump areas of memory... hopefully there'll be this feature in a newer release!
1,462,829
1,462,884
What is the most elegant and efficient way to model a game object hierarchy? (design bothers)
I've got the following code, think simple shooter in c++: // world.hpp //---------- class Enemy; class Bullet; class Player; struct World { // has-a collision map // has-a list of Enemies // has-a list of Bullets // has-a pointer to a player }; // object.hpp //----------- #include "world.hpp" struct Object { virtual ~Object(); virtual void Update() =0; virtual void Render() const =0; Float xPos, yPos, xVel, yVel, radius; // etc. }; struct Enemy: public Object { virtual ~Enemy(); virtual void Update(); virtual void Render() const; }; // Bullet and Player are similar (they render and update differently per se, /// but the behavior exposed to World is similar) // world.cpp //---------- #include "object.hpp" // object.cpp //----------- #include "object.hpp" Two problems with this: 1, Game objects knowing about other game objects. There has to be a facility that knows about all objects. It might or might not have to expose ALL objects, it has to expose some of it, depending parameters of the enquirer (position, for one). This facility is supposed to be World. Objects have to know about the World they're in, to query for collision information and other objects. This introduces a dependency where both Objects' and World's implementation have to access to object's header, thus World won't include its own header directly rather than by including object.hpp (which in turn includes world.hpp). This makes me feel uncomfortable -- I don't feel that world.cpp should recompile after I make a change to object.hpp. World doesn't feel like it should work with Object. It feels like bad design - how can it be fixed? 2, Polymorphism -- can and should it be used for anything beyond code reuse and logical grouping of game entities (and how)? Enemies, Bullets and Player will update and render differently, surely, hence the virtual Update() and Render() functionality -- an identical interface. They're still kept in separate lists and the reason for this is that their interaction depends on which lists two interacting objects are - two Enemies bounce off each other, a Bullet and an Enemy destroys each other etc. This is functionality that's beyond the implementation of Enemy and Bullet; that's not my concern here. I feel that beyond their identical interfaces there's a factor that separates Enemies, Bullets and Players and this could and should be expressed in some other way, allowing me to create a single list for all of them -- as their interface is identical! The problem is how to tell an object category from another if contained within the same list. Typeid or other form of type identification is out of the question - but then what other way to do it? Or maybe there's nothing wrong with the approach?
This is probably the biggest issue I encounter when designing similar programs. The approach I've settled on is to realize that an object really does not care about where it is in absolute terms. All it cares about is what is around it. As a result, the World object (and I prefer the object approach to a singleton for many good reasons which you can search for on the Internet) maintains where all the objects are, and they can ask the world what objects are nearby, where other objects are in relation to it, etc. World should not care about the content of Object; it will hold pretty much anything, and the Objects themselves will define how they interact with each other. Events are also a great way to handle objects interacting, as they provide a means for World to inform an Object of what's going on without caring what an Object is. Hiding information from an Object about all objects is a good idea, and should not be confused with hiding information about any Object. Think in terms of people - it's reasonable for you to know and retain information about many different people, though you can only find that information out by encountering them or having someone else telling you about them. EDIT AGAIN: All right. It's pretty clear to me what you really want, and that is multiple dispatch - the ability to handle a situation polymorphically on types of many parameters to the function call, rather than just one. C++ unfortunately does not support multiple dispatch natively. There are two options here. You can attempt to reproduce multiple dispatch with double dispatch or the visitor pattern, or you can use dynamic_cast. Which you want to use depends on the circumstances. If you have a lot of different types to use this on, dynamic_cast is probably the better approach. If you have only a few, double dispatch or the visitor pattern is probably more appropriate.
1,462,932
1,462,943
Is there a 'restart' function in Windows/C++
In a windows project I am working on, I intend to have a menu selection that copletely restarts the app. Is there a Windows or C++ function that does this?
There isn't a built-in for this, but a well-designed application can simply stop everything that's going on and then loop back to the start. If you want a true 'fresh start', you will have to spawn a new process (possibly as the last thing you do before the old one shuts down.)
1,463,040
1,463,050
Does Windows have its own 'call other .exe' function (C++)
I know in C++ there is a function system("example.exe"); that runs another program, put it requires the include stdlib.h. Because I am already including 'windows.h', is there an equivilant to the system() function in Windows?
There is CreateProcess to run a specific executable, or ShellExecute to run programs or open documents with their associated program. If portability to other platforms is any issue at all, I'd stick with system. #including stdlib.h won't kill you ;)
1,463,148
1,474,613
Is it possible to prevent an RAII-style class from being instantiated "anonymously"?
Suppose I have an RAII-style C++ class: class StateSaver { public: StateSaver(int i) { saveState(); } ~StateSaver() { restoreState(); } }; ...to be used like so in my code: void Manipulate() { StateSaver save(1); // ...do stuff that modifies state } ...the goal being to enter some state, do stuff, then leave that state when I leave that scope. Is there a way to make this typo not compile (or warn, or somehow complain so that the mistake can be noticed)? void Manipulate() { StateSaver(1); // ruh-roh, state saved and immediately restored! // ...do stuff that modifies state } I'm not aware of anything in C++ itself which I could use to prevent this, but that doesn't mean it doesn't exist. If there isn't anything in C++, compiler-specific extensions would be acceptable. I'm primarily interested in anything targeting gcc and msvc (someday icc, ideas for other compilers welcome but less likely to be useful) so hacks for any of them would be useful (abstracted into appropriately #ifdef'd macro definitions, of course).
I actually had to tweak my solution in a bunch of ways from the variant Waldo posted, but what I eventually got to is a macro-ized version of: class GuardNotifier { bool* notified; public: GuardNotifier() : notified(NULL) { } void init(bool* ptr) { notified = ptr; } ~GuardNotifier() { *notified = true; } }; class GuardNotifyReceiver { bool notified; public: GuardNotifyReceiver() : notified(false) { } void init(const GuardNotifier& notifier) { const_cast<GuardNotifier&>(notifier).init(&notified); } ~GuardNotifyReceiver() { assert(notified); } }; class StateSaver { GuardNotifyReceiver receiver; public: StateSaver(int i, const GuardNotifier& notifier = GuardNotifier()) { receiver.init(notifier) saveState(); } ~StateSaver() { restoreState(); } };
1,463,150
1,463,194
C++: Pointer to class member function inside a non-related structure
I've done a bit of reading online as to how to go about this and I think I'm doing it correctly... My goal is to have an array of structure objects that contain pointers to member-functions of a class. Here's what I have so far... typedef void (foo::*HandlerPtr)(...); class foo { public: void someFunc(...); // ... private: // ... }; struct STRUCT { HandlerPtr handler; }; STRUCT stuff[] { {&foo::someFunc} }; Then when calling the function using (stuff[0].*handler)(), with or without arguments (I do actually intend to use argument lists), I get "handler": Undeclared identifier... I've got to be missing something, just don't know what.
someFunc() is not a static method, so you need a foo object instance in order to call someFunc() via your pointer-to-method variable, ie: foo f; f.*(stuff[0].handler)(); Or: foo f; HandlerPtr mthd = stuff[0].handler; f.*mthd(); Or, using pointers: foo *f = new foo; f->*(stuff[0].handler)(); delete f; Or: foo *f = new foo; HandlerPtr mthd = stuff[0].handler; f->*mthd(); delete f;
1,463,409
1,463,435
How to check for NULL in c++?
Let say for example, I have a struct, and an array of the struct. What I want to do is to iterate through the array and check if any of the item is a null. I tried checking the item against NULL and (struct *) 0, that don't seem to work. Is there any reliable way to check for null value? UPDATE Sample Code struct Test{ int a; }; Test testArray[size]; for (int i = 0; i < testCount; i++) { if (testArray[i] == NULL) //this doesnt work { } } Thanks, RWendi
If you have an array of structs, then there are no pointers, so it doesn't make sense to check for null. An array of n structs is literally n of those structs laid out one after the other in memory. Could you change it to an array of pointers to structs, initialise them all to NULL, and create them as you need them? I'd be looking into why you want to check for null though first - it feels like you're doing something wrong. (Edit for code added to question) You don't show how you define testArray, but I suspect you've done the following: Test testArray[testCount]; If you really need to compare against null, try the following: Test *testArray[testCount]; for (int i = 0; i < testCount; i++) { testArray[i] = new Test; } At this point, none of the entries will be NULL, but if later in your code you do something like: testArray[3] = NULL; then you'll be able to detect that with the loop you provided in your question. Can you clarify why you want to compare with NULL? (And it keeps growing again - this time to address question regarding initialisation): As others have mentioned, comparing with NULL is not a valid way of telling if something is initialised or not. Probably the best way forward is to write your code in such a way that you guarantee it will be initialised. Probably the best way to do this is to put a default constructor on your Test struct (you can do this in C++, but not C). Something like: struct A { int x; A() : x(0) { } }; will do the job just fine. Now all of the structs in your array are guaranteed to exist, and be initialised with their x value set to 0.
1,463,515
1,463,570
How can I use Dynamic Methods in C++
I've found myself writing some repetitious code in C++. I'm using some auto-generated, such that if I want to deal with Foo, Bar, & Baz they all have fairly similar method. E.g., get_foo, get_bar, get_baz, etc. For each "thing" I more or less have to do the same types of thing. Check if it exists, if it does, get the log, look for the most recent entry in the log, check the entry for problems, etc. That's lead to a fair bit of repeated code, along the lines of: if (obj->has_foo) { if(obj->get_foo().has_log()) { Log *l = obj->get_foo().get_foo_log(); if (!l) { ERROR("Foo does not have a log") } ... 30-40 more lines of stuff ... } } if (obj->has_bar) { if(obj->get_bar().has_log()) { Log *l = obj->get_bar().get_bar_log(); if (!l) { ERROR("Bar does not have a log") } ... 30-40 more lines of stuff ... } } if (obj->has_baz) { if(obj->get_baz().has_log()) { Log *l = obj->get_baz().get_baz_log(); if (!l) { ERROR("Baz does not have a log") } ... 30-40 more lines of stuff ... } } Is there a way I could build a collection, such that each item in the collection would have the unique aspects of Foo, Bar, Baz and I could use them in a single block of code. Forgive the Perl-eese, but something like: foreach my $thingie ("foo", "bar", "baz") { if (obj->has_$thingie) { if(obj->get_$thingie().has_log()) { Log *l = obj->get_$thingie().get_$thingie_log(); if (!l) { ERROR(sprintf("%s does not have a log", $thingie)) } ... 30-40 more lines of stuff ... } } } Or, if that's not the right direction, how do I avoid copy/pasting/tweaking that same fundamental block 3 times?
Sure (code untested, I might have missed some problem with member pointers and type deduction, or I might just have left bugs): template <typename T, typename M, typename F, typename G> void doChecks(T *obj, M has_member, F get_fn, G getlog_fn) { if (obj->*has_member) { if (obj->*get_fn().has_log()) { Log *l = obj->*get_fn().*getlog_fn(); if (!l) { ERROR("%s does not have a log", typeid(T).name()); } } } } MyObj obj; doChecks(obj, &MyObj::has_foo, &MyObj::get_foo, &Foo::get_foo_log); doChecks(obj, &MyObj::has_bar, &MyObj::get_bar, &Bar::get_bar_log); doChecks(obj, &MyObj::has_baz, &MyObj::get_baz, &Baz::get_baz_log); Obviously you could use a functor-type template parameter, but this is the closest to the perl approach without actually building a dictionary into the object and rolling your own dispatch. You could also macro-ise those calls to doChecks if you wanted, and use some token-pasting to make them a bit shorter: #define DOCHECKS(obj, class, thing) doChecks(obj, &MyObj::has_##thing, &MyObj::get_##thing, & class :: get_##thing##log) DOCHECKS(obj, Foo, foo); DOCHECKS(obj, Bar, bar); DOCHECKS(obj, Baz, baz); With additional preprocessor wizardry you can probably make it a loop, not sure. Look at the Boost preprocessor library or the Chaos Preprocessor.
1,464,098
1,464,106
How can I get c-function based diffs?
Our team uses svn to manage our source. When performing a re-factor on a C file, I occasionally both change functions and move them within the file. Generally I try to avoid moving functions, because it makes the default svn diff get a bit addled about what's going on, and it often provides a diff which is more confusing than it needs to be. None the less, occasionally I do make both function file-location changes, and function internal code changes. Another place this comes up is in branch merging, when the file is in conflict, and either or both branches have moves as well as intra-function changes. So, what I am looking for is a semantically aware diff tool that could tell me diffs at two levels - function arrangement, and detail (intra-function). I tried using the "-p" option to diff (-x -p to svn diff), but that's not what it's intended for, it certainly didn't do what I wanted. Another option I just thought of is using a diff program designed to catch code-copying such as a university might use for checking assignments, but nothing obvious came up in a quick search.
One way to do it with the tools you have is to move the functions first, check them in, then change them. Or have two enlistments, and when you see this happening move them in one, svn up the other, resolve the merge issue. It moves the work to you, but makes code reviews easier.
1,464,439
1,464,660
Using std::bind2nd with references
I have a simple class like this: class A { public: void f(const int& n) { std::cout<<"A::f()" << n <<"\n"; } }; and I am trying to use it like this: std::vector<A> vec; A a; vec.push_back(a); std::for_each(vec.begin(), vec.end(), std::bind2nd(std::mem_fun_ref(&A::f), 9)); But when I compile the code I get the following error somewhere inside functional header file: error C2529: '_Right' : reference to reference is illegal If I remove the reference in the parameter f() it compiles fine. How do I resolve this? I don't want to remove the reference as in my real code the copying of the object is quite costly. Also, I am not using boost.
You can't do that easily, sorry. Just consider it one of those cases not covered by std::bind1st and std::bind2nd (kinda like 3-argument functions etc). Boost would help - boost::bind supports references transparently, and there's also boost::ref. If your implementation supports TR1 - latest g++ versions and VC++2008 SP1 both do - then you can use std::tr1::bind, which is for the most part same as boost::bind, but standardized.
1,464,510
1,464,930
Storage Card Problem In windows mobile
I m making windows mobile application, it refers some DLL's but i have some problem here. Imagine my application is installed in storage card related DLL's present in Storage card only, if i launch application it refers some of DLL, now i will remove the storage card, still my application will be running,it will not quit only ultimately it leads to restart of my mobile device.. i do get the divice card remove notification but its in DLL and its c++ code.. if card is removed no DLL will be present in storage card, i dont even get the notification also in c# i dont no how to get the card removed notification in c#. how to handle these scenarios please let me know. Thanks
You can use the function SHChangeNotifyRegister to WM_FILECHANGEINFO message. After you subscribe, you will be receiving events with ids such as SHCNE_DRIVEREMOVED or SHCNE_MEDIAREMOVED, so you can trigger some actions when storage card is removed. To use native functions from the compact framework, use P/Invoke.
1,464,591
1,464,601
How to create a bold, red text label in Qt?
I want to write a single, bold red line in my application using Qt. As far as I understand, I would create a QLabel, set its textFormat to rich text and give it a rich text string to display: QLabel *warning = new QLabel; warning->setTextFormat(Qt::RichText); warning->setText("{\\rtf1\\ansi\\ansicpg1252 {\\fonttbl\\f0\\fswiss\\fcharset0 Helvetica;} {\\colortbl;\\red255\\green0\\blue0;} \\f0 \\cf0 this is bold red text}"); I tested this rich text string in a rich text editor and it displays fine. But Qt displays the whole string with all braces, keywords and backslashes instead of "this is bold red text". What am I doing wrong? Thank you for your help.
Try using HTML formatting: <b><font... etc </b>. Qt Designer does it like this: <span style=" font-size:8pt; font-weight:600; color:#aa0000;">TextLabel</span>
1,464,711
1,464,759
How to detect if errno_t is defined?
I'm compiling code using gcc that comes from Visual C++ 2008. The code is using errno_t, but in some versions of gcc headers including <errno.h> doesn't define the type. How do I detect if the type is defined? Is there a define that signals that the type was defined? In the case it isn't defined I'd like to provide the typedef to let the code compile correctly on all platforms.
You can't check for a typedef the way you can for a macro, so this is a bit on the tricky side. If you're using autoconf, this patch shows the minimum changes that you need to have autoconf check for the presence of errno_t and define it if it's missing (the typedef would be placed in a file that includes your generated config.h and is included by all files that need errno_t). If you're not using autoconf you need to come up with some way to do the same thing within your build system, or a very clever set of tests against compiler version macros.
1,464,751
1,465,552
I want to use Infocardapi.dll in Delphi/WIN32 but would like a header file for it
Microsoft has this nice little feature called CardSpace. This is a Microsoft implementation of InfoCards. Microsoft has a nice document which explains how it can be used, which is useful. And doing a Google search doesn't provide me many useful answers but it does provide an enormous amount of noise. (Mostly because people wonder what it is or sites offering this DLL as some kind of download. The latter is suspicious since it's just part of Windows Vista and .NET 3.0 and higher.) Basically, I need to call all functionality from this DLL within Delphi 2007. If there's a C++ header for this DLL then I can convert it. Or maybe some other information about it's functions, parameters, datatypes and whatever more.
There is an InfoCard.h file included with Microsoft's Windows SDK which should be what you need. Bit of a hefty download for a single file if you don't already have it - you might be better visiting the MSDN reference for the CardSpace API and getting the info from there.
1,464,758
1,464,808
[c++ / pointers]: having objects A and B (B has vector member, which stores pointer to A), knowing A is it possible to retrieve pointer to B?
While trying to learn c++, I tried to implement class representing very basic trie. I came up with the following: class Trie { public: char data; vector<Trie* > children; Trie(char data); Trie* addChild(Trie* ch); // adds child node (skipped others members/methods) }; Method addChild checks if child ch with the same data is present in vector children, if not then it inserts it there, if yes - returns pointer to already existing child. Now, considering this code snippet: Trie t('c'); Trie* firstchild = new Trie('b'); Trie* secondchild = new Trie('a'); firstchild->addChild(secondchild); t.addChild(firstchild); if I only have pointer to secondchild, is it possible to somehow return pointers to firstchild or maybe even t? I would like to know if it possible to do so, because the logic of my working code needs to traverse the trie "up" (from lower nodes to upper ones), to the parent of current object. Currently I am just using recursive function to travel down - but I am wondering if there exists any other way? I am sorry if above is unclear or if I messed up somewhere, I am rather inexperienced and writing from my memory, without the working code.
You need to add something like Trie* parent; or Trie* previoussibling; Trie* nextsibling; to the class to get directly from firstchild to secondchild or vice-versa, or to go up from one of the children to t. Note that if you need this kind of relationship then you will require more maintenance when adding and removing nodes to keep all the links correct.
1,464,932
1,464,976
How to make the ToolTip appear in the foreground of the floating CPaneDialog?
Does anybody has a hint for the following problem? I have a derived class from CPaneDialog, it contains just one button. I want to show a tooltip if the mouse is over it. For this I use CMFCToolTipCtrl: // Create the ToolTip control. m_ToolTip.Create(this, TTS_ALWAYSTIP | TTS_NOPREFIX); m_ToolTip.Activate(TRUE); CMFCToolTipInfo params; params.m_bVislManagerTheme = TRUE; m_ToolTip.SetParams(&params); m_ToolTip.AddTool(GetDlgItem(IDC_BUTTON1), _T("Here is the text of my tooltip message.")); The m_ToolTip.RelayEvent(pMsg) I call from PreTranslateMessage(). If i compile and run the application, it looks like on the image below: The tooltip appears in the background of my pane! ToolTipOnPane http://img268.imageshack.us/img268/9926/tooltiponpanedialog.png
set the topmost property. m_ToolTip.SetWindowPos(&CWnd::wndTopMost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
1,465,018
1,465,034
Switch Programming Language
I've forgotten how to switch programming languages in Visual Studio 2008. I need to switch from C++ to C#. Help!
Do you mean you want to switch the key-mappings ? Main menu > Tools > Options > Environment > Keyboard Use the dropdown that says Apply keyboard mapping scheme.. to switch from C++ to C#
1,465,112
1,531,429
SetWindowsHook stops working after some time
I defined a global hook on WM_MOUSE that works perfectly for some time. It post a message to a specific window each time the mouse move. After some random time the hook stop sending messages. If I unregister and register the hook it works again. I suppose some specific thing happening in Windows cause the hook to stop, but I can't find what. Any ideas ? Edit: I attached a debugger to other processes when the hook is not active anymore, and I observed that the dll is not loaded anymore. What could cause a hook dll to unload ? Edit2 : I find out that a crash in MouseHookProc the dll in any process unload the hook dll from every process it's loaded in. I can't find a cause to a crash in my code. Might be some race condition or something ? Here is the hook dll code : #include "stdafx.h" // define a data segment #pragma data_seg(".SHARED") HWND hwnd=0; HHOOK hHook=0; #pragma data_seg() // tell the linker to share the segment #pragma comment(linker, "/section:.SHARED,RWS") #define WM_MOUSEHOOK WM_USER+0x100 HINSTANCE hInstance=0; // this allow to build a very small executable without any extra libraries // (probably not the problem, the bug still occurs without this ) #ifndef _DEBUG void *__cdecl operator new(unsigned int bytes) { return HeapAlloc(GetProcessHeap(), 0, bytes); } void __cdecl operator delete(void *ptr) { if(ptr) HeapFree(GetProcessHeap(), 0, ptr); } extern "C" int __cdecl __purecall(void) { return 0; } #endif BOOL APIENTRY DllMain( HINSTANCE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { hInstance=hModule; return TRUE; } LRESULT CALLBACK MouseHookProc(int nCode, WORD wParam, DWORD lParam) { if(nCode==HC_ACTION && (wParam==WM_MOUSEMOVE || wParam==WM_NCMOUSEMOVE)) { MSLLHOOKSTRUCT *mhs=(MSLLHOOKSTRUCT*)lParam; PostMessage(hwnd, WM_MOUSEHOOK, wParam, 0); } return CallNextHookEx(hHook,nCode,wParam,lParam); } extern "C" __declspec(dllexport) HHOOK InitializeWindowsHook(char *title) { hwnd=FindWindow(0, title); if(hwnd) hHook=SetWindowsHookEx(WH_MOUSE, (HOOKPROC)MouseHookProc, hInstance, 0); return hHook; } extern "C" __declspec(dllexport) BOOL DeinitializeWindowsHook() { if(hHook) { BOOL b=UnhookWindowsHookEx(hHook); hHook=0; return b; } return FALSE; }
Did you check, if the hook is still installed when its not called any more (i.e. check the return value from BOOL UnhookWindowsHook)? Possibly another hook is installed that does not preserve your hook, not calling CallNextHookEx().
1,465,494
1,465,957
service and registry
I have a problem in understanding the relationship between services and registry. I have the task of taking my windows C++ program and transform it from simple application to a service. I read that I need to produce some more functions as: start stop resume install. The problem is: Why I need the regisrty ? how I enter the new program ? Beside those method what I need to do with the registry? how I enter inside it ? Do I need to write a script for entering the service ? I read but I just didn't understand, any answear and or some good links to explanation will be appreciated. Thanks,
I'm not aware of any documented relationship between services and the registry. Services can use the registry to store their settings, just like any other application, but they're not required to. Formally, you don't need the registry. You simply need to install the service using the relevant API functions. As part of their implementation, the API functions create registry entries that the OS uses later to know when and how to start your service, but I don't think those keys are documented with any expectation that developers would modify them manually, so don't worry about them. If your program uses the registry to store settings, though, you'll need to understand what account your service runs as, because that affects what areas of the registry your program has access to. Install your service by calling CreateService. Do that in your program's installer. You can also make your service install itself when it detects itself being run with a certain command-line switch, such as -i. To uninstall your service, call OpenService and then DeleteService. In either case, you'll need to call OpenSCManager first. See MSDN for more on how to call those functions. Alternatively, you can use the sc command to create and delete your service. As I mentioned above, you don't need to do anything with the registry. Just install and uninstall your service with the API and let the OS take care of the rest. You don't need to write any scripts to start your service. The OS already knows how to start it (because it's installed). If your service is something that users would want to start and stop frequently, then rather than use the service control panel then they can use the net or sc commands.
1,465,549
1,465,609
CMFCButton with Vista Style
I can't seem to get a CMFCButton to be displayed in Vista style in a dialog box application. I'm using VS2008 with MFC Feature Pack. Here are some steps to reproduce my problem: Create a new MFC Project; Specify a Dialog based project. Add two buttons to the main dialog. Add a variable for each button. Make one of the variables a CButton, the other one a CMFCButton. Compile and run. test app picture http://img7.imageshack.us/img7/3/testapp.png As you can see, the CButton has the correct style but the CMFCButton does not. What I am missing here?
The CMFCButton has the BS_OWNERDRAW style set by default - you can remove it in the OnInitDialog() for your dialog: mfcButton.ModifyStyle(BS_OWNERDRAW, 0, 0); However, removing the owner draw style results in many of the methods of CMFCButton being rendered useless (e.g. SetTextColor). You can get the button to render using the current windows theme by setting up the visual manager: CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows)); This is done instead of the ModifyStyle above, resulting in buttons that fit the default style but still have the newer rendering features.
1,465,655
1,465,760
Unmanaged C++ tlh file not updating?
I have an IDL file with some interfaces in it. [ object, uuid(newguid), dual, helpstring("NewInterface Interface"), pointer_default(unique) ] interface INewInterface: IOldInterface { [id(newid), helpstring("method NewMethod")] HRESULT NewMethod([in] BSTR bstrParam ); } But when I compile my code it does not see my new interface. Also when I open the .tlh file it has not been updated to display the new interface. Any thoughts on what I need to do? Edit: Imports are made via #import "File.tlb" raw_interfaces_only no_namespace The tlb file does not seem to be getting updated either :(
The .tlh and .tli file should be updated when the .tlb timestamp has changed and you're #importing it. The .tlb file is the output when compiling the .idl file. So you should check if the compile-settings for the .idl file are correct (configuration-dependent!) if the .tlb imported is really the same as the one compiled (check the include paths), as sharptooth described in the comment. Beyond that, clearing/deleting all output-files manually sometimes makes a difference. Although, I've to say, the usual problem with the MS toolchain using the project-files is that it is recompiling too often instead not often enough, so beyond configuration problems I've not had such a problem as you describe.
1,465,851
1,465,919
Returning const reference to local variable from a function
I have some questions on returning a reference to a local variable from a function: class A { public: A(int xx) : x(xx) { printf("A::A()\n"); } }; const A& getA1() { A a(5); return a; } A& getA2() { A a(5); return a; } A getA3() { A a(5); return a; } int main() { const A& newA1 = getA1(); //1 A& newA2 = getA2(); //2 A& newA3 = getA3(); //3 } My questions are => Is the implementation of getA1() correct? I feel it is incorrect as it is returning the address of a local variable or temporary. Which of the statements in main (1,2,3) will lead to undefined behavior? In const A& newA1 = getA1(); does the standard guarantee that a temporary bound by a const reference will not be destroyed until the reference goes out of scope?
1. Is getA1() implementation correct ? I feel it is incorrect as it is returning address of local variable or temporary. The only version of getAx() that is correct in your program is getA3(). Both of the others have undefined behaviour no matter how you use them later. 2. Which of the statements in main ( 1,2,3) will lead to undefined behavior ? In one sense none of them. For 1 and 2 the undefined behaviour is as a result of the bodies of the functions. For the last line, newA3 should be a compile error as you cannot bind a temporary to a non const reference. 3. In const A& newA1 = getA1(); does standard guarantees that temporary bound by a const reference will not be destroyed until the reference goes out of scope? No. The following is an example of that: A const & newConstA3 = getA3 (); Here, getA3() returns a temporary and the lifetime of that temporary is now bound to the object newConstA3. In other words the temporary will exist until newConstA3 goes out of scope.
1,465,970
1,465,983
Transfer ownership within STL containers?
Is it possible to transfer ownership of a vector contents from one vector to another? vector<T> v1; // fill v1 vector<T> v2 = OvertakeContents(v1); // now v1 would be empty and v2 would have all the contents of v1 It is possible for lists with splice function. This should be possible in constant time for whole vector as well. If it isn't then why not?
Check out std::swap vector<T> v1; // fill v1 vector<T> v2; swap(v1, v2); OR v2.swap(v1); Swap Reference
1,466,073
1,466,658
How is std::string implemented?
I am curious to know how std::string is implemented and how does it differ from c string?If the standard does not specify any implementation then any implementation with explanation would be great with how it satisfies the string requirement given by standard?
Virtually every compiler I've used provides source code for the runtime - so whether you're using GCC or MSVC or whatever, you have the capability to look at the implementation. However, a large part or all of std::string will be implemented as template code, which can make for very difficult reading. Scott Meyer's book, Effective STL, has a chapter on std::string implementations that's a decent overview of the common variations: "Item 15: Be aware of variations in string implementations". He talks about 4 variations: several variations on a ref-counted implementation (commonly known as copy on write) - when a string object is copied unchanged, the refcount is incremented but the actual string data is not. Both object point to the same refcounted data until one of the objects modifies it, causing a 'copy on write' of the data. The variations are in where things like the refcount, locks etc are stored. a "short string optimization" (SSO) implementation. In this variant, the object contains the usual pointer to data, length, size of the dynamically allocated buffer, etc. But if the string is short enough, it will use that area to hold the string instead of dynamically allocating a buffer Also, Herb Sutter's "More Exceptional C++" has an appendix (Appendix A: "Optimizations that aren't (in a Multithreaded World)") that discusses why copy on write refcounted implementations often have performance problems in multithreaded applications due to synchronization issues. That article is also available online (but I'm not sure if it's exactly the same as what's in the book): http://www.gotw.ca/publications/optimizations.htm Both those chapters would be worthwhile reading.
1,466,121
1,466,152
How to use Intel C++ Compiler with Qt Creator
I am writing a program wherein i will need to do a stupendous number of numerical calculations. But since I am developing the front end of the program in Qt Creator, I have as yet been dealing with MinGW. As such, is there any way to integrate or use the Intel C++ Compiler with QT Creator? Currently using IC++ 11.0 and QtCreator 1.2.1
I think so but you need to rebuild / reconfigure Qt Creator as documented in the Deploying an Application on Windows section. And looking into the mkspecs directory, I see 'win32-icc' which is probably what you need. Edit: To clarify, you may need the whole 'SDK' rather than just the creator, and you need to then re-configure Qt within qt/ directoty of the SDK file tree using configure -platform win32-icc plus whatever other options you may need. It also takes a little while to build this, and as icc isn't know for its compilation speed you may want to give this a couple of hours to a day.
1,466,163
1,466,510
Overridden function pointer problem at template base class C++
I implemented a template base class for observer pattern, template<class T> class ActionListener { public: ActionListener(void); virtual ~ActionListener(void); void registerListener(T* listener); void unregisterListener(T* listener); template<typename Signal> void emit(Signal signal); template<typename Signal, typename Parameter> void emit(Signal signal, const Parameter& parameter); template<typename Signal, typename Parameter1, typename Parameter2> void emit(Signal signal, const Parameter1& parameter1, const Parameter2& parameter2); private: std::vector<T*> mListenerList; }; class IEventListener { public: virtual void messageArrived( Message* message); virtual void messageArrived(ClientHandle* handle, Message* message); }; i am using classes like this emit(&IEventListener::messageArrived, message); emit(&IEventListener::messageArrived, mHandle, message); the problem here is, compiler cannot deduce template parameters and i couldn't gave template parameters explicitly? Do someone have an idea ?? EDIT: Problem here is overridden function calling with template parameters."Emit" function works correctly for other function types. Usage of this pattern is class SampleClass : public ActionListener<IEventListener> { //some stuff here //this class is observing events of IEventListener } by the way this is C++.
IEventListener::messageArrived is overloaded, so the compiler can't determine the type of &IEventListener::messageArrived. It could be void (IEventListener::*)(Message*) or void (IEventListener::*)(ClientHandle*, Message*). The straighforward (and ugly) solution is to explicitely cast &IEventListener::messageArrived to the desired type at the call site, like this: emit(static_cast<void (IEventListener::*)(Message*)>(&IEventListener::messageArrived), a_message_ptr); or by assigning to a variable of the desired function type: void (IEventListener::*func_ptr)(Message*) = &IEventListener::messageArrived; emit(func_ptr, a_message_ptr); (Did I say it was ugly?) The template parameter could also be explicitly specified: emit<void (IEventListener::*)(Message*)>(&IEventListener::messageArrived, a_message_ptr); (Still ugly) Another imperfect solution is to deduce the type of Signal from the type of the listener (T) and the other parameters: // Warning: untested. // For illustration purposes only template<class T> class ActionListener { public: //... void emit(void (T::*signal)()); template<class Arg1T> void emit(void (T::*signal)(Arg1T), Arg1T); template<class Arg1T, class Arg2T> void emit(void (T::*signal)(Arg1T, Arg2T), Arg1T, Arg2T); }; This is imperfect though because the arguments types must match exactly. Depending how much change you can make in the design, a simpler solution would be to remove the ambiguity by giving different names to the members of IEventListener. You could also use an already existing signals/slots library, like Boost.Signals2
1,466,591
1,469,412
Problems encountered when implement a float, translucent sub-window in MFC with C++
I have tried several methods, but problems always exist. Sometimes the sub-window didn't refresh and sometimes the sub-window will keep blink. This is a sample project that i have written http://rapidshare.com/files/283950611/TestProject.7z.html My method to implement that is: Put a scroll bar on the top of sub-window, whenever the scroll bar was dragged, the sub-window would be moved as well. And every dialog is inherited from CDialogBase, All the drawing is done in this class, Drawer.h is a helper for drawing. Only when the DC that user assigned is dirty, then system will redraw the window, it is used for accelerating the painting.
WS_EX_LAYERED only can be added to with top level window, not sub-window; I've tried to modify the window style from WS_CHILD to WS_OVERLAPPED, and then using layed window, and then clip the visiable area of the window, but, the result is not what I expected. Anywhere, thank you for your advice...
1,466,756
1,466,769
C++ equivalent of Java ByteBuffer?
I'm looking for a C++ "equivalent" of Java ByteBuffer. I'm probably missing the obvious or just need an isolated usage example to clarify. I've looked through the iostream family & it looks like it may provide a basis. Specifically, I want to be able to: build a buffer from a byte array/point and get primitives from the buffer, e.g. getByte, getInt build a buffer using primitives e.g. putByte, putInt and then get the byte array/pointer.
You have stringbuf, filebuf or you could use vector<char>. This is a simple example using stringbuf: std::stringbuf buf; char data[] = {0, 1, 2, 3, 4, 5}; char tempbuf[sizeof data]; buf.sputn(data, sizeof data); // put data buf.sgetn(tempbuf, sizeof data); // get data Thanks @Pete Kirkham for the idea of generic functions. #include <sstream> template <class Type> std::stringbuf& put(std::stringbuf& buf, const Type& var) { buf.sputn(reinterpret_cast<const char*>(&var), sizeof var); return buf; } template <class Type> std::stringbuf& get(std::stringbuf& buf, Type& var) { buf.sgetn(reinterpret_cast<char*>(&var), sizeof(var)); return buf; } int main() { std::stringbuf mybuf; char byte = 0; int var; put(mybuf, byte++); put(mybuf, byte++); put(mybuf, byte++); put(mybuf, byte++); get(mybuf, var); }
1,466,810
1,467,462
How to draw a progress bar inside a list widget in Qt
I want to have a list of items that need to be processed in a QListWidget. Similar to Windows Media Player CD import, there should be a progress bar for every item in the list. Now there seems to be a way to do this by creating a regular progress bar, using QPixmap::grabWidget() to save its appearance in a QPixmap and then adding this QPixmap as Icon to the QListWidgetItem via QListWidgetItem::setIcon(). However, this seems to be horribly wacky. Do you know a more elegant way to achieve a progress bar inside a list widget?
Each item in a QListWidget can be represented by a QWidget of your choice, rather than the default rendering (text). You can set this by calling QListWidget::setItemWidget(). In this case, I'd recommend using QProgressBar as the rendering widget -- you should get the desired result. From the documentation of QListWidget::setItemWidget(): This function should only be used to display static content in the place of a list widget item. If you want to display custom dynamic content or implement a custom editor widget, use QListView and subclass QItemDelegate instead.
1,466,940
1,467,349
What is better for a message queue? mutex & cond or mutex&semaphore?
I am implementing a C++ message queue based on a std::queue. As I need popers to wait on an empty queue I was considering using mutex for mutual exclusion and cond for suspending threads on empty queue, as glib does with the gasyncqueue. However it looks to me that a mutex&semaphore would do the job, I think it contains an integer and that seems like a pretty high number to reach on pending messages. Pros of semaphore are that you don't need to check manually the condition each time you return from a wait, as you now for sure that someone inserted something(when someone inserted 2 items and you are the second thread arriving). Which one would you choose? EDIT: Changed the question in response to @Greg Rogers
A single semaphore does not do the job - you need to be comparing (mutex + semaphore) and (mutex + condition variable). It is pretty easy to see this by trying to implement it: void push(T t) { queue.push(t); sem.post(); } T pop() { sem.wait(); T t = queue.top(); queue.pop(); return t; } As you can see there is no mutual exclusion when you are actually reading/writing to the queue, even though the signalling (from the semaphore) is there. Multiple threads can call push at the same time and break the queue, or multiple threads could call pop at the same time and break it. Or, a thread could call pop and be removing the first element of the queue while another thread called push. You should use whichever you think is easier to implement, I doubt performance will vary much if any (it might be interesting to measure though).
1,467,057
1,468,317
Overhead of casting double to float?
So I have megabytes of data stored as doubles that need to be sent over a network... now I don't need the precision that a double offers, so I want to convert these to a float before sending them over the network. What is the overhead of simply doing: float myFloat = (float)myDouble; I'll be doing this operation several million times every few seconds and don't want to slow anything down. Thanks EDIT: My platform is x64 with Visual Studio 2008. EDIT 2: I have no control over how they are stored.
As Michael Burr said, while the overhead strongly depends on your platform, the overhead is definitely less than the time needed to send them over the wire. a rough estimate: 800MBit/s payload on a excellent Gigabit wire, 25M-floats/second. On a 2GHz single core, that gives you a whopping 80 clock cycles for each value converted to break even - anythign less, and you will save time. That should be more than enough on all architectures :) A simple load-store cycle (barring all caching delays) should be below 5 cycles per value. With instruction interleaving, SIMD extensions and/or parallelizing on multiple cores, you are likely to do multiple conversions in a single cycle. Also, the receiver will be happy having to handle only half the data. Remember that memory access time is nonlinear. The only thing arguing against the conversion would be is if the transfer should have minimal CPU load: a modern architecture could transfer the data from disk/memory to bus without CPU intervention. However, with above numbers I'd say that doesn't matter in practice. [edit] I checked some numbers, the 387 coprocessor would indeed have taken around 70 cycles for a load-store cycle. On the initial pentium, you are down to 3 cycles without any parallelization. So, unless you run a gigabit network on a 386...
1,467,067
1,467,270
Visual Studio 2008 Team: No call stack when I throw an exception
I am building the debug version of my app, with full symbols. I set a breakpoint on the following line: throw std::range_error( "invalid utf32" ); When the breakpoint hits, my stack looks normal. I can see all my routines. But if I run, and let the exception get thrown, I see a worthless stack. it has MyApp.exe!_threadstartex() towards the bottom, a few disabled entries labeled kernel32.dll, and the line "Frames below may be incorrect and/or missing" etc. This really sucks! Because very often I will get an exception in my debug build, and this $5000 development environment is not even showing me my own stack! I am statically linking with everything so its not a DLL problem. Help!
I think you mix up smth. here. If you catch the exception in some catch statement or it is propagated until main your stack was unwound and you can not expect VC++ to remember the entire stack. For example in Java stack trace is part of the exception itself. Dependent on you compiler you can write an exception class which records the stack trace if it is constructed (but not copy constructed) and carries the information. When the class is caught you can evaluate the info. If you program using MFC take a look at AfxDumpStack. Hope that helps, Ovanes P.S: This DDJ article might be helpful to you: C++ Stack Traces
1,467,144
1,467,187
How do I stop name-mangling of my DLL's exported function?
I'm trying to create a DLL that exports a function called "GetName". I'd like other code to be able to call this function without having to know the mangled function name. My header file looks like this: #ifdef __cplusplus #define EXPORT extern "C" __declspec (dllexport) #else #define EXPORT __declspec (dllexport) #endif EXPORT TCHAR * CALLBACK GetName(); My code looks like this: #include <windows.h> #include "PluginOne.h" int WINAPI DllMain (HINSTANCE hInstance, DWORD fdwReason, PVOID pvReserved) { return TRUE ; } EXPORT TCHAR * CALLBACK GetName() { return TEXT("Test Name"); } When I build, the DLL still exports the function with the name: "_GetName@0". What am I doing wrong?
Small correction - for success resolving name by clinet extern "C" must be as on export side as on import. extern "C" will reduce name of proc to: "_GetName". More over you can force any name with help of section EXPORTS in .def file
1,467,449
1,467,500
Designing a Vector3D class
I dont know which is the best practice when we want to create a new vector 3D class, i mean, which of this two examples is the best way ? class Vec3D { private: float m_fX; float m_fY; float m_fZ; ... }; or class Vec3D { private: float m_vVec[3]; ... }; With the first aproach, we have individual variables, we canot be sure to be contiguous in memory, so caches can fail, but access to this variables are a single instruction. With the second aproach, we have a vector of 3 contiguous floats in memory, caches are fine here, but every access will make an extra sum of variable offset. Buti think that this vector aproach could fit better with optimitzations like SSE2/3 or something. Which aproach is better, i'm lost, i need advices :) Thanks for your time :) LLORENS
use class Vec3D { private: union { float m_vVec[3]; struct { float m_fX; float m_fY; float m_fZ; }; }; ... } this will give you both at no extra cost
1,467,452
1,936,475
QDockWidget - remove handle
Is there an easy way to remove the QDockWidget's resize handle? My dock widget can't be resized (the sizepolicy is fixed), so having the handle there is just redundant.
This bug is as old as Qt itself, I reported this in this report for this in the Qt bugtracker. Please vote it up if you want it to get fixed faster.
1,467,529
1,467,723
Is it possible to wrap a .net Stream as an stl std::ostream*?
I have an unmanaged c++ library that outputs text to an std::ostream*. I call this from a managed c++ wrapper that is used by a c# library. Currently I pass the unmanaged code a pointer to a std::stringstream and then later call System.String(stringstream.str().c_str()) to copy my unmanaged buffer back into a .net friendly string. Is it possible to wrap a .net Stream as an stl std::ostream*? - allowing me to stream text directly from my unmanaged code to a managed STREAM implementation.
If I understood correctly, you want to wrap a .NET stream with a C++ std stream, so that your native code streams into the C++ std stream, but the data ends up in the .NET stream. C++ IO streams roughly split into the streams themselves, which do all of the conversion between the C++ types and a binary representation, and the stream buffers, which buffer the data and read from/write to a device. What you would need to do in order to achieve you goal is to use a stream buffer that writes to a .NET stream. In order to do this, you need to create your own stream buffer, derived from std::stream_buffer, which internally references a .NET stream and forwards all data to it. This you pass to the std::ostream object which is passed to the native code. Writing your own stream buffer isn't a beginner's task, but it isn't particularly hard either. Pick any decent reference on C++ IO streams (Langer/Kreft is the best you can get on paper), find out which of the virtual functions you need to overwrite in order to do that, and you're done.
1,467,538
1,467,876
C++ Check if pointer is passed, else create one?
Okay i've seen this done somewhere before where you have a function that takes a pointer parameter and returns a pointer. However you can choose not to pass a parameter and it will return a dynamically allocated pointer but if you do pass a pointer then it just fills it in instead of creating one on the heap. This is a single function not overloaded. My question is how is this safely done? I had a guess it was something like this: point* funct(point *p = some_value) { if p == some_value //create a point *p on the heap else //create use the given *p and fill it in return p } Now i can't think if this is right way to do it and if it is then what could be a good some_value? it can't be NULL because when you pass empty pointer it will also be NULL and not sure if it is safe to have it greater than 0. Also you can't have negative numbers on pointers either, so whats a good safe value? Any good way to do this that is also PORTABLE across platforms? EDIT: Okay maybe i didn't explain properly basically i want the function to be used like this: point *x; point *y; x = func(); func(y); Not x = func(NULL); if I use NULL i get an error segmentation fault only when i do func(y); The reason for this is: either the user passes a pointer he manages such as one created on the stack OR the function will give a dynamic one back if none is given. I don't want to force the return of only dynamic memory or only accepting a pointer to fill. I know I have seen this done somewhere before.
You have to ask yourself why passing NULL us giving you a seg-fault. It is certainly not because NULL is not an appropriate value, it will be caused by whatever your code does when NULL is passed. However you chose not to show that code. Haver you stepped through this code in your debugger? Apart from that, in C++ do not use NULL. It is a macro and open to incorrect redefinition. Use plain zero (0). The language places guarantees that a zero literal constant when converted to a pointer will not be a valid address. The chances are that your NULL macro is in fact defined as zero. If you attempt to dereference a null pointer you will get a fault.
1,467,963
1,468,896
VCL forms application writing to stdout
My company has a large Windows application with a document-object model: open application, open a file, make some changes, save, close. I'm attempting to cut the GUI off of the top and create a console application that accepts some parameters, opens a file, does something useful, saves, closes the file, and terminates. Because there is a large amount of legacy code, I'm forced to use VCL forms application and launch it from the command line (or batch script). I really need to be able to print to stdout so I can write out status messages, respond to options like "--version" and "-?". I've spent all morning doing Google searches on this topic and I haven't found anything that's helpful. The application is written in CodeGear C++ Builder 2007 using the VCL.
You can write to STDOUT in a GUI program, there just usually won't be any output since there is no Console, unless it is launched from an actual Console. Alternatively, look at the GetStdHandle() and WriteConsole() functions in the Win32 API. If GetStdHandle() returns a valid handle, then you can write to it. This is particlarly useful if your GUI app is launched by another app that wants to intercept your STDOUT output for its own purposes.
1,468,000
1,468,214
boost scoped_lock. Will this lock?
solved I changed the bfs::directory_iterator Queue to a std::string queue, and surprisingly solved the problem. Hi, I have a gut feeling that i'm doing things wrong. I've implemented (or attempted to) the thread pool pattern. N threads read from a Queue, but i'm having some trouble. Here's what i got: //inside a while loop bool isEmpty; bfs::directory_iterator elem; { boost::mutex::scoped_lock lock(this->queue_mutex); isEmpty = this->input_queue.isEmpty(); if (!isEmpty){ elem= *(this->input_queue.pop()); } else{ continue; } } Will the scoped_lock still work inside the if's body? Im starting to believe that it wont (after running many tests). If not, is there any scoped way to do this (i.e not the explicit lock unlock way) Thanks in advance. update The code that adds elements to the queue looks like this //launches the above code, passing a reference to mutex and queue. Threads threads(queue,queue_mutex); for (bfs::directory_iterator dir_it:every file in directory){ boost::mutex::scoped_lock lock(queue_mutex); queue.push(dir_it); } Im placing a cout to control the poped filename, and if I push 2 files (file1) and (file2), and use 2 threads, I get boths "file2". class Threads{ boost::thread::thread_group group; Thread (N){ //also asigns a reference to a queue and a mutex. for(i 1..N){ //loop is posted above. group.add(new boost::thread(boost::bind(&loop,this))); } } };
The code as posted appears fine - if you're seeing problems maybe there's some other place where the lock should be taken and isn't (such as the code that adds something to the queue).
1,468,143
1,478,561
Using QFileSystemModel in a QCompleter
How does one use QFileSystemModel in the context of a QCompleter? It looks like a better choice than QDirModel as it is non UI-blocking. The following snippet doesn't seem to do anything. QLineEdit* l = new QLineEdit ; QCompleter* c = new QCompleter ; QFileSystemModel* m = new QFileSystemModel ; m->setRootPath( "c:\\" ) ; c->setModel( m ) ; l->setCompleter( c ) ;
Looks like it just hasn't been implemented yet. http://qt.nokia.com/developer/task-tracker/index_html?method=entry&id=221860
1,468,165
1,468,231
How to send a CBN_SELCHANGE message when using CB_SETCURSEL?
When using the CB_SETCURSEL message, the CBN_SELCHANGE message is not sent. How to notify a control that the selection was changed ? P.S. I found on the Sexchange site, a very ugly hack : SendMessage( hwnd, 0x014F/*CB_SHOWDROPDOWN*/, 1, 0 ); SendMessage( hwnd, 0x014E/*CB_SETCURSEL*/, ItemIndex, 0 ); SendMessage( hwnd, 0x0201/*WM_LBUTTONDOWN*/, 0, -1 ); SendMessage( hwnd, 0x0202/*WM_LBUTTONUP*/, 0, -1 ); Will do for now... Not really. P.S.2 For resolving my problem, I'll follow Ken's suggestion in the comments.
You're not supposed to use CBN_SELCHANGE unless the change in selection was made by the user. You don't indicate what language you're using; it would make it easier to provide you with a workaround if you did so. In Delphi, where an OnChange() would be associated with the combobox, you just call the event method directly: // Send the CB_SETCURSEL message to the combobox PostMessage(ComboBox1.Handle, CB_SETCURSEL, Whatever, WhateverElse); // Directly call the OnChange() handler, which is the equivalent to CBN_SELCHANGE ComboBox1Change(nil);
1,468,298
1,474,397
Is there any way to access all of the Clib functions from one file?
I'd like to include just one file instead of all of them, because the compiler I have to use does not include them by default.
Write a header that includes all standard headers and include it in your file. That would make compilation slow though.
1,468,662
1,489,278
OpenCV Vs ImageMagick?
I have an upcoming project which is about image segmentation i.e. to group the pixels constituting the image into clusters based on certain visual properties of the pixel. We plan to do it in C++ and have zeroed in on two image processing/manipulation libraries - OpenCV and ImageMagick. I'm reading on ImageMagick and it seems it has lot of APIs to manipulate the image. That's good but in our project we would be using quite a bit of linear algebra and matrix manipulations pertaining to the pixels forming the image, in order to get the segmentation done. I wonder whether ImageMagick has any support for that. How about OpenCV, how good it is to suit my needs?
I've used OpenCV for this type of task and have found it to work very well. It's well documented and has many of the types of operations that one typical needs for image analysis. I don't see how ImageMagick could even get you started on this. I'm assuming here that what you mean by "image segmentation" is grouping pixels into clusters based on their value and the values of neighbouring pixels. If you're just counting pixels properties independently and essentially just want to load an image into an matrix, it probably doesn't matter what you use; but to do any analysis, OpenCV is the way to go, or at least worth a good look. I suggest looking at some of the typical functions one needs, like Erode, Canny Edge Detection, Adaptive Thresholds, Contouring algorithms, etc, and check whether ImageMagick has any of these.
1,468,774
1,468,817
Why am I having problems recursively deleting directories?
I've written an application that uses the WIN32 api to create a temporarily directory hierarchy. Now, when wanting to delete the directories when shutting down the application I'm running into some problems. So lets say I have a directory hierarchy: C:\temp\directory\subdirectory\ I'm using this recursive function: bool Dir::deleteDirectory(std::string& directoryname, int flags) { if(directoryname.at(directoryname.size()-1) != '\\') directoryname += '\\'; if ((flags & CONTENTS) == CONTENTS) { WIN32_FIND_DATAA fdata; HANDLE dhandle; directoryname += "\\*"; dhandle = FindFirstFileA(directoryname.c_str(), &fdata); // Loop through all the files in the main directory and delete files & make a list of directories while(true) { if(FindNextFileA(dhandle, &fdata)) { std::string filename = fdata.cFileName; if(filename.compare("..") != 0) { std::string filelocation = directoryname.substr(0, directoryname.size()-2) + StringManip::reverseSlashes(filename); // If we've encountered a directory then recall this function for that specific folder. if(!isDirectory(filelocation)) DeleteFileA(filename.c_str()); else deleteDirectory(filelocation, DIRECTORY_AND_CONTENTS); } } else if(GetLastError() == ERROR_NO_MORE_FILES) break; } directoryname = directoryname.substr(0, directoryname.size()-2); } if ((flags & DIRECTORY) == DIRECTORY) { HANDLE DirectoryHandle; DirectoryHandle = CreateFileA(directoryname.c_str(), FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL); bool DeletionResult = (RemoveDirectoryA(directoryname.c_str()) != 0)?true:false; CloseHandle(DirectoryHandle); return DeletionResult; } return true; } This function iterates over the directory contents of the temp directory; and for each directory in the temp directory it keeps recalling itself until it's at the lowest directory; subdirectory in the example. There are also 3 flags defined enum DirectoryDeletion { CONTENTS = 0x1, DIRECTORY = 0x2, DIRECTORY_AND_CONTENTS = (0x1 | 0x2) }; When using this function, it only removes the lowest subdirectory and I can't remove the ones higher in hierarchy because it says that the directory is not empty. When I go and look to the directory 'subdirectory' is only removed after the application ends. However, when I try to encapsulate this in a non recursive simple main application I have no problems at all with deleting the directories.
You're not closing dhandle from all those FindFirstFile calls, so each directory has a reference to it when you try to delete it. And, why do you need to create DirectoryHandle? It's not needed, and will probably also block the directory deletion. When your app closes, those handles are forced close, and (I guess) the last attempted delete then succeeds.
1,469,033
1,469,089
How to initialize an array in a class constructor?
Working in Xcode on Mac OS X Leopard in C++: I have the following code: class Foo{ private: string bars[]; public: Foo(string initial_bars[]){ bars = initial_bars; } } It does not compile and throws the following error: error: incompatible types in assignment of 'std::string*' to 'std::string [0u]' I notice that removing the line bars = initial_bars; solves the problem. It seems like I am not doing the assignment correctly. How could I go about fixing this problem? EDIT: The variable bars is an array of strings. In the main function I initialize it like this: string bars[] = {"bar1", "bar2", "bar3"}; But it can contain an arbitrary number of members.
Arrays behave like const pointers, you can't assign pointers to them. You also can't directly assign arrays to each other. You either use a pointer member variable have a fixed size of bars you get and initialize your member array with its contents just use a reference to a std container like std::vector
1,469,149
1,469,166
Calculating vertices of a rotated rectangle
I am trying to calculate the vertices of a rotated rectangle (2D). It's easy enough if the rectangle has not been rotated, I figured that part out. If the rectangle has been rotated, I thought of two possible ways to calculate the vertices. Figure out how to transform the vertices from local/object/model space (the ones I figured out below) to world space. I honestly have no clue, and if it is the best way then I feel like I would learn a lot from it if I could figure it out. Use trig to somehow figure out where the endpoints of the rectangle are relative to the position of the rectangle in world space. This has been the way I have been trying to do up until now, I just haven't figured out how. Here's the function that calculates the vertices thus far, thanks for any help void Rect::calculateVertices() { if(m_orientation == 0) // if no rotation { setVertices( &Vertex( (m_position.x - (m_width / 2) * m_scaleX), (m_position.y + (m_height / 2) * m_scaleY), m_position.z), &Vertex( (m_position.x + (m_width / 2) * m_scaleX), (m_position.y + (m_height / 2) * m_scaleY), m_position.z), &Vertex( (m_position.x + (m_width / 2) * m_scaleX), (m_position.y - (m_height / 2) * m_scaleY), m_position.z), &Vertex( (m_position.x - (m_width / 2) * m_scaleX), (m_position.y - (m_height / 2) * m_scaleY), m_position.z) ); } else { // if the rectangle has been rotated.. } //GLfloat theta = RAD_TO_DEG( atan( ((m_width/2) * m_scaleX) / ((m_height / 2) * m_scaleY) ) ); //LOG->writeLn(&theta); }
I would just transform each point, applying the same rotation matrix to each one. If it's a 2D planar rotation, it would look like this: x' = x*cos(t) - y*sin(t) y' = x*sin(t) + y*cos(t) where (x, y) are the original points, (x', y') are the rotated coordinates, and t is the angle measured in radians from the x-axis. The rotation is counter-clockwise as written. My recommendation would be to do it out on paper once. Draw a rectangle, calculate the new coordinates, and redraw the rectangle to satisfy yourself that it's correct before you code. Then use this example as a unit test to ensure that you coded it properly.
1,469,211
1,469,243
Unmanaged dll call to crash a dotnet app?
As part of segmenting my app into separate appdomains in order to catch and recover from an intermittent crash when calling a native dll, I need a way to reliably trigger this type of crash in order to determine if I am catching the appdomain going down correctly. I'm looking for some simple native code (C++ ?) I can compile into a dll, and call from my dotnet code with the expectation it'll take the dotnet code down with it. Any suggestions?
Just make a native C++ function that does anything bad, such as divide by zero, ie: void BeABadMethod() { int i = 5; int j = 0; printf("%d", i/j); }
1,469,370
1,469,445
Why can't I import the 'math' library when embedding python in c?
I'm using the example in python's 2.6 docs to begin a foray into embedding some python in C. The example C-code does not allow me to execute the following 1 line script: import math Using line: ./tmp.exe tmp foo bar it complains Traceback (most recent call last): File "/home/rbroger1/scripts/tmp.py", line 1, in <module> import math ImportError: [...]/python/2.6.2/lib/python2.6/lib-dynload/math.so: undefined symbol: PyInt_FromLong When I do nm on my generated binary (tmp.exe) it shows 0000000000420d30 T PyInt_FromLong The function seems to be defined, so why can't the shared object find the function?
I'm using Python 2.6, and I successfully compiled and ran that same example code that you listed, without changing anything in the source. $ gcc python.c -I/usr/include/python2.6/ /usr/lib/libpython2.6.so $ ./a.out random randint 1 100 Result of call: 39 $ ./a.out random randint 1 100 Result of call: 57 I specifically chose the random module because it does have from math import log,... so it is certainly importing the math module as well. Your issue is probably due to how you're linking; see this forum post for a similar issue someone else had. I can't find the links again, but it seems like there are some common issues when trying to link against Python's static library then importing modules that require a dynamic library.
1,469,635
1,469,644
SDL: Initializng TTF problems. Possibly freetype?
Edited: Look at comments below. Short version: Screen simply flashes when I try to run program. int main(int argc, char** args) { bool quit = false; std::ofstream out("error.txt"); if(init() == false) { return 1; } if (load_files() == false) { return 1; } // Render the text message = TTF_RenderText_Solid(font, "The quick brown fox jumps over the lazy dog", textColor); // If there was an error in rendering the text if (message == NULL) { return 1; } // Apply the images to the screen apply_surface(0,0, background, screen); apply_surface(0,150, message, screen); // Update the screen if (SDL_Flip(screen) == -1) { std::cout << SDL_GetError() << '\n'; return 1; } while (quit == false) { while (SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { quit = true; } } } clean_up(); return 0; }
What's the problem you're having? Is it failing to compile? Failing to link? Failing at program load time due to missing DLLs/shared libraries? Or failing at runtime? Is screen NULL after the call to SDL_SetVideoMode()? If so, you should print out SDL_GetError(). If it is in fact TTF_Init() that is failing, then what is the error message that is printed?
1,469,687
1,469,748
Lookup table where most sequential values point to the same object?
Suppose I have a range of keys, say 0 -> 1000 Say 0 - > 99 map to one object 100 -> 251 map to another etc. etc. What is a good way to map a key to an object without having to have an array of 1000 size and a bunch of if (x >= 0 && x <= 99) business? I mean without any logic i.e. a stairstep table
Use a std::map along with lower_bound: map<long, string> theMap; theMap[0] = "lessThan1"; theMap[99] = "1to99"; theMap[1000] = "100to1000"; theMap[numeric_limits<long>::max()] = "greaterThan1000"; cout << theMap.lower_bound(0)->second << endl; // outputs "lessThan1" cout << theMap.lower_bound(1)->second << endl; // outputs "1to99" cout << theMap.lower_bound(50)->second << endl; // outputs "1to99" cout << theMap.lower_bound(99)->second << endl; // outputs "1to99" cout << theMap.lower_bound(999)->second << endl; // outputs "100to1000" cout << theMap.lower_bound(1001)->second << endl; // outputs "greaterThan1000" Wrap it up in your own class to hide the details and you're good to go.
1,469,743
1,469,766
Standard Library Containers with additional optional template parameters?
Having read the claim multiple times in articles - I want to add this question to Stackoverflow, and ask the community - is the following code portable? template<template<typename T, typename Alloc> class C> void f() { /* some code goes here ... */ } int main() { f<std::vector>(); } Is the implementation that supplies std::vector really allowed to have additional, defaulted template parameters beyond the two well known ones? This would render the above code ill-formed, as it assumes two template parameters. See the last paragraph in this article for an example of such a claim.
I found the following issue report, which says There is no ambiguity; the standard is clear as written. Library implementors are not permitted to add template parameters to standard library classes. This does not fall under the "as if" rule, so it would be permitted only if the standard gave explicit license for implementors to do this. This would require a change in the standard. The LWG decided against making this change, because it would break user code involving template template parameters or specializations of standard library class templates. The books and people that say an implementation may add other optional parameters seem to be wrong.