question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,595,770
2,595,839
Exposing an ISO C++ class to C#
I need to expose some C++ classes to C# (I am building on Linux, using mono, so COM is not an option) The evidence I have gathered so far suggests that the best way to approach this is: Write a wrapper C++.Net class around the ISO C++ class Consume the C++.Net classes from C# I have the following questions: First, is this the "best" way of achieving the goal of exposing ISO C++ classes to C# ? So far though, I have not seen any examples that actually show how to do this - can anyone suggest some links, or a code snippet to show how this is done for a dummy class? How may I send asynchronous message notifications from the C++ code to the C# code ?. Ideally, I would like to cause the C# class to raise an event, with the received data as an argument
You can't do C++/.NET classes on Linux using Mono. Mono doesn't support Managed C++ or C++/CLI, so there is no way to "Write a wrapper C++.Net class around the ISO C++ class". Your best option for this is to generate a C API for your C++ class, which can be accessed via Platform Invoke. That being said, one option for easing this is to use SWIG to generate the wrappers for you. It supports generation of C# wrappers from C++ classes (as well as wrappers to other languages), and works well on Linux/Mono. Edit: For an official "Mono doesn't support mixed mode C++/CLI", see the Languages page: It's important to note that any language that compiles to pure IL should work under Mono. Some languages such as Microsoft's Managed C++ do not always compile to pure IL, so they will not always work as expected, since they are not truly platform independent. C++/CLI for native interop requires non-pure IL, so it will not work on Mono.
2,595,849
2,595,884
how can i inherit from both QWidget and QThread?
I have a class like this class GUI : public QWidget, public QThread When I do the above i get errors about connect signals. The error says Reference to "connect" is ambiguous. Is there a way to inherit from both? Thank you
You can't. Both QWidget and QThread inherit (non-virtually) from QObject. You therefore do not have virtual derivation, thus two copies of QObject, which confuses the compiler. QObject was specifically designed this way. See: http://lists.trolltech.com/qt-interest/2006-10/msg00711.html http://www.qtforum.org/article/23295/problem-opening-the-qfiledialog.html There are some who allegedly went around this (can't find the link right now, but it's out there on Google, I had the same trouble two weeks ago), but it is unsafe at best. Edit: the best way would probably be to have another object inherit from QThread and keep that object as a member in your GUI class. That is the sort of workaround most people do in this matter.
2,595,920
2,596,280
C++ allocators, specifically passing constructor arguments to objects allocated with boost::interprocess::cached_adaptive_pool
This is an embarrassing question, but even the well-written documentation provided with boost.interprocess hasn't been enough for me to figure out how to do this. What I have is a cached_adaptive_pool allocator instance, and I want to use it to construct an object, passing along constructor parameters: struct Test { Test(float argument, bool flag); Test(); }; // Normal construction Test obj(10, true); // Normal dynamic allocation Test* obj2 = new Test(20, false); typedef managed_unique_ptr< Test, boost::interprocess::managed_shared_memory>::type unique_ptr; // Dynamic allocation where allocator_instance == cached_adaptive_pool, // using the default constructor unique_ptr obj3 = allocator_instance.allocate_one() // As above, but with the non-default constructor unique_ptr obj4 = allocator_instance ... ??? This may very well be a failure on my part on how to use allocator objects in general. But in any case, I cannot see how to use this specific allocator, with the interface specified in cached_adaptive_pool to pass constructor arguments to my object. cached_adaptive_pool has the method: void construct(const pointer & ptr, const_reference v) but I don't understand what that means and I can't find examples using it. My head has been swimming in templates all day, so a helping hand, even if the answer is obvious, will be greatly appreciated.
cached_adaptive_pool has the method: void construct(const pointer & ptr, const_reference v) but I don't understand what that means and I can't find examples using it. It should follow the interface of std::allocator, in which case allocate() gives you a suitable chunk of uninitialized memory and construct() calls placement new on the given pointer. Something like: allocator_instance.construct(allocator_instance.allocate_one(), Test(30, true)); Haven't used those pools myself, though. In C++0x, allocators should be able to call any constructor, not just the copy constructor, so it might be that boost's allocators already support this to an extent. a.construct(p, 30, true); //a C++0x allocator would allow this and call new (p) Test(30, true)
2,596,275
2,600,141
How to export C++ functions with GCC?
I'm using Code::Blocks to compile a shared library on Ubuntu. When I make a simple main.c file with: void* CreateInterface() { int* x = (int*)malloc( sizeof( int ) ); *x = 1337; return x; } This works fine and I can find the function CreateInterface with dlsym in another application. However, I want the function to create an instance of a class written in C++. I tried the following: #include "IRender.h" extern "C" { void* CreateInterface() { return new Flow::Render::IRender(); } } This compiled fine, but now my other application fails to find CreateInterface. How should I deal with this?
I've solved the problem by making a .cpp file with the declaration: extern "C" void* CreateInterface() { return new Flow::Render::IRender(); } and a .c file with the header like this: extern void* CreateInterface();
2,596,450
2,596,472
#define and how to use them - C++
In a pre-compiled header if I do: #define DS_BUILD #define PGE_BUILD #define DEMO then in source I do: #if (DS_BUILD && DEMO) ---- code--- #elif (PGE_BUILD && DEMO) --- code--- #else --- code --- #endif Do I get an error that states: error: operator '&&' has no right operand I have never seen this before. I am using XCode 3.2, GCC 4.2 on OS X 10.6.3
You need to add the defined keyword since you want to check that you defined have been defined. #if defined (DS_BUILD) && defined (DEMO) ---- code--- #elif defined (PGE_BUILD) && defined (DEMO) --- code--- #else --- code --- #endif
2,596,470
2,596,487
Importing a DllMain winapi .dll into Visual Studio project C++
I have the .def file, .lib file, the .dll, the source files. It's using WINAPI DllMain, all its functions follow that. It's like this: BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; } extern "C" { int WINAPI DoSomething() { return -1; } int WINAPI DOSOMETHIGNELSE!() { return 202020; } }; IN the project settings linker I added the .lib file. There is no header file for the actual functions in the extern "C" part. I include windows.h try to call DoSomething() but doesnt know what it is.
I'm not sure exactly what you're asking for, but I think at the least you'll need to create a .h file for client code to include so it can call functions in the the DLL - otherwise how will the compiler know what the name DoSomething is? The header file should probably look something like: #ifndef DOSOMETHING_H #define DOSOMETHING_H #ifdef __cplusplus extern "C" { #endif int WINAPI DoSomething(void); // I commented out the 2nd function because I don't think the `!` character // could ever be valid there //int WINAPI DOSOMETHIGNELSE!(); #ifdef __cplusplus } #endif #endif /* DOSOMETHING_H */
2,596,500
2,596,549
Circumvent c++ null-terminated string frustration
I'm using boost::program_options and it suffers from the same as many other c++ libs, even std itself: It still uses C-style null-terminated strings, because nobody really likes the weak std::string. The method in question is: options_description_easy_init& operator()(const char* name, const value_semantic* s, const char* description); The typical use case is just fine: options.add_options() ("graphical", bool_switch(&isGraphical)->default_value(false), "Show any graphical output during runtime") However, I need the name of the option to be set dynamically. The reason is that in some cases I nead a custom prefix, which is added to the string by my function std::string key(const std::string& k): options.add_options() (key("graphical"), bool_switch(&isGraphical)->default_value(false), "Show any graphical output during runtime") This fails. I could now use c_str() on the std::string but that's evil -- I don't know how long program_options keeps the variable around and if my string is still alive when needed. I could also reserve memory in a buffer etc. and hand in that. The buffer is never freed and it sucks/is evil. Is there anything else I can do to circumvent the C-style string mess in this situation?
It's pretty strong convention to not hold on to const char*'s beyond the life of a function call like this. As long as they're not bucking this convention, .c_str() is the expected and best way to do what you're trying to do IMO. options.add_options() (key("graphical").c_str(), bool_switch(&isGraphical)->default_value(false), "Show any graphical output during runtime")
2,596,522
2,596,551
C++ standard input from file when debugging from IDE
I'm using VS 2010, and I'm wondering how I can get my c++ program to read a file using standard input while debugging. I know how to do it from command prompt, but not when debugging. Basically I want it to read in a file with cin>> instead of me typing stuff - but in debug mode.
If you go into the project's Properties, under Debugging there's a set of options for how to actually launch the process. IIRC the way to do this is to put: < yourfile.txt In the Command Arguments box.
2,596,588
2,596,633
MFC/CCriticalSection: Simple lock situation hangs
I have to program a simple threaded program with MFC/C++ for a uni assignment. I have a simple scenario in wich i have a worker thread which executes a function along the lines of : UINT createSchedules(LPVOID param) { genProgThreadVal* v = (genProgThreadVal*) param; // v->searcherLock is of type CcriticalSection* while(1) { if(v->searcherLock->Lock()) { //do the stuff, access shared object , exit clause etc.. v->searcherLock->Unlock(); } } PostMessage(v->hwnd, WM_USER_THREAD_FINISHED , 0,0); delete v; return 0; } In my main UI class, i have a CListControl that i want to be able to access the shared object (of type std::List). Hence the locking stuff. So this CList has an handler function looking like this : void Ccreationprogramme::OnLvnItemchangedList5(NMHDR *pNMHDR, LRESULT *pResult) { LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR); if((pNMLV->uChanged & LVIF_STATE) && (pNMLV->uNewState & LVNI_SELECTED)) { searcherLock.Lock(); // do the stuff on shared object searcherLock.Unlock(); // do some more stuff } *pResult = 0; } The searcherLock in both function is the same object. The worker thread function is passed a pointer to the CCriticalSection object, which is a member of my dialog class. Everything works but, as soon as i do click on my list, and so triggers the handler function, the whole program hangs indefinitely.I tried using a Cmutex. I tried using a CSingleLock wrapping over the critical section object, and none of this has worked. What am i missing ? EDIT: I found the solution, thanks to the amazing insight of Franci. That'll teach me to not put every bit of the code into the question. Thanks !
Are you sure the background thread is not doing anything that would SendMessage to the UI thread between the Lock and Unlock? If it does, it'll be blocked until the message queue processes that message; however, the message queue will never get to it, since it's blocked in the middle of processing the item changed notification of the list view.
2,596,863
2,596,878
How to process all #include directives in Visual Studio C++ 2005?
I want to see how my #include files be processed when Microsoft Visual Studio C++ compile it. As I remember, there is a compile option to inline all #includes and #define lines but I can't find it. I use MSVC 2005 sp1.
The option you are looking for is under your project properties, "C/C++", "Preprocessor" then change "Generate Preprocessed File" to "With Line Numbers" or "Without Line Numbers", whatever you want.
2,596,909
2,596,940
What's correct way to remove a boost::shared_ptr from a list?
I have a std::list of boost::shared_ptr<T> and I want to remove an item from it but I only have a pointer of type T* which matches one of the items in the list. However I cant use myList.remove( tPtr ) I'm guessing because shared_ptr does not implement == for its template argument type. My immediate thought was to try myList.remove( shared_ptr<T>(tPtr) ) which is syntactically correct but it will crash from a double delete since the temporary shared_ptr has a separate use_count. std::list< boost::shared_ptr<T> > myList; T* tThisPtr = new T(); // This is wrong; only done for example code. // stand-in for actual code in T using // T's actual "this" pointer from within T { boost::shared_ptr<T> toAdd( tThisPtr ); // typically would be new T() myList.push_back( toAdd ); } { //T has pointer to myList so that upon a certain action, // it will remove itself romt the list //myList.remove( tThisPtr); //doesn't compile myList.remove( boost::shared_ptr<T>(tThisPtr) ); // compiles, but causes // double delete } The only options I see remaining are to use std::find with a custom compare, or to loop through the list brute force and find it myself, but it seems there should be a better way. Am I missing something obvious, or is this just too non-standard a use to be doing a remove the clean/normal way?
enable_shared_from_this can help with your problem, but it will require that the types you're using in the list derive from it: http://www.boost.org/doc/libs/1_42_0/libs/smart_ptr/enable_shared_from_this.html If the type enables that functionality, you can get the shared pointer from the object itself by calling shared_from_this().
2,596,934
2,598,483
How to draw an Arc in OpenGL
While making a little Pong game in C++ OpenGL, I decided it'd be fun to create arcs (semi-circles) when stuff bounces. I decided to skip Bezier curves for the moment and just go with straight algebra, but I didn't get far. My algebra follows a simple quadratic function (y = +- sqrt(mx+c)). This little excerpt is just an example I've yet to fully parameterize, I just wanted to see how it would look. When I draw this, however, it gives me a straight vertical line where the line's tangent line approaches -1.0 / 1.0. Is this a limitation of the GL_LINE_STRIP style or is there an easier way to draw semi-circles / arcs? Or did I just completely miss something obvious? void Ball::drawBounce() { float piecesToDraw = 100.0f; float arcWidth = 10.0f; float arcAngle = 4.0f; glBegin(GL_LINE_STRIP); for (float i = 0.0f; i < piecesToDraw; i += 1.0f) // Positive Half { float currentX = (i / piecesToDraw) * arcWidth; glVertex2f(currentX, sqrtf((-currentX * arcAngle)+ arcWidth)); } for (float j = piecesToDraw; j > 0.0f; j -= 1.0f) // Negative half (go backwards in X direction now) { float currentX = (j / piecesToDraw) * arcWidth; glVertex2f(currentX, -sqrtf((-currentX * arcAngle) + arcWidth)); } glEnd(); } Thanks in advance.
What is the purpose of sqrtf((-currentX * arcAngle)+ arcWidth)? When i>25, that expression becomes imaginary. The proper way of doing this would be using sin()/cos() to generate the X and Y coordinates for a semi-circle as stated in your question. If you want to use a parabola instead, the cleaner way would be to calculate y=H-H(x/W)^2
2,596,953
2,596,970
Multiply char by integer (c++)
Is it possible to multiply a char by an int? For example, I am trying to make a graph, with *'s for each time a number occurs. So something like, but this doesn't work char star = "*"; int num = 7; cout << star * num //to output 7 stars
I wouldn't call that operation "multiplication", that's just confusing. Concatenation is a better word. In any case, the C++ standard string class, named std::string, has a constructor that's perfect for you. string ( size_t n, char c ); Content is initialized as a string formed by a repetition of character c, n times. So you can go like this: char star = '*'; int num = 7; std::cout << std::string(num, star) << std::endl; Make sure to include the relevant header, <string>.
2,597,116
2,597,398
Is extending a base class with non-virtual destructor dangerous?
In the following code: class A { }; class B : public A { }; class C : public A { int x; }; int main (int argc, char** argv) { A* b = new B(); A* c = new C(); //in both cases, only ~A() is called, not ~B() or ~C() delete b; //is this ok? delete c; //does this line leak memory? return 0; } When calling delete on a class with a non-virtual destructor with member functions (like class C), can the memory allocator tell what the proper size of the object is? If not, is memory leaked? Secondly, if the class has no member functions, and no explicit destructor behaviour (like class B), is everything ok? I ask this because I wanted to create a class to extend std::string, (which I know is not recommended, but for the sake of the discussion just bear with it), and overload the +=, + operator. -Weffc++ gives me a warning because std::string has a non virtual destructor, but does it matter if the sub-class has no members and does not need to do anything in its destructor? FYI the += overload was to do proper file path formatting, so the path class could be used like: class path : public std::string { //... overload, +=, + //... add last_path_component, remove_path_component, ext, etc... }; path foo = "/some/file/path"; foo = foo + "filename.txt"; std::string s = foo; //easy assignment to std::string some_function_taking_std_string (foo); //easy implicit conversion //and so on... I just wanted to make sure someone doing this: path* foo = new path(); std::string* bar = foo; delete bar; would not cause any problems with memory allocation?
So everyone has been saying you cant do it - it leads to undefined behaviour. However there are some cases where it is safe. If you are never creating instances of your class dynamically then you should be OK. (i.e. no new calls) That said, it is generally considered a bad thing to do as someone might try to create one polymorphically at some later date. ( You may be able to protect against this by having a private unimplemented operator new, but I'm not sure. ) I have two examples where I don't hate deriving from classes with non-virtual destructors. The first is creating syntactic sugar using temporaries ... here's a contrived example. class MyList : public std::vector<int> { public: MyList operator<<(int i) const { MyList retval(*this); retval.push_back(i); return retval; } private: // Prevent heap allocation void * operator new (size_t); void * operator new[] (size_t); void operator delete (void *); void operator delete[] (void*); }; void do_somthing_with_a_vec( std::vector<int> v ); void do_somthing_with_a_const_vec_ref( const std::vector<int> &v ); int main() { // I think this slices correctly .. // if it doesn't compile you might need to add a // conversion operator to MyList std::vector<int> v = MyList()<<1<<2<<3<<4; // This will slice to a vector correctly. do_something_with_a_vec( MyList()<<1<<2<<3<<4 ); // This will pass a const ref - which will be OK too. do_something_with_a_const_vec_ref( MyList()<<1<<2<<3<<4 ); //This will not compile as MyList::operator new is private MyList * ptr = new MyList(); } The other valid usage I can think of comes from the lack of template typedefs in C++. Here's how you might use it. // Assume this is in code we cant control template<typename T1, typename T2 > class ComplicatedClass { ... }; // Now in our code we want TrivialClass = ComplicatedClass<int,int> // Normal typedef is OK typedef ComplicatedClass<int,int> TrivialClass; // Next we want to be able to do SimpleClass<T> = ComplicatedClass<T,T> // But this doesn't compile template<typename T> typedef CompilicatedClass<T,T> SimpleClass; // So instead we can do this - // so long as it is not used polymorphically if // ComplicatedClass doesn't have a virtual destructor we are OK. template<typename T> class SimpleClass : public ComplicatedClass<T,T> { // Need to add the constructors we want here :( // ... private: // Prevent heap allocation void * operator new (size_t); void * operator new[] (size_t); void operator delete (void *); void operator delete[] (void*); } Heres a more concrete example of this. You want to use std::map with a custom allocator for many different types, but you dont want the unmaintainable std::map<K,V, std::less<K>, MyAlloc<K,V> > littered through your code. template<typename K, typename V> class CustomAllocMap : public std::map< K,V, std::less<K>, MyAlloc<K,V> > { ... private: // Prevent heap allocation void * operator new (size_t); void * operator new[] (size_t); void operator delete (void *); void operator delete[] (void*); }; MyCustomAllocMap<K,V> map;
2,597,157
2,597,341
Get a QWidget to take up the entire QMainWindow
I have a class that inherits QMainWindow and I just want it to have a webview widget and nothing else, so here's what I tried doing for constructor: MyWindow::MyWindow(QWidget *parent) : QMainWindow(parent) { this->_webView = new QWebView(this); this->setCentralWidget(this->_webView); } This didnt work do I have to use some kind of layout to make this fill?
Just get rid of the QMainWindow and use QWebView as the top level widget. If you're not going to use any of the features of QMainWindow then there's no reason to use it.
2,597,534
2,597,664
Is there a way to display icons in QListView without text?
Using a QListView, and QStandardItemModel, is it possible to display icons in the list view without displaying the associated text? QStandardItem is defined as so: QStandardItem ( const QIcon & icon, const QString & text ) So it seems to require a text string of some sort - I only want the icon displayed. If I use the following code, I get the icons as requested, but I also get a blank text element underneath them. I don't want this. ImageListView->setViewMode( QListView::IconMode ); { QStandardItemModel *iStandardModel = new QStandardItemModel(this); QStandardItem* item1 = new QStandardItem(QIcon("images/shield-280x280.png"),""); QStandardItem* item2 = new QStandardItem(QIcon("images/shield-280x280.png"),""); iStandardModel->appendRow(item1); iStandardModel->appendRow(item2); ImageListView->setIconSize(QSize(100,100)); ImageListView->setUniformItemSizes(true); ImageListView->setDragDropMode(QAbstractItemView::DropOnly); ImageListView->setModel(iStandardModel); } If I go to the trouble of building a custom model, can I resolve this issue?
Yes, you can do. first you create a delegate associated with the list-view.Then, While inserting the elements to the listview, use set-data function to insert the icon and in the paint event of delegate you handle the drawing icon. i hope its clear.
2,597,996
2,598,041
precompiled header .pch files are machine sensitive?
I tried to reuse the .pch to speed the build using the following way: use /Yc on stdafx.cpp to create the .pch files to a folder exclude stdafx.cpp in the project, and modify the link option It success in my machine, but failed in another, got the error message: error C2011: '***' : 'struct' type redefinition So first I want to ask whether the .pch files are machine sensitive? then secondly, the above approaches workable? Thanks!
Precompiled headers can be machine specific up to Visual Studio 2008 SP1 (from here): Precompiled header files store the “state” of a compilation up to a certain point, and that state information can be reused in subsequent compiler invocations to significantly increase build throughput. For the past 15 years, our compiler has persisted precompiled headers to disk and reloaded them directly into virtual memory with 99.999% reliability and considerable performance gains. The tradeoff, however, was a degree of fragility in our architecture. Since the PCH file itself contains internal pointers, it must be loaded at the exact same address in virtual memory where it was created.
2,598,084
2,598,093
Function with missing return value, behavior at runtime
As expected, the compiler (VisualStudio 2008) will give a warning warning C4715: 'doSomethingWith' : not all control paths return a value when compiling the following code: int doSomethingWith(int value) { int returnValue = 3; bool condition = false; if(condition) // returnValue += value; // DOH return returnValue; } int main(int argc, char* argv[]) { int foo = 10; int result = doSomethingWith(foo); return 0; } But the program runs just fine. The return value of function doSomethingWith() is 0. Is is just undefined behavior, or is there a certain rule how the result value is created/computed at runtime. What happens with non-POD datatypes as return value?
It is Undefined behaviour as specified in the ISO C++ standard section 6.6.3: Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.
2,598,132
2,598,140
length of va_list when using variable list arguments?
Is there any way to compute length of va_list? All examples I saw the number of variable parameters is given explicitly.
There is no way to compute the length of a va_list, this is why you need the format string in printf like functions. The only functions macros available for working with a va_list are: va_start - start using the va_list va_arg - get the next argument va_end - stop using the va_list va_copy (since C++11 and C99) - copy the va_list Please note that you need to call va_start and va_end in the same scope which means you cannot wrap it in a utility class which calls va_start in its constructor and va_end in its destructor (I was bitten by this once). For example, this class is worthless: class arg_list { va_list vl; public: arg_list(const int& n) { va_start(vl, n); } ~arg_list() { va_end(vl); } int arg() { return static_cast<int>(va_arg(vl, int)); } }; GCC outputs the following error t.cpp: In constructor arg_list::arg_list(const int&): Line 7: error: va_start used in function with fixed args compilation terminated due to -Wfatal-errors.
2,598,178
2,598,272
Is there any reasonable use of a function returning an anonymous struct?
Here is an (artificial) example of using a function that returns an anonymous struct and does "something" useful: #include <iostream> template<typename T> T* func(T* t, float a, float b) { if(!t) { t = new T; t->a = a; t->b = b; } else { t->a += a; t->b += b; } return t; } struct { float a, b; }* foo(float a, float b) { if(a==0) return 0; return func(foo(a-1,b), a, b); } int main() { std::cout << foo(5,6)->a << std::endl; std::cout << foo(5,6)->b << std::endl; void* v = (void*)(foo(5,6)); //[1] delete f now because I know struct is floats only. float* f = (float*)(v); std::cout << f[0] << std::endl; std::cout << f[1] << std::endl; delete[] f; return 0; } There are a few points I would like to discuss: As is apparent, this code leaks, is there anyway I can NOT leak without knowing what the underlying struct definition is? see Comment [1]. I have to return a pointer to an anonymous struct so I can create an instance of the object within the templatized function func, can I do something similar without returning a pointer? I guess the most important, is there ANY (real-world) use for this at all? As the example given above leaks and is admittedly contrived. By the way, what the function foo(a,b) does is, to return a struct containing two numbers, the sum of all numbers from 1 to a and the product of a and b. Maybe the line new T could use a boost::shared_ptr somehow to avoid leaks, but I haven't tried that. Would that work? I think I was just trying to delete the anonymous struct as an array of floats, something like float* f = new float[2]. Which might be wrong, as the comment below suggests, so what can be done? can I delete at all? I can compile and run this code "as-is" on VS2008, maybe some non-standard extensions might be being used by VS, but it does run and gives 15 and 30 as the answer. From the answers I believe this contraption is a VS2008 specific entity, it is not standards compliant and thus not portable. Too bad though, I would have liked to see what voodoo the Stackoverflow or Boost people came up with if this was in their arsenal :). Thanks all.
For now, your code is not portable; it will, for example, not build with gcc. Section 14.3.1/2 of the standard says: A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template- argument for a template type-parameter. See item 488 in the C++ Standard Core Language Defect Reports, Revision 69 and Paper N2657 for one possible evolution. UPDATE 1 Assuming that your code were well-formed, then: you may be able to rewrite: std::cout << foo(5,6)->a << std::endl; as std::cout << std::auto_ptr(foo(5,6))->a << std::endl; you may return an anonymous struct by-value provided that the anonymous struct had a constructor taking another type (anonymous or not, that you'd be able to initialize inside the body of your method) -- except, of course, how do you specify a constructor for an anonymous struct? :) no real-world use that I can see other than an extremely convoluted way of trying not to assign an explicit name to the structure; one would typically use anonymous structs (not technically legal in C++, but supported by various compilers as extensions) in order to not pollute the namespace, typically by instantiating one right away (you may for example see one-shot functors being instantiated and passed down as anonymous structs -- again, technically not legal C++.) UPDATE 2 Thank you gf for the link to the relevant portion of the C++ standard concerning new types which may not be defined in a return type. UPDATE 3 Bringing this one out here from the comments: calling delete[] on memory allocated with new (as opposed to new[]) is an invitation to heap corruption. Calling delete on a pointer whose type you do not know is technically undefined (which destructor should get called?) but in the case of PODs (your anonymous struct being one) you can get away with it in this horrible hackish way: delete (int*)f; Of course, were your code magically well-formed, std::auto_ptr would have been able to retain the anonymous type and would have taken care of calling delete for you correctly and gracefully.
2,598,394
2,598,538
Timestamp issue with localtime and mktime
Please see the code below: #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; int main(void) { time_t current_time = 1270715952; cout << "Subscriber current timestamp:" << current_time << endl; tm* currentTm = localtime(&current_time); char tmp_str[256]; //2010-04-08T11:39:12 snprintf(tmp_str, sizeof(tmp_str), "%04d%02d%02d%02d%02d%02d.000", currentTm->tm_year+1900, currentTm->tm_mon+1, currentTm->tm_mday, currentTm->tm_hour, currentTm->tm_min, currentTm->tm_sec); cout << "Subscriber current date:" << tmp_str << endl; tm tmpDateScheduleFrom, tmpDateScheduleTo; memset(&tmpDateScheduleFrom, 0, sizeof(tm)); memset(&tmpDateScheduleTo, 0, sizeof(tm)); //2010-04-08T11:00 tmpDateScheduleFrom.tm_sec = 0; tmpDateScheduleFrom.tm_min = 0; tmpDateScheduleFrom.tm_hour = 11; tmpDateScheduleFrom.tm_mday = 8; tmpDateScheduleFrom.tm_mon = 3; tmpDateScheduleFrom.tm_year = 110; //2010-04-08T12:00 tmpDateScheduleTo.tm_sec = 0; tmpDateScheduleTo.tm_min = 0; tmpDateScheduleTo.tm_hour = 12; tmpDateScheduleTo.tm_mday = 8; tmpDateScheduleTo.tm_mon = 3; tmpDateScheduleTo.tm_year = 110; time_t localFrom = mktime(&tmpDateScheduleFrom); time_t localTo = mktime(&tmpDateScheduleTo); cout << "Subscriber current timestamp:" << current_time << endl; cout << "Subscriber localFrom:" << localFrom << endl; cout << "Subscriber localTo:" << localTo << endl; return 0; } The results are the following: Subscriber current timestamp:1270715952 Subscriber current date:20100408113912.000 Subscriber current timestamp:1270715952 Subscriber localFrom:1270717200 Subscriber localTo:1270720800 Why the current subscriber timestamp (subscriber date and time: 2010-04-08T11:39:12) is not between the range localFrom (timestamp of date/time: 2010-04-08T11:00:00) and LocalTo (timestamp of date/time: 2010-04-08T12:00:00)?
I think the problem is that you set tm_isdst to 0, which means no DST, however localtime() uses system-wide DST settings. If you set tm_isdst to 1, everything should be ok. According to man mktime, you can set negative value for tm_isdst if you are not sure about it. man doesn't say it explicitly but I guess in this case mktime() will use system settings as well, just like localtime().
2,598,401
2,599,608
C++: Failure to get data through pipe when using wide strings in both programs
I’m trying to use the following code in C++ on Mac OS X Snow Leopard to get the output of an external program through a pipe. FILE * al = popen("program program.cfg", "r"); string data; char buffer[100]; while (fgets(buffer, 100, al) != NULL) data.append(buffer); cout << "«" << data << "»" << endl; pclose(al); However, no data gets printed out. I suspect the problem lies in the fact that the external program outputs to wcout and wclog, but I’m not sure how to deal with it. I also tried using a wstring and fgetws, but that didn’t help either. I read about using boost::iostreams and again had no luck: FILE * al = popen("program program.cfg", "r"); boost::iostreams::file_descriptor_source alDesc(fileno(al)); boost::iostreams::stream_buffer<boost::iostreams::file_descriptor_source> alStream(alDesc); istream align(&alStream); string alignOutput; while (align) { getline(align, alignOutput); cout << "«" << alignOutput << "»" << endl; } align >> alignOutput; alStream.close(); alDesc.close(); pclose(al); Does anyone have a clue as to what the actual problem might be and how to resolve it? In case someone might ask, both the external program and the one reading from the pipe need to use wstring as I’m dealing with data that might be in any language, including Chinese etc. Thanks in advance for any clues!
It turned out that I was overwriting a file the external program used for input, so it did not give any output… Still, it’s nice to have the above snippets at one place, as it wasn’t straightforward to decipher the Boost documentation.
2,598,486
2,598,523
Safe division function
I would like to define some kind of safe division (and modulo) function, one that would return some predefined value when attempting to divide by zero. I don't want to throw exceptions, just to return some "reasonable" value (1? 0?) and continue the program flow. Obviously there is no correct return value, but I wonder if there is some standard or known approach to this
The IEEE floating point standard defines what to get from a division by zero. +a / +0 gives +Inf +a / -0 gives -Inf 0 / 0 gives NaN If you work with integers, you can use this standard to define your own routine, but you have to define what is Inf and what is NaN in integer logic.
2,598,516
2,598,797
C++ Array of Variable sized Arrays
I am very new to C++ and I realise the following is not necessarily as easy as I'd like it to be, but I'd really appreciate a more expert opinion. I am essentially trying to achieve a dynamic iteration over a variable sized array of variable sized arrays similar to the following. String *2d_array[][] = {{"A1","A2"},{"B1","B2","B3"},{"C1"}}; for (int i=0; i<2d_array.length; i++) { for (int j=0; j<2d_array[i].length; j++) { print(2d_array[i][j]); } } Is there a reasonable way to do this? Perhaps by using a vector, or another struct? Thanks :)
You are using a plain C array of C++ string objects. In C there are no variable sized arrays. Besides that this code wont compile anyway, in such a construct the compiler will generate a array of arrays that have the maximum length declared. In the sample case that would be String *2d_array[3][3] If you want variable sized arrays, you have to use C++ STL(Standard template library)-containers such as vector or list: #include <string> #include <vector> void f() { typedef std::vector<std::string> CStringVector; typedef std::vector<CStringVector> C2DArrayType; C2DArrayType theArray; CStringVector tmp; tmp.push_back("A1"); tmp.push_back("A2"); theArray.push_back(tmp); tmp.clear(); tmp.push_back("B1"); tmp.push_back("B2"); tmp.push_back("B3"); theArray.push_back(tmp); tmp.clear(); tmp.push_back("C1"); theArray.push_back(tmp); for(C2DArrayType::iterator it1 = theArray.begin(); it1 != theArray.end(); it1++) for(CStringVector::iterator it2 = it1->begin(); it2 != it1->end(); it2++) { std::string &s = *it2; } }
2,598,535
2,598,689
About enumerations in Delphi and c++ in 64-bit environments
I recently had to work around the different default sizes used for enumerations in Delphi and c++ since i have to use a c++ dll from a delphi application. One function call returns an array of structs (or records in delphi), the first element of which is an enum. To make this work, I use packed records (or aligned(1)-structs). However, since delphi selects the size of an enum-variable dynamically by default and uses the smallest datatype possible (it was a byte in my case), but C++ uses an int for enums, my data was not interpreted correctly. Delphi offers a compiler switch to work around this, so the declaration of the enum becomes {$Z4} TTypeofLight = ( V3d_AMBIENT, V3d_DIRECTIONAL, V3d_POSITIONAL, V3d_SPOT ); {$Z1} My Questions are: What will become of my structs when they are compiled on/for a 64-bit environment? Does the default c++ integer grow to 8 Bytes? Are there other memory alignment / data type size modifications (other than pointers)?
There is no 64bits compiler for Delphi so you can't compile your program for 64bits. However, you can still compile it and run it on a 64bit OS as a 32 bits process. in that case, noting will happens to your structures. The question of the library is a bit more complex: if you compile it as a 64 bits library, you won't be able to load it in your 32-bits process at all. However, assuming you're going to compile it for 64 bits and then use it from a 64 bits process, then the actual length of an int variable is most likely going to stay 32 bits (that's not going to be the case for everything, though). See this wikipedia article for some more information: http://en.wikipedia.org/wiki/64-bit#Specific_data_models
2,598,569
2,598,678
toupper/tolower + locale (german)
how to convert a string (wstring) from lowercase to uppercase characters and vice versa? I searched the net and found there is a STL-function std::transform. But until now I hav'nt figured out how to give the right locale-object for example "Germany_german" to the function. Who can help please? my code looks like: wstring strin = L"ABCÄÖÜabcäöü"; wstring str = strin; locale loc( "Germany_german" ); // ??? how to apply this ??? std::transform( str.begin(), str.end(), str.begin(), (int(*)(int)tolower ); //result: "abcäöüabcäöü" The characters ÄÖÜ and äöü (it's like Ae, Oe, Ue) will not be converted correctly. P.S.: I don't prefer a big switch sweat and also I know BOOST is capable of everything, i would prefer a STL solution. thanks in advance Oops
If you're on Unix, see /usr/share/locale/ for available locales. It looks like you want "de_DE.UTF-8". But setlocale(LC_ALL, ""); should set the program to work in the system's locale, whatever it is. Your program works for me (I fixed a close-paren) if I simply set the default locale like that, without specifying Germany.
2,598,579
2,598,596
C++ Expression Templates
I currently use C for numerical computations. I've heard that using C++ Expression Templates is better for scientific computing. What are C++ Expression Templates in simple terms? Are there books around that discuss numerical methods/computations using C++ Expression Templates? In what way, C++ Expression Templates are better than using pure C?
What are C++ Expression Templates in simple terms? Expression templates are a category of C++ template meta programming which delays evaluation of subexpressions until the full expression is known, so that optimizations (especially the elimination of temporaries) can be applied. Are there books around that discuss numerical methods/computations using C++ Expression Templates? I believe ET's were invented by Todd Veldhuizen who published a paper on it 15 years ago. (It seems that many older links to it are dead by now, but currently here is a version of it.) Some material about it is in David Vandevoorde's and Nicolai Josuttis' C++ Templates: The Complete Guide. In what way, C++ Expression Templates are better than using pure C? They allow you to write your code in an expressive high level way without losing performance. For example, void f(const my_array<double> a1, const my_array<double> a2) { my_array<double> a3 = 1.2 * a1 + a1 * a2; // .. } can be optimized all the way down to for( my_array<double>::size_type idx=0; idx<a1.size(); ++idx ) a3[idx] = 1.2*a1[idx] + a1[idx]*a2[idx]; which is faster, but harder to understand.
2,598,965
2,598,983
gethostbyname replacement for IPv6 addresses
I have a program that uses gethostbyname (in Windows) in order to convert IP address to hostname. But, it works only for IPv4... What is the correct replacement for IPv6? Thanks.
Looking up gethostbyname in MSDN tells us that it's deprecated and we should look at getaddrinfo, which has all kinds of options for dealing with other addressing families. Or if you're doing address to name translation, you'll end up at getnameinfo
2,599,036
2,605,171
How do you debug c/c++ source code in linux using emacs?
I am using emacs and autotools, to write and compile c/c++ sources on linux. I am using gdb via GUD in emacs. I have defined for convenience: F7:compile, F10:gud-next, F11:gud-step, F5:gud-cont, F9:gud-tbreak, F8:gud-until, F4:gud-print. I am mainly interested in debugging c/c++ source code on linux from emacs and I would like to get the most gdb can give. Unfortunately I am using only F4 which prints the variable under cursor. So my question is how do you guys debug the source code ? What programs do you use ? What key bindings (functionality) do you use mostly ? What do you need the debugger to do for you ? If you do weird stuff it doesn't matter. I would like to know everything to boost my speed a bit here. Thanks in advance. Mihai
You'll get the most out of gdb by using the command line instead of key bindings. The most useful commands that I use: bt - prints a backtrace; helpful to know full context of where you are s, n, cont - step, next, continue run - very useful for starting over within the same session watch - sets a watchpoint; useful for catching when a value changes call - invoke a function display - Print a value every time the program stops.
2,599,211
2,599,625
C++ dynamic type construction and detection
There was an interesting problem in C++, but it was more about architecture. There are many (10, 20, 40, etc) classes describing some characteristics (mix-in classes), for example: struct Base { virtual ~Base() {} }; struct A : virtual public Base { int size; }; struct B : virtual public Base { float x, y; }; struct C : virtual public Base { bool some_bool_state; }; struct D : virtual public Base { string str; } // .... The primary module declares and exports a function (for simplicity just function declarations without classes): // .h file void operate(Base *pBase); // .cpp file void operate(Base *pBase) { // .... } Any other module can have code like this: #include "mixing.h" #include "primary.h" class obj1_t : public A, public C, public D {}; class obj2_t : public B, public D {}; // ... void Pass() { obj1_t obj1; obj2_t obj2; operate(&obj1); operate(&obj2); } The question is how do you know what the real type of a given object in operate() is without using dynamic_cast and any type information in classes (constants, etc)? The operate() function is used with a big array of objects in small time periods and dynamic_cast is too slow for it and I don't want to include constants (enum obj_type { ... }) because this is not the OOP-way. // module operate.cpp void some_operate(Base *pBase) { processA(pBase); processB(pBase); } void processA(A *pA) { } void processB(B *pB) { } I cannot directly pass a pBase to these functions. And it's impossible to have all possible combinations of classes, because I can add new classes just by including new header files. One solution that came to mind, in the editor I can use a composite container: struct CompositeObject { vector<Base *pBase> parts; }; But the editor does not need time optimization and can use dynamic_cast for parts to determine the exact type. In operate() I cannot use this solution. So, is it possible to avoid using a dynamic_cast and type information to solve this problem? Or maybe I should use another architecture?
The real problem here is about what you are trying to achieve. Do you want something like: void operate(A-B& ) { operateA(); operateB(); } // OR void operate(A-B& ) { operateAB(); } That is, do you want to apply an operation on each subcomponent (independently), or do you wish to be able to apply operations depending on the combination of components (much harder). I'll take the first approach here. 1. Virtual ? class Base { public: virtual void operate() = 0; }; class A: virtual public Base { public virtual void operate() = 0; }; void A::operate() { ++size; } // yes, it's possible to define a pure virtual class obj1_t: public A, public B { public: virtual void operate() { A::operate(); B::operate(); } }; Some more work, for sure. Notably I don't like the repetition much. But that's one call to the _vtable, so it should be one of the fastest solution! 2. Composite Pattern That would probably be the more natural thing here. Note that you can perfectly use a template version of the pattern in C++! template <class T1, class T2, class T3> class BaseT: public Base, private T1, private T2, private T3 { public: void operate() { T1::operate(); T2::operate(); T3::operate(); } }; class obj1_t: public BaseT<A,B,C> {}; Advantages: no more need to repeat yourself! write operate once and for all (baring variadic...) only 1 virtual call, no more virtual inheritance, so even more efficient that before A, B and C can be of arbitrary type, they should not inherit from Base at all edit the operate method of A, B and C may be inlined now that it's not virtual Disadvantage: Some more work on the framework if you don't have access to variadic templates yet, but it's feasible within a couple dozen of lines.
2,599,658
2,599,969
C++ library for Coordinate Transformation Matrices (CTM)?
I'm looking for a C++ library which allows for easy integration of Coordinate Transformation Matrices (CTM) in my application. You might know CTMs from PDF or PostScript. For one project we are using C++/Qt4 as a framework, which offers a QTransform class, which provides methods like .translate(double x, double y) or .rotate(double degrees). After doing some transformations, it would allow me to get all 6 CTM values, which I could feed into a PDF library or use a transformation matrix in export files. Qt's API also allows for arbitrary mapping of polygons (QPolygon), rectangles (QRect) and other primitive data structures into transformed coordinate systems. So basically I'm looking for something similar to what Qt provides, but without the need of using Qt. I know I could do the matrix multiplications myself, but I'm not really interested in doing so, as I'm very sure that someone already solved this problem, so please no links to books or other guides on how to multiply matrices. Thanks!
Why not just use Qt? It does what you want, is open source (LGPL I think) and you should be able to link just against the QTransform class.
2,599,795
2,609,695
UnitTest++ creates cmd windows, which can't be closed
I have a setup for using UnitTest++ like this in VS2008. Sometimes the cmd window, which shows the console output of the unit tests just hangs. I can move the window, resize and stuff, but I'm unable to close it. I see the window in the App tab of the Task Manager, but not in the Process tab, "Switch to process" doesn't work either. Stop debugging or closing VS is also no help, it seems VS has lost control over this window. If this cmd window is lost, I'm unable to shutdown my computer, which is pretty annoying Any hints?
See Unkillable console windows
2,599,809
2,599,872
No whitespace between a cast and a namespace operator?
Could anyone please explain the following line of code, found on http://docs.openttd.org/ai__cargo_8cpp_source.html return (AICargo::TownEffect)::CargoSpec::Get(cargo_type)->town_effect; If this line was: return (AICargo::TownEffect) ::CargoSpec::Get(cargo_type)->town_effect; (note the space between TownEffect) and the ::) then I would understand it fine. However there is no whitespace in that document*, which would mean (AICargo::TownEffect) is the left operand of the :: operator. How does this code work/compile? Or are the two things equivilent due to some obscure C++ rule? *It's the same in the cpp file as well.
Other than separating tokens, white space is generally not significant in C++ grammar. Parentheses are significant, and they can't appear in a qualified-id so there is no equivalence between: (AICargo::TownEffect)::CargoSpec::Get and AICargo::TownEffect::CargoSpec::Get In the first there are two qualified-ids, one in parentheses naming a type and the other naming a function. The only valid interpretation of a parenthesized type in this context is as a cast-expression. Whether there is a space after the closing parenthesis makes no difference.
2,599,844
2,602,887
ideas for a distributed cache proxy server
I am implementing, a distributed cache proxy server.I have an idea of the HTTP and related stuff, so i am rather concentrating on the sub part "Distributed data storage". From some search on web i found that this could be done using Distributed Hash Tables(DHT). I was wondering if there exists some kind of library for this preferably in C/C++. Any better suggestions for the same will also be appreciated.
Have you looked at Kademlia? There's KadC (C) and maidsafe-dht (C++) for it.
2,599,990
2,600,090
Looking for a safe, portable password-storage method
I'm working on C++ project that is supposed to run on both Win32 and Linux, the software is to be deployed to small computers, usually working in remote locations - each machine likely to contain it's own users/service-men pool. Recently, our client has requested that we introduce access control via password protection. We are to meet the following criteria : Support remote login Support remote password change Support remote password reset EDITED Support data retrieval on accidental/purposeful deletion Support secure storage I'm capable of meeting the "remote" requirements using an existing library, however what I do need to consider is a method of storing this data, preferably in a way that will work on both platforms and will not let the user see it/read it, encryption is not the issue here - it's the storage method itself. Can anyone recommend a safe storage method that could help me meet those criteria? EDIT We're initially considering using a portable SQLite database, however what we are interested in, is limiting the access to the file with the data to users. How can we achieve that? (file not visible to the user, file cannot be opened manually by user etc.) EDIT 2 Cheers for the responses flowing in so far, Can we focus on ways to limit the access to the file itself? Encryption is not the issue here. What we're looking for is a way to hide and or backup the file, and only permit the "MyApp.exe" to work with it. So far we're also investigating Alternate NTFS Streams, however we're not sure if this will work on Linux
You could use a SQLite database. As it's just a file you can use standard file permissions to restrict access. e.g. chmod 600 foo.dbs will restrict access to the file so that only the owner can read/write to it. Then as others have suggested you store a hashed password in the database and it'll be reasonably secure. Rumour has it that there's a commercial version of SQLite available that encrypts the entire database file. However, this shouldn't be a substitute for storing hashed passwords, merely an addition to hashing. edit: Here's the link to the commercial version of sqlite with support for encryption of the entire DB.
2,600,100
2,602,285
how to determine base of a number?
Given a integer number and its reresentation in some arbitrary number system. The purpose is to find the base of the number system. For example, number is 10 and representation is 000010, then the base should be 10. Another example: number 21 representation is 0010101 then base is 2. One more example is: number is 6 and representation os 10100 then base is sqrt(2). Does anyone have any idea how to solve such problem?
An algorithm like this should find the base if it is an integer, and should at least narrow down the choices for a non-integer base: Let N be your integer and R be its representation in the mystery base. Find the largest digit in R and call it r. You know that your base is at least r + 1. For base == (r+1, r+2, ...), let I represent R interpreted in base base If I equals N, then base is your mystery base. If I is less than N, try the next base. If I is greater than N, then your base is somewhere between base - 1 and base. It's a brute-force method, but it should work. You may also be able to speed it up a bit by incrementing base by more than one if I is significantly smaller than N. Something else that might help speed things up, particularly in the case of a non-integer base: Remember that as several people have mentioned, a number in an arbitrary base can be expanded as a polynomial like x = a[n]*base^n + a[n-1]*base^(n-1) + ... + a[2]*base^2 + a[1]*base + a[0] When evaluating potential bases, you don't need to convert the entire number. Start by converting only the largest term, a[n]*base^n. If this is larger than x, then you already know your base is too big. Otherwise, add one term at a time (moving from most-significant to least-significant). That way, you don't waste time computing terms after you know your base is wrong. Also, there is another quick way to eliminate a potential base. Notice that you can re-arrange the above polynomial expression and get (x - a[0]) = a[n]*base^n + a[n-1]*base^(n-1) + ... + a[2]*base^2 + a[1]*base or (x - a[0]) = (a[n]*base^(n-1) + a[n-1]*base^(n-2) + ... + a[2]*base + a[1])*base You know the values of x and a[0] (the "ones" digit, you can interpret it regardless of base). What this gives you the extra condition that (x - a[0]) must be evenly divisible by base (since all your a[] values are integers). If you calculate (x - a[0]) % base and get a non-zero result, then base cannot be the correct base.
2,600,152
2,600,328
Initialising a reference member with itself legal?
This was a bug I found in a server application using Valgrind. struct Foo { Foo(const std::string& a) : a_(a_) { } const std::string& a_; }; with gcc -Wall you don't get a warning. Why is this legal code?
What you've got violates 8.3.2/4 A ... reference shall be initialized to refer to a valid object or function. So it is most certainly illegal. Note that not all erroneous programs are required to be detected by the compiler, although I honestly would have thought this was one of them. For what it's worth, g++ version 4.4.1 with maximal compiler warnings turned on happily accepts this program without a warning either: int main(void) { int *p = 0; *p = 5; }
2,600,336
2,600,610
How to initialize 4th position only in Array of 5 positions
I wanted to store 10 in 4th position of array of 5 positions. How to do ? int main( ) { int a[5] = {,,,,4} ; return 0; } If i do that i get error. Please help. Thanks in advance.
I suppose you can use placement new. int arr[4]; //uninitialized new (&arr[3]) int(10); //"initializes"
2,600,385
2,600,679
C++ nested class/forward declaration issue
Is it possible to forward-declare a nested class, then use it as the type for a concrete (not pointer to/reference to) data member of the outer class? I.E. class Outer; class Outer::MaybeThisWay // Error: Outer is undefined { }; class Outer { MaybeThisWay x; class MaybeThatOtherWay; MaybeThatOtherWay y; // Error: MaybeThatOtherWay is undefined };
You can't forward-declare a nested class like that. Depending on what you're trying to do, maybe you can use a namespace rather than a class on the outer layer. You can forward-declare such a class no problem: namespace Outer { struct Inner; }; Outer::Inner* sweets; // Outer::Inner is incomplete so // I can only make a pointer to it If your Outer absolutely must be a class, and you can't shoe-horn it into a namespace, then you'll need for Outer to be a complete type in the context where you forward declare Inner. class Outer { class Inner; // Inner forward-declared }; // Outer is fully-defined now Outer yes; // Outer is complete, you can make instances of it Outer::Inner* fun; // Inner is incomplete, you can only make // pointers/references to it class Outer::Inner { }; // now Inner is fully-defined too Outer::Inner win; // Now I can make instances of Inner too
2,600,395
2,600,453
VS2005 C++: strange linking problem
I have some strange linking problem in my Visual Studio 2005 C++ project. As always, I declare class in a header and define it's methods in cpp. A have all these files included in my project. And I still have the unresolved external symbol calcWeight. It appears if I actually use this class in my main function. calcWeight() is declared as virtual in the parent class CHDRGenerator If I comment a code in cpp and define calcWeight in a class body, it works fine. But i really don't like this magic. Can someone help? Here is the part of a code: //mann-pickard.h #include "stdafx.h" #include "simple.h" class CHDRGenerator_Mann_Pickard : public CHDRGenerator { public: /// @name Constructors /// @{ /// @brief a constructor using prepared imaged sequence CHDRGenerator_Mann_Pickard(CSimpleImageFile * imSeq, int seqL) : CHDRGenerator(imSeq, seqL) { } /// @brief a constructor using filenames CHDRGenerator_Mann_Pickard(std::string * filenames, int seqL) : CHDRGenerator(filenames, seqL) { } /// @brief a constructor, CFileNameSequence object parameter CHDRGenerator_Mann_Pickard(CFileNameSequence & const fileseq) : CHDRGenerator(fileseq) { } /// @} private: inline double calcWeight(double val); }; //mann-pickard.cpp #include "mann-pickard.h" //=======================Class CHDRGenerator_Mann_Pickard methods=====================// //... inline double CHDRGenerator_Mann_Pickard::calcWeight(double val) { const double gamma = 2.2f; return gamma * pow(val, gamma - 1); } //=====================End of Class CHDRGenerator_Mann_Pickard methods=================// "simple.h" is a header with CHDRGenerator class implementation. I know it should work...as it always worked. Maybe I have some stupid hard-to-find mistake?..
What happens if you remove "inline" from your declaration and definition of calcWeight?
2,600,505
2,600,530
C++ Class Inheritance architecture - preventing casting
I have a structure of base class and a couple of inherited classed. Base class should be pure virtual class, it should prevent instantiation. Inherited classes can be instantiated. Code example below: class BaseClass { public: BaseClass(void); virtual ~BaseClass(void) = 0; }; class InheritedClass : public BaseClass { public: InheritedClass1(void); ~InheritedClass1(void); }; class DifferentInheritedClass : public BaseClass { public: DifferentInheritedClass(void); ~DifferentInheritedClass(void); }; I want to prevent the following operations to happen: InheritedClass *inherited1 = new InheritedClass(); DifferentInheritedClass *inherited2 = new DifferentInheritedClass (); BaseClass *base_1 = inherited1; BaseClass *base_2 = inherited2; *base_1 = *base_2;
Make the copy constructor and the assignment operator in BaseClass protected. The class is non-creatable already, so you don't need public copy-constructor and assignment operators. With protected copy constructor and assignments operators you can call it from the derived classes constructors and assignment operators.
2,600,585
2,603,655
Emacs, Cedet and semantic
I've configured CEDET for emacs following Alex article (great!!). Now, the questions: I've generated GTAGS with Gnu Global in my /usr/include, how can i check if semantic is using GTAGS? Can I keep my GTAGS in another directory and instruct semantic to use that dir? In C/C++ sources, completion on include statement (from system headers) doesn't list all available headers. Ok, this is a stupid problem.. but makes me think something is not working right
You can use the command: M-x semantic-c-describe-environment RET to find out about your include path and CPP macro settings. To test GNU Global use, you can use: M-x semanticdb-test-gnu-global RET printf RET to search for "printf" in in some project. Since your project (perhaps in /home/you/myproject) does not have printf in it, it will fail, but if you opened a file in /usr/include, and did the same command, it will hopefully identify printf. A more general way to ask about GNU Global is with: M-x cedet-gnu-global-version-check RET That all said, the GNU Global support is best in situations where you want to have lots and lots of preparsed files that you access infrequently. Once a header is accessed once (like for printf), then the GNU Global database won't be used anymore, because an equivalent Semantic database will have been created for it. This is necessary because GNU Global does not provide enough information to do smart completion.
2,600,616
2,600,700
How can one enforce calling a base class function after derived class constructor?
I'm looking for a clean C++ idiom for the following situation: class SomeLibraryClass { public: SomeLibraryClass() { /* start initialization */ } void addFoo() { /* we are a collection of foos */ } void funcToCallAfterAllAddFoos() { /* Making sure this is called is the issue */ } }; class SomeUserClass : public SomeLibraryClass { public: SomeUserClass() { addFoo(); addFoo(); addFoo(); // SomeUserClass has three foos. } }; class SomeUserDerrivedClass : public SomeUserClass { public: SomeUserDerrivedClass() { addFoo(); // This one has four foos. } }; So, what I really want is for SomeLibraryClass to enforce the calling of funcToCallAfterAllAddFoos at the end of the construction process. The user can't put it at the end of SomeUserClass::SomeUserClass(), that would mess up SomeUserDerrivedClass. If he puts it at the end of SomeUserDerrivedClass, then it never gets called for SomeUserClass. To further clarify what I need, imagine that /* start initialization */ acquires a lock, and funcToCallAfterAllAddFoos() releases a lock. The compiler knows when all the initializations for an object are done, but can I get at that information by some nice trick?
I would probably implement this with a factory of some sort. The following code should be read as pseudocode, I haven't tried compiling it or anything. class LibraryClass { public: template<typename D> static D *GetNewInstance() { // by assigning the new D to a LibraryClass pointer, you guarantee it derives from LibraryClass at compile time // that way, the user can't accidentally type "LibraryClass::GetNewInstance<int>()" and have it work LibraryClass *c = new D(); c->funcToCallAfterAllAddFoos(); return c; } ... };
2,600,676
2,601,827
Tokenizer for full-text
This should be an ideal case of not re-inventing the wheel, but so far my search has been in vain. Instead of writing one myself, I would like to use an existing C++ tokenizer. The tokens are to be used in an index for full text searching. Performance is very important, I will parse many gigabytes of text. Edit: Please note that the tokens are to be used in a search index. Creating such tokens is not an exact science (afaik) and requires some heuristics. This has been done a thousand time before, and probably in a thousand different ways, but I can't even find one of them :) Any good pointers? Thanks!
I wrote my own tokenizer as part of the open-source SWISH++ indexing and search engine. There's also the the ICU tokenizer that handles Unicode.
2,600,682
7,362,512
How to make ATL control persistence future proof?
I have a custom button control created using ATL. This control is used by some composite controls and lots of dialog boxes. I just added some new properties to the button control and found that I then had to update all the controls and dialogs that used it. This is a really poor situation so I wondered if I could be doing something better. Here are some relevant bits of code: class ATL_NO_VTABLE CSMButton : public CComObjectRootEx<CComSingleThreadModel>, public CStockPropImpl<CSMButton, ISMButton>, public IPersistStreamInitImpl<CSMButton>, public IOleControlImpl<CSMButton>, public IOleObjectImpl<CSMButton>, public IOleInPlaceActiveObjectImpl<CSMButton>, public IViewObjectExImpl<CSMButton>, public IOleInPlaceObjectWindowlessImpl<CSMButton>, public ISupportErrorInfo, public IConnectionPointContainerImpl<CSMButton>, public IConnectionPointImpl<CSMButton, &DIID__ISMButtonEvents>, public CProxy_ISMButtonEvents<CSMButton>, public IPersistStorageImpl<CSMButton>, public ISpecifyPropertyPagesImpl<CSMButton>, public IQuickActivateImpl<CSMButton>, #ifndef _WIN32_WCE public IDataObjectImpl<CSMButton>, #endif public IProvideClassInfo2Impl<&CLSID_SMButton, &__uuidof(_ISMButtonEvents), &LIBID_BaseControlsLib>, #ifdef _WIN32_WCE // IObjectSafety is required on Windows CE for the control to be loaded correctly public IObjectSafetyImpl<CSMButton, INTERFACESAFE_FOR_UNTRUSTED_CALLER>, #endif public CComCoClass<CSMButton, &CLSID_SMButton>, public CComControl<CSMButton> { ... BEGIN_COM_MAP(CSMButton) COM_INTERFACE_ENTRY(ISMButton) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(IViewObjectEx) COM_INTERFACE_ENTRY(IViewObject2) COM_INTERFACE_ENTRY(IViewObject) COM_INTERFACE_ENTRY(IOleInPlaceObjectWindowless) COM_INTERFACE_ENTRY(IOleInPlaceObject) COM_INTERFACE_ENTRY2(IOleWindow, IOleInPlaceObjectWindowless) COM_INTERFACE_ENTRY(IOleInPlaceActiveObject) COM_INTERFACE_ENTRY(IOleControl) COM_INTERFACE_ENTRY(IOleObject) COM_INTERFACE_ENTRY(IPersistStreamInit) COM_INTERFACE_ENTRY2(IPersist, IPersistStreamInit) COM_INTERFACE_ENTRY(ISupportErrorInfo) COM_INTERFACE_ENTRY(IConnectionPointContainer) COM_INTERFACE_ENTRY(ISpecifyPropertyPages) COM_INTERFACE_ENTRY(IQuickActivate) COM_INTERFACE_ENTRY(IPersistStorage) #ifndef _WIN32_WCE COM_INTERFACE_ENTRY(IDataObject) #endif COM_INTERFACE_ENTRY(IProvideClassInfo) COM_INTERFACE_ENTRY(IProvideClassInfo2) #ifdef _WIN32_WCE // IObjectSafety is required on Windows CE for the control to be loaded correctly COM_INTERFACE_ENTRY_IID(IID_IObjectSafety, IObjectSafety) #endif END_COM_MAP() BEGIN_PROP_MAP(CSMButton) PROP_DATA_ENTRY("_cx", m_sizeExtent.cx, VT_UI4) PROP_DATA_ENTRY("_cy", m_sizeExtent.cy, VT_UI4) PROP_ENTRY_TYPE("Caption", DISPID_CAPTION, CLSID_NULL, VT_BSTR) PROP_ENTRY_TYPE("Colour", DISPID_COLOUR, CLSID_NULL, VT_COLOR) PROP_ENTRY_TYPE("ButtonType", DISPID_BUTTONTYPE, CLSID_NULL, VT_I4) PROP_ENTRY_TYPE("Toggle", DISPID_TOGGLE, CLSID_NULL, VT_BOOL) PROP_ENTRY_TYPE("Down", DISPID_DOWN, CLSID_NULL, VT_BOOL) // Example entries // PROP_ENTRY_TYPE("Property Name", dispid, clsid, vtType) // PROP_PAGE(CLSID_StockColorPage) END_PROP_MAP() The two VT_BOOLs are what I added. After doing that and building the control, I got an assert at runtime when showing a dialog and when I opened the dialog in visual studio I got a warning and I had to resave the dialog box. The dialog then worked ok at runtime. I believe the reason for this is that the dialog has saved the properties as a binary stream in the resource and when new properties are added there is no longer enough data to fully initialize the control. The behaviour I would like in this case is for property values that are present to be set and any remaining properties should have default values. How can this be achieved? And no, I can't use .net :-(
I used to slightly modify ATL persistence classes to implement a simple thing. When loading from stream, before starting each property the implementation checks if we are already at the end of stream and if so, it exits the loop assuming that unloaded properties are left initialized by default. From there on, you can add new properties and be backward compatible. If you need to remove a property, do not take it off the map. Instead, you need to leave the entry but you can point it to fake property setter, so that if you have a persistence value for the property saved by earlier version of control, it would be discarded without causing any errors. Hope this helps.
2,600,874
2,618,259
Symbol Not Found, expected in Flat Namespace ObjC++
I've got probably what is a simple problem, but there's no informative errors or warnings during compile to alert me to what is going wrong. I've got a Objective-C++ app that includes a C++ main and ObjC header files. It builds fine, but when run, it gives this error message: Dyld Error Message: Symbol not found: _OBJC_CLASS_$_AppController Referenced from: /Users/slate/Documents/osirixplugins/eqOsirix/build/Development/rcOsirix.app/Contents/MacOS/rcOsirix Expected in: flat namespace in /Users/slate/Documents/osirixplugins/eqOsirix/build/Development/rcOsirix.app/Contents/MacOS/rcOsirix No amount of googling has resulted in a solution, and I'm sure I've just missed a compilation or build option somewhere. "AppController.h" is included in the target (checked), and #import'd in the ObjC Class File. Any help is greatly appreciated. ObjC++ constantly gives me a headache. Thanks, -S!
Clearly the AppController class is missing. Is the AppController class defined in a framework of dynamic library? If so, when you run the app, does it know where to find the libraries/frameworks? This is a linker issue, by the way. The header files are irrelevant. It's the .m or .mm files you need to look at.
2,601,161
2,601,499
C++ Pointer trouble with File I/O
I am writing a function that takes in a output target file and a couple of other arguments. I am currently having trouble with converting types between the argument passed in and using it in the fopen_s() method. FILE* outputf; void myfunc(FILE* fin, CString finpath,...) { outputf = fopen_s(&fin, finpath, "w"); ....... } I've been stuck on this for a while and could use some help on this one. I am developing in Visual Studio 2008 Thanks
Looks like I found my answer. Turns out that fopen_S doesn't allow shared access to the FILE* specified for opening. I had to use _fsopen instead and that solced my problem!
2,601,290
2,601,402
"Unhandled exception" error when mixing boost::thread with wxWidgets GUI
I was trying to access a wxDialog members from a boost::thread: void AnotherThread(myWxDialog *dlg) { wxMessageBox(dlg->TextBox1->GetValue(), "It works!"); // This throws an error } void myWxDialog::OnButtonClick(wxCommandEvent &event) { boost::thread myThread(AnotherThread, this); } And I got this error: Unhandled exception at 0x004043d7 in MyProgram.exe: 0xC0000005: Access violation reading location 0xbaadf00d. I think this kind of action is not allowed between different thread. So, is there any other way to do the same thing? Any kind of help would be appreciated. :) (Microsoft Visual C++ 2008 Express Edition)
0xbaadf00d indicates that you're dereferencing an uninitialized pointer; if I were you I'd dig deeper with the debugger to see exactly where that pointer is (in dlg? in TextBox1? in what GetValue() returns? Somewhere else in wxMessageBox?). This would help you to understand where is the problem. Still, the biggest fault is trying to access GUI things from another thread: as explicitly stated here, When writing a multi-threaded application, it is strongly recommended that no secondary threads call GUI functions. The design which uses one GUI thread and several worker threads which communicate with the main one using events is much more robust and will undoubtedly save you countless problems (example: under Win32 a thread can only access GDI objects such as pens, brushes, device contexts created by itself and not by the other threads). There you can also find some suggestions about how to work around these limitations with events and other wxWidgets facilities.
2,601,370
2,601,854
C++/MFC: Handling multiple CListCtrl's headers HDN_ITEMCLICK events
I'm coding an MFC application in which i have a dialog box with multiple CListCtrls in report view. I want one of them to be sortable. So i handled the HDM_ITEMCLICK event, and everything works just fine .. Except that if i click on the headers of another CListCtrl, it does sort the OTHER CListCtrl, which does look kind of dumb. This is apparently due to the fact that headers have an ID of 0, which make the entry in the message map look like this : ON_NOTIFY(HDN_ITEMCLICK, 0, &Ccreationprogramme::OnHdnItemclickList5) But since all the headers have an id of zero, apparently every header of my dialog sends the message. Is there an easy way around this problem ? EDIT: Maybe i wasn't clear, but i did check the values inside the NMHDR structure. The HwndFrom pointer is different depending on which header is clicked, which doesn't help me a lot since it's value is obviously different at each runtime. The idFrom value is 0, for the very reasons i explained above, because that's the id of every header. Thanks EDIT2: The hwnd pointer values do also not correspond to the CListCtrl, probably because it's coming from a different object entirely.
Ok i found a solution, though i find it a bit dirty but it works, so i'll post it for future reference. You can get the Header through the GetHeaderCtrl member function of CListCtrl. You can then get it's handler thru m_hWnd. So all you got to do is to test if that handler is the same as the one in the NMHDR structure, so the code looks like this : void Ccreationprogramme::OnHdnItemclickList5(NMHDR *pNMHDR, LRESULT *pResult) { if (pNMHDR->hwndFrom == LC_gen_schedules.GetHeaderCtrl()->mhWnd) { // Code goes here } *pResult = 0; } Thanks all for the help
2,601,630
2,601,672
Which HRESULT literal constant will fail the SUCCEEDED() macro?
Definition of SUCCEEDED(): #define SUCCEEDED(hr) (((HRESULT)(hr)) >= 0) Background: When an Ok button is clicked on a dialog, I need to return an HRESULT value hr such that SUCCEEDED(hr) is true. If Cancel button is clicked, I need to return a negative value. I could have used bools, but that would break the existing pattern (usually the hr values come from depths of system dlls). So, I know I can return S_OK on Ok, but what do I return on Cancel? I could just return (HRESULT)-1;, but there must be a better way - some HRESULT literal constant which has negative value and represents a generic failure. S_FALSE is not it, for it's value is defined as 1L. Please help me find the right constant.
Typical values are shown here: http://msdn.microsoft.com/en-us/library/aa378137(VS.85).aspx E_FAIL or E_ABORT seem the most obvious.
2,601,798
2,603,449
Adding compiled libraries and include files to a CMake Project?
What is the best method to include a prebuilt library to a cmake project? I want to include FreeType into the project I am working on and the file structure is like this: Build MacOS Make/ XCode/ Windows VisualStudio/ Source libs MacOS libfreetype Windows freetype.dll includes freetype/ (Various header files that are included automatically by ftbuild.h) ftbuild.h (this is what is included in code from my understanding.) MyProject main.cpp foo.cpp foo.h The library is already compiled. MyProject is the name of the current project. Thanks! Mike
Recent versions already have a module for finding FreeType. Here's the kind of thing I've done in the past: INCLUDE(FindFreetype) IF(NOT FREETYPE_FOUND) FIND_LIBRARY(FREETYPE_LIBRARIES NAMES libfreetype freetype.dll PATHS "./libs/MacOS" "./libs/Windows" DOC "Freetype library") FIND_PATH(FREETYPE_INCLUDE_DIRS ftbuild.h "./includes" DOC "Freetype includes") ENDIF(NOT FREETYPE_FOUND) INCLUDE_DIRECTORIES(${FREETYPE_INCLUDE_DIRS}) TARGET_LINK_LIBRARIES(MyProject ${FREETYPE_LIBRARIES}) You'll need to change the paths to be relative to your CMakeLists.txt. This snippet first invokes the FindFreetype module to check in the standard system locations. If it fails to find the library there, then this falls back to checking directories relative to the your CMakeLists.txt script. If that still fails, you can still set or override the locations via the usual CMake UI. In any event, it tries to add something to the list of includes and libraries to link.
2,601,869
2,602,116
Using Valgrind tool how can I detect which object trying to access 0x0 address?
I have this output when trying to debug Program received signal SIGSEGV, Segmentation fault 0x43989029 in std::string::compare (this=0x88fd430, __str=@0xbfff9060) at /home/devsw/tmp/objdir/i686-pc-linux-gnu/libstdc++-v3/include/bits/char_traits.h:253 253 { return memcmp(__s1, __s2, __n); } Current language: auto; currently c++ Using valgrind I getting this output ==12485== Process terminating with default action of signal 11 (SIGSEGV) ==12485== Bad permissions for mapped region at address 0x0 ==12485== at 0x1: (within path_to_my_executable_file/executable_file)
You don't need to use Valgrind, in fact you want to use the GNU DeBugger (GDB). If you run the application via gdb (gdb path_to_my_executable_file/executable_file) and you've compiled the application with debugging enabled (-g or -ggdb for GNU C/C++ compilers), you can start the application (via run command at the gdb prompt) and once you arrive at the SegFault, do a backtrace (bt) to see what part of your program called std::string::compare which died. Example (C): mctaylor@mpc:~/stackoverflow$ gcc -ggdb crash.c -o crash mctaylor@mpc:~/stackoverflow$ gdb -q ./crash (gdb) run Starting program: /home/mctaylor/stackoverflow/crash Program received signal SIGSEGV, Segmentation fault. 0x00007f78521bdeb1 in memcpy () from /lib/libc.so.6 (gdb) bt #0 0x00007f78521bdeb1 in memcpy () from /lib/libc.so.6 #1 0x00000000004004ef in main (argc=1, argv=0x7fff3ef4d848) at crash.c:5 (gdb) So the error I'm interested in is located on crash.c line 5. Good luck.
2,601,902
2,601,977
passing structure directly to function
I have a struct that I initialize like this: typedef struct { word w; long v; } MyStruct; MyStruct sx = {0,0}; Update(sx); Now, it seems such a waste to first declare it and then to pass it. I know that in C#, there's a way to do everything in one line. Is there any possiblity of passing it in a more clever (read: cleaner) way to my update function?
It depends on how your Update is declared. If it expects a value of MyStruct type or a reference of const MyStruct& type, you can just do Update(MyStruct()); This is possible because you wanted to initialize your object with zeroes (which is what the () initializer will do in this case). If you needed different (non-zero) initializer values, you have to either provide a constructor for MyStruct or do it the way you do it in your question (at least in the current version of the C++ language).
2,601,916
2,602,021
C++ Memory Leak, Can't find where
I'm using Visual Studio 2008, Developing an OpenGL window. I've created several classes for creating a skeleton, one for joints, one for skin, one for a Body(which is a holder for several joints and skin) and one for reading a skel/skin file. Within each of my classes, I'm using pointers for most of my data, most of which are declared using = new int[XX]. I have a destructor for each Class that deletes the pointers, using delete[XX]. Within my GLUT display function I have it declaring a body, opening the files and drawing them, then deleting the body at the end of the display. But there's still a memory leak somewhere in the program. As Time goes on, it's memory usage just keep increasing, at a consistent rate, which I'm interpreting as something that's not getting deleted. I'm not sure if it's something in the glut display function that's just not deleting the Body class, or something else. I've followed the steps for memory leak detection in Visual Studio 2008 and it doesn't report any leak, but I'm not 100% sure if it's working right for me. I'm not fluent in C++, so there maybe something I'm overlooking, can anyone see it? From main: void display(void){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Body *body = new Body(); body->readSkel("C:\\skel2.skel"); body->drawBody(); body = new Body(); body->readSkel("C:\\skel1.skel"); body->drawBody(); glutSwapBuffers(); body->~Body(); delete body; } From Body: Body::Body(){ skelFile = string(); skinFile = string(); totalJoints = 0; joints = new Joint[25]; skin = new Skin; } Body::~Body(){ delete[25] joints; delete skin; }
In this code: Body *body = new Body(); body->readSkel("C:\\skel2.skel"); body->drawBody(); body = new Body(); you're leaking a Body because you don't delete the first one. And this: body->~Body(); delete body; is just weird. You don't explicitly call destructors like that - the delete takes care of calling the destructor. This code: delete[25] joints; is also weird. The correct form is: delete [] joints; You're using a non-standard syntax, and the 25 will be ignored. See this question for more information.
2,602,013
2,602,060
Read whole ASCII file into C++ std::string
I need to read a whole file into memory and place it in a C++ std::string. If I were to read it into a char[], the answer would be very simple: std::ifstream t; int length; t.open("file.txt"); // open input file t.seekg(0, std::ios::end); // go to the end length = t.tellg(); // report location (this is the length) t.seekg(0, std::ios::beg); // go back to the beginning buffer = new char[length]; // allocate memory for a buffer of appropriate dimension t.read(buffer, length); // read the whole file into the buffer t.close(); // close file handle // ... Do stuff with buffer here ... Now, I want to do the exact same thing, but using a std::string instead of a char[]. I want to avoid loops, i.e. I don't want to: std::ifstream t; t.open("file.txt"); std::string buffer; std::string line; while(t){ std::getline(t, line); // ... Append line to buffer and go on } t.close() Any ideas?
Update: Turns out that this method, while following STL idioms well, is actually surprisingly inefficient! Don't do this with large files. (See: http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html) You can make a streambuf iterator out of the file and initialize the string with it: #include <string> #include <fstream> #include <streambuf> std::ifstream t("file.txt"); std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); Not sure where you're getting the t.open("file.txt", "r") syntax from. As far as I know that's not a method that std::ifstream has. It looks like you've confused it with C's fopen. Edit: Also note the extra parentheses around the first argument to the string constructor. These are essential. They prevent the problem known as the "most vexing parse", which in this case won't actually give you a compile error like it usually does, but will give you interesting (read: wrong) results. Following KeithB's point in the comments, here's a way to do it that allocates all the memory up front (rather than relying on the string class's automatic reallocation): #include <string> #include <fstream> #include <streambuf> std::ifstream t("file.txt"); std::string str; t.seekg(0, std::ios::end); str.reserve(t.tellg()); t.seekg(0, std::ios::beg); str.assign((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
2,602,254
2,602,308
Member function pointers in a hierarchy
I'm using a library that defines an interface: template<class desttype> void connect(desttype* pclass, void (desttype::*pmemfun)()); and I have a small hierarchy class base { void foo(); }; class derived: public base { ... }; In a member function of derived, I want to call connect(this, &derived::foo); but it seems that &derived::foo is actually a member function pointer of base; gcc spits out error: no matching function for call to ‘connect(derived* const&, void (base::* const&)())’ I can get around this by explicitly casting this to base *; but why can't the compiler match the call with desttype = base (since derived * can be implicitly cast to base *)? Also, why is &derived::foo not a member function pointer of derived?
Firstly, when you do &class::member the type of the result is always based on the class that member actually declared in. That's just how unary & works in C++. Secondly, the code does not compile because the template argument deduction fails. From the first argument it derives that desttype = derived, while from the second one it derives that desttype = base. This is what makes the compilation to fail. The template argument deduction rules in C++ don't consider the fact that this can be converted to base * type. Moreover, one can argue that instead of converting this to base * type, the proper way would be to convert &derived::foo from pointer-to-base-member to pointer-to-derived-member type. Both approaches are equally viable (see below). Thirdly, member pointers in C++ obey the rules of contra-variance, which means that a pointer to a base class member can be implicitly converted to a pointer to a derived class member. In your case, all you need to do is to help the compiler get through template argument deduction by specifying the argument explicitly, and the code should compile connect<derived>(this, &derived::foo); The above should compile because of contra-variance of &derived::foo pointer, even though it is a pointer to base member. Alternatively you can do connect<base>(this, &derived::foo); This should also compile because of covariance of this pointer. You can also use explicit casts on the actual arguments (as you mention in the question) to get through the deduction ambiguity, but in my opinion in this case the explicitly specified template argument looks better.
2,602,312
2,671,399
Compiling Havok demos
I've downloaded and extracted the Havok demos, but the project has dependency on a folder: $(HAVOK_SDKS_DIR)/win32/dx/Include But it didn't set up a HAVOK_SDKS_DIR (there is no installer), and I can't find a win32/dx directory anywhere in the extracted Havok package. How can I get the demo files to build? What am I missing?
I fixed this by simply REMOVING all references to $(HAVOK_SDKS_DIR) from the project settings. You don't need it.
2,602,724
2,603,000
Can I use QSharedData while inheriting from QObject?
How do I hide the private implementation (implicit sharing) in Qt: I have Employee.cpp the following in my Employee.h header: #include <QSharedData> #include <QString> class EmployeeData; class Employee: public QObject { Q_OBJECT public: Employee(); Employee(int id, QString name); Employee(const Employee &other); void setId(int id); void setName(QString name); int id(); QString name(); private: QSharedDataPointer<EmployeeData> d; }; class EmployeeData : public QSharedData { public: EmployeeData() : id(-1) { name.clear(); } EmployeeData(const EmployeeData &other) : QSharedData(other), id(other.id), name(other.name) { } ~EmployeeData() { } int id; QString name; }; But when I move EmployeeData to a private part, say Employee.cpp I get: error: invalid use of incomplete type ‘struct EmployeeData’ However, if I change my definition to this it works fine: class Employee { public: Employee(); Employee(int id, QString name); .. Thus, can I use QSharedData while inheriting from QObject ?
Thus, can I use QSharedData while inheriting from QObject ? You cannot inherit from QObject when using QSharedData. QSharedData uses copy-on-write semantics and will call detach() to create a copy of the data when it's no longer being shared. In order to do the copy, a copy-constructor is needed, which QObject does not support. The pimpl (or handle-body/opaque-pointer idiom) will often give the data class a reference to the public implementation, which is how you're expected to work with signals and slots. QSharedDataPointer provides most of the implementation details, but it's also quite instructive to take a look at the pimpl idiom as used in Qt (see Q_D and friends)
2,602,823
2,602,836
In C/C++ what's the simplest way to reverse the order of bits in a byte?
While there are multiple ways to reverse bit order in a byte, I'm curious as to what is the "simplest" for a developer to implement. And by reversing I mean: 1110 -> 0111 0010 -> 0100 This is similar to, but not a duplicate of this PHP question. This is similar to, but not a duplicate of this C question. This question is asking for the easiest method to implement by a developer. The "Best Algorithm" is concerned with memory and cpu performance.
If you are talking about a single byte, a table-lookup is probably the best bet, unless for some reason you don't have 256 bytes available.
2,602,874
2,602,909
How to use enumeration types in C++?
I do not understand how to use enumeration types. I understand what they are, but I don't quite get their purpose. I have made a program that inputs three sides of a triangle and outputs whether or not they are isosceles, scalene, or equilateral. I'm suppose to incorporate the enumeration type somewhere, but don't get where and how to use them. Any help would be appreciated. #include <iostream> using namespace std; enum triangleType {scalene, isosceles, equilateral, noTriangle}; triangleType triangleShape(double x, double y, double z); void printTriangleShape(triangleType shape); int main() { double x, y, z; triangleType scalene, isosceles, equilateral, noTriangle; cout << "Please enter the three sides of a triangle:" << endl; cout << "Enter side 1: "; cin >> x; cout << endl; cout << "Enter side 2: "; cin >> y; cout << endl; cout << "Enter side 3: "; cin >> z; cout << endl; triangleType t = triangleShape(x, y, z); printTriangleShape(t); return 0; } triangleType triangleShape(double x, double y, double z) { triangleType scalene, isoceles, equilateral, noTriangle; if (((x+y) > z) && ((x+z) > y) && ((y+z) > x)) { cout << "You have a triangle!" << endl; if (x == y && y == z) return equilateral; else if (x == y || x == z || y == z) return isosceles; else return scalene; } else if ((x+y) <= z || ((x+z) <= y) || ((y+z) <= x)) return noTriangle; } void printTriangleShape(triangleType shape) { switch (shape) { case scalene: cout << "Your triangle is Scalene!" << endl; break; case isosceles: cout << "Your triangle is an isosceles!" << endl; break; case equilateral: cout << "Your triangle is an equilateral!" << endl; break; } }
It's a value, and you probably want to return it from your function. Try: triangleType triangleShape(double x, double y, double z) { if (...) { return scalene; } else if (...) { return isosceles. } else if (...) { return equilateral } else { return noTriangle; } } Note, you can print the result, but it will print as an integer: scalene = 0, isosceles = 1, ... Edit, for printing you may want to do this: void printTriangleShape(triangleType shape) { switch (shape) { case scalene: cout << "Your triangle is Scalene!" << endl; break; case isosceles: cout << "Your triangle is isosceles!" << endl; break; ...; } }
2,603,095
2,603,233
Change Name of Outputted DLL
If my project name is ABC and the DLL currently outputs as ABC.DLL, how can I make my DLL be outputted as say CBA.DLL and so that when the .LIB is compiled linked against, it is not looking for ABC.DLL, but CBA.DLL. I tried changing the name under Linker > General > Output File but when I linked to the .lib in my other application, it was still looking for ABC.DLL and CBA.DLL.
No repro, the .lib file has the correct DLL name. The original name is not present at all. But, don't make the same mistake I first made. Use cba.lib, not abc.lib.
2,603,271
2,603,301
Placement new in gcc
I need to find a workaround for a bug with placement new in g++. I now it was fixed in gcc-4.3 but I have to support versions 4.2 and 4.1. For example, following code compiles with an error "error: no matching function for call to 'operator new(long unsigned int, void*&)" template<class T, template<typename> class Alloc> inline void* type_ctor() { Alloc<T> a; void* p = a.allocate(1); new(p) T; return p; } ..... type_ctor<A, NewAllocator >();
To use the standard library placement news, you have to #include <new>.
2,603,276
10,627,669
How do I clear a Direct2D render target to fully transparent
I'm trying to draw semi-transparent rectangles on an invisible HWND. However, clearing the window with ID2D1HwndRenderTarget::Clear just makes the entire window black, so when I draw rectangles on top, they look semi-black. If I don't Clear() and don't draw, then the window is invisible, as it should be. Clear() is the culprit here; however if I don't use it then painting messes up pretty badly. Here's the code I'm using in my WindowProc: case WM_PAINT: // Begin drawing pRenderTarget->BeginDraw(); pRenderTarget->SetTransform(D2D1::Matrix3x2F::Identity()); // Clear the window pRenderTarget->Clear(); // Paint the panel and its children D2DSurface()->StartPainting(); { D2DSurface()->PaintTraverse(panel); } D2DSurface()->FinishPainting(); // Finish drawing HRESULT hr = plat->pRenderTarget->EndDraw(); Thanks in advance!
When creating your RenderTarget, you'll have to tell D2D that you want to use alpha (in premultiplied mode) in the pixel format: HRESULT hr = mD2DFactory->CreateHwndRenderTarget( D2D1::RenderTargetProperties( D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat( DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED ) ), D2D1::HwndRenderTargetProperties( mWindow, size ), &mRenderTarget ); After this, calling Clear() with an alpha value of zero works just fine.
2,603,279
2,603,335
Are C/C++/ObjC/Swift/JS Apple's only allowed languages for iPhone development?
According to this post on Daring Fireball a new iPhone SDK Agreement release in conjunction with the iPhone OS 4.0 announcement today specifically bans any iPhone application not implemented in C, C++ Objective-C or JavaScript. The clear impact here is to the wide array of programs written in languages other than those. Is that your reading of the clause in the new agreement as well? Update: Here is the clause as printed on Daring Fireball: 3.3.1 — Applications may only use Documented APIs in the manner prescribed by Apple and must not use or call any private APIs. Applications must be originally written in Objective-C, C, C++, or JavaScript as executed by the iPhone OS WebKit engine, and only code written in C, C++, and Objective-C may compile and directly link against the Documented APIs (e.g., Applications that link to Documented APIs through an intermediary translation or compatibility layer or tool are prohibited).
Apple has had a ban on interpreted languages on the iPhone for a while now, but yes, I suppose this makes the ban more clear and more precise. I imagine that yes, Apple is saying that if you use a language other than C, C++, Objective-C, or JavaScript, you run the risk of having your app rejected from the App Store on those grounds.
2,603,312
2,603,349
The result of int c=0; cout<<c++<<c;
I think it should be 01 but someone says its "undefined", any reason for that?
c++ is both an increment and an assignment. When the assignment occurs (before or after other code on that line) is left up to the discretion of the compiler. It can occur after the cout << or before. This can be found in the C99 standard http://www.open-std.org/JTC1/SC22/wg14/www/docs/n1124.pdf You can find it on page 28 in the pdf or section 5.1.2.3 the actual increment of p can occur at any time between the previous sequence point and the next sequence point Since someone asked for the C++ standard (as this is a C++ question) it can be found in section 1.9.15 page 10 (or 24 in pdf format) evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced It also includes the following code block: i = v[i++]; // the behavior is undefined i = 7, i++, i++; // i becomes 9 i = i++ + 1; // the behavior is undefined I feel that the C99 standard's explanation is clearer, but it is true in both languages.
2,603,314
2,604,157
forward/strong enum in VS2010
At http://blogs.msdn.com/vcblog/archive/2010/04/06/c-0x-core-language-features-in-vc10-the-table.aspx there is a table showing C++0x features that are implemented in 2010 RC. Among them are listed forwarding enums and strongly typed enums but they are listed as "partial". The main text of the article says that this means they are either incomplete or implemented in some non-standard way. So I've got VS2010RC and am playing around with the C++0x features. I can't figure these ones out and can't find any documentation on these two features. Not even the simplest attempts compile. enum class E { test }; int main() {} fails with: 1>e:\dev_workspace\experimental\2010_feature_assessment\2010_feature_assessment\main.cpp(518): error C2332: 'enum' : missing tag name 1>e:\dev_workspace\experimental\2010_feature_assessment\2010_feature_assessment\main.cpp(518): error C2236: unexpected 'class' 'E'. Did you forget a ';'? 1>e:\dev_workspace\experimental\2010_feature_assessment\2010_feature_assessment\main.cpp(518): error C3381: 'E' : assembly access specifiers are only available in code compiled with a /clr option 1>e:\dev_workspace\experimental\2010_feature_assessment\2010_feature_assessment\main.cpp(518): error C2143: syntax error : missing ';' before '}' 1>e:\dev_workspace\experimental\2010_feature_assessment\2010_feature_assessment\main.cpp(518): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== int main() { enum E : short; } Fails with: 1>e:\dev_workspace\experimental\2010_feature_assessment\2010_feature_assessment\main.cpp(513): warning C4480: nonstandard extension used: specifying underlying type for enum 'main::E' 1>e:\dev_workspace\experimental\2010_feature_assessment\2010_feature_assessment\main.cpp(513): error C2059: syntax error : ';' ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== So it seems it must be some totally non-standard implementation that has allowed them to justify calling this feature "partially" done. How would I rewrite that code to access the forwarding and strong type feature? Some further information about the new features I'm attempting to use: Strongly typed enums: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2347.pdf Forward declaration of enums: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2764.pdf
I think I found the answer. I found "enum class" in the VS 2010 documentation under the keywords documentation. It's managed only--unsupported in real C++ builds. So it seems that they mean this C++0x feature is "partially done" in that it isn't done at all.
2,603,583
2,603,767
Boost Thread Hanging on _endthreadex
I think I am making a simple mistake, but since I noticed there are many boost experts here, I thought I would ask for help. I am trying to use boost threads(1_40) on windows xp. The main program loads a dll, starts the thread like so (note this is not in a class, the static does not mean static to a class but private to the file). static boost::thread network_thread; static bool quit = false; HANDLE quitEvent; //some code omitted for clarity, ask if you think it would help void network_start() { HANDLE *waitHandles = (HANDLE*)malloc(3 * sizeof(HANDLE)); waitHandles[0] = quitEvent; waitHandles[1] = recvEvent; waitHandles[2] = pendingEvent; do { //read network stuff, or quit event dwEvents =WaitForMultipleObjects(3, waitHandles, FALSE, timeout); } while (!quit) } DllClass::InitInstance() { } DllClass::ExportedFunction() { network_thread = boost::thread(boost::bind<void>(network_start)); } DllClass::ExitInstance() { //signal quit (which works) quit = true; SetEvent(QuitEvent); //the following code is slightly verbose because I'm trying to figure out what's wrong try { if (network_thread.joinable() ) { network_thread.join(); } else { TRACE("Too late!"); } } catch (boost::thread_interrupted&) { TRACE("NET INTERRUPTED"); } } The problem is that the main thread is hanging on the join, and the network thread is hanging at the end of _endthreadex. What am I misunderstanding?
You are not supposed to create/end threads in InitInstance/ExitInstance, see http://support.microsoft.com/default.aspx?scid=kb;EN-US;142243 for more info. Also, see http://msdn.microsoft.com/en-us/library/ms682583%28VS.85%29.aspx about DllMain in general.
2,603,611
2,603,845
write a program that prompts the user to input five decimal numbers
This is the question. write a program that prompts the user to input five decimal numbers. the program should then add the five decimal numbers, convert the sum to the nearest integer,m and print the result. This is what I've gotten so far: // p111n9.cpp : Defines the entry point for the console application. // #include <iostream> using namespace std; double a, b , c , d , e, f; int main(int argc, char* argv[]) { cout << "enter 5 decimals: " << endl; cin >> a >> b >> c >> d >> e; f = a + b + c + d + e; return 0; } Now I just need to convert the sum(f) to the nearest integer, m and print the result. How do I do this?
"declare m" means say int m; if you say m = (int)f; // it means the int value of f is assigned to m. The casting is actually not even necessary here: m=f; //works just as well now you can print m cout<<m;
2,603,917
2,604,080
Generic FSM for game in C++?
I was wondering if there's a way I could code some kind of "generic" FSM for a game with C++?. My game has a component oriented design, so I use a FSM Component. my Finite State Machine (FSM) Component, looks more or less this way. class gecFSM : public gecBehaviour { public: //Constructors gecFSM() { state = kEntityState_walk; } gecFSM(kEntityState s) { state = s; } //Interface void setRule(kEntityState initialState, int inputAction, kEntityState resultingState); void performAction(int action); private: kEntityState fsmTable[MAX_STATES][MAX_ACTIONS]; }; I would love to hear your opinions/ideas or suggestions about how to make this FSM component, generic. With generic I mean: 1) Creating the fsmTable from an xml file is really easy, I mean it's just a bunch of integers that can be loaded to create an MAX_STATESxMAX_ACTION matrix. void gecFSM::setRule(kEntityState initialState, int inputAction, kEntityState resultingState) { fsmTable[initialState][inputAction] = resultingState; } 2) But what about the "perform Action" method ? void gecFSM::performAction(int action) { switch( smTable[ ownerEntity->getState() ][ action ] ) { case WALK: /*Walk action*/ break; case STAND: /*Stand action*/ break; case JUMP: /*Jump action*/ break; case RUN: /*Run action*/ break; } } What if I wanted to make the "actions" and the switch generic? This in order to avoid creating a different FSM component class for each GameEntity? (gecFSMZombie, gecFSMDryad, gecFSMBoss etc ?). That would allow me to go "Data Driven" and construct my generic FSM's from files for example. What do you people suggest?
Have a look at the Boost Statechart Library. (formerly known as boost::fsm) It comes with a very nice photo camera example.
2,604,201
2,604,292
Inter process communication C# <--> C++ for game debugging engine
I am working on a debugger project for a game's scripting engine. I'm hoping to write the debugger's GUI in C#. The actual debugging engine, however, is embedded in the game itself and is written in a mixture of C, C++, and assembly patches. What's the best way to handle communication between the debugger GUI and the debugging engine? The two will be running in separate processes. Thanks! Andy
If you can require Windows Vista or later, and .Net 3.5 or later, Named Pipes provide simple, high-performance IPC. Check out this article.
2,604,202
2,604,216
C++ extern keyword on functions. Why no just include the header file?
If I understand it correctly this means extern void foo(); that the function foo is declared in another translation unit. 1) Why not just #include the header in which this function is declared? 2) How does the linker know where to look for function at linking time? edit: Maybe I should clarify that the above declaration is then followed by using the function foo(); It is never defined in this translation unit.
1) It may not have a header file. But yes, in general, for large projects, you should have a header file if multiple translation units are going to use that function (don't repeat yourself). 2) The linker searches through all the object files and libraries it was told about to find functions and other symbols.
2,604,206
2,604,269
C++ constant reference lifetime (container adaptor)
I have code that looks like this: class T {}; class container { const T &first, T &second; container(const T&first, const T & second); }; class adapter : T {}; container(adapter(), adapter()); I thought lifetime of constant reference would be lifetime of container. However, it appears otherwise, adapter object is destroyed after container is created, leaving dangling reference. What is the correct lifetime? is stack scope of adapter temporary object the scope of container object or of container constructor? how to correctly implement binding temporary object to class member reference? Thanks
According to the C++03 standard, a temporary bound to a reference has differing lifetimes depending on the context. In your example, I think the highlighted portion below applies (12.2/5 "Temporary objects"): The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below. A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits. A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call. So while binding a temporary is an advanced technique to extend the lifetime of the temporary object (GotW #88: A Candidate For the "Most Important const"), it apparently won't help you in this case. On the other hand, Eric Niebler has an article that you may be interested in that discusses an interesting (if convoluted) technique that could let your class's constructors deduce whether a temporary object (actually an rvalue) has been passed to it (and therefore would have to be copied) or a non-temporary (lvalue) as been passed (and therefore could potentially safely have a reference stashed away instead of copying): Conditional Love: FOREACH Redux Good luck with it though - every time I read the article, I have to work through everything as if I've never seen the material before. It only sticks with me for a fleeting moment... And I should mention that C++0x's rvalue references should make Niebler's techniques unnecessary. Rvalue references will be supported by MSVC 2010 which is scheduled to be released in a week or so (on 12 April 2010 if I recall correctly). I don't know what the status of rvalue references is in GCC.
2,604,358
2,605,585
From where starts the process' memory space and where does it end?
On Windows platform, I'm trying to dump memory from my application where the variables lie. Here's the function: void MyDump(const void *m, unsigned int n) { const unsigned char *p = reinterpret_cast<const unsigned char *>(m); char buffer[16]; unsigned int mod = 0; for (unsigned int i = 0; i < n; ++i, ++mod) { if (mod % 16 == 0) { mod = 0; std::cout << " | "; for (unsigned short j = 0; j < 16; ++j) { switch (buffer[j]) { case 0xa: case 0xb: case 0xd: case 0xe: case 0xf: std::cout << " "; break; default: std::cout << buffer[j]; } } std::cout << "\n0x" << std::setfill('0') << std::setw(8) << std::hex << (long)i << " | "; } buffer[i % 16] = p[i]; std::cout << std::setw(2) << std::hex << static_cast<unsigned int>(p[i]) << " "; if (i % 4 == 0 && i != 1) std::cout << " "; } } Now, how can I know from which address starts my process memory space, where all the variables are stored? And how do I now, how long the area is? For instance: MyDump(0x0000 /* <-- Starts from here? */, 0x1000 /* <-- This much? */); Best regards, nhaa123
Overview What you're trying to do is absolutely possible, and there are even tools to help, but you'll have to do more legwork than I think you're expecting. In your case, you're particularly interested in "where the variables lie." The system heap API on Windows will be an incredible help to you. The reference is really quite good, and though it won't be a single contiguous region the API will tell you where your variables are. In general, though, not knowing anything about where your memory is laid out, you're going to have to do a sweep of the entire address space of the process. If you want only data, you'll have to do some filtering of that, too, because code and stack nonsense are also there. Lastly, to avoid seg-faulting while you dump the address space, you may need to add a segfault signal handler that lets you skip unmapped memory while you're dumping. Process Memory Layout What you will have, in a running process, is multiple disjoint stretches of memory to print out. They will include: Compiled code (read-only), Stack data (local variables), Static Globals (e.g. from shared libraries or in your program), and Dynamic heap data (everything from malloc or new). The key to a reasonable dump of memory is being able to tell which range of addresses belongs to which family. That's your main job, when you're dumping the program. Some of this, you can do by reading the addresses of functions (1) and variables (2, 3 and 4), but if you want to print more than a few things, you'll need some help. For this, we have... Useful Tools Rather than just blindly searching the address space from 0 to 2^64 (which, we all know, is painfully huge), you will want to employ OS and compiler developer tools to narrow down your search. Someone out there needs these tools, maybe even more than you do; it's just a matter of finding them. Here are a few of which I'm aware. Disclaimer: I don't know many of the Windows equivalents for many of these things, though I'm sure they exist somewhere. I've already mentioned the Windows system heap API. This is a best-case scenario for you. The more things you can find in this vein, the more accurate and easy your dump will be. Really, the OS and the C runtime know quite a bit about your program. It's a matter of extracting the information. On Linux, memory types 1 and 3 are accessible through utilities like /proc/pid/maps. In /proc/pid/maps you can see the ranges of the address space reserved for libraries and program code. You can also see the protection bits; read-only ranges, for instance, are probably code, not data. For Windows tips, Mark Russinovich has written some articles on how to learn about a Windows process's address space and where different things are stored. I imagine he might have some good pointers in there.
2,604,541
2,605,828
How can I use ToUnicode without breaking dead key support?
A similar question has already been asked, so I'm not going to waste time re-explaining it, an existing discussion can be found here: ToAscii/ToUnicode in a keyboard hook destroys dead keys The reason I'm posting a new question however is that I seem to have come across a 'solution', but I'm not quite sure how to implement it. This blog post seems to propose a solution to the problem of ToUnicode killing dead-key support: http://www.siao2.com/2005/01/19/355870.aspx However I'm not sure how to implement the suggested solution. A push in the right direction would be greatly appreciated. To be clear, the part I'm referring to is this: There are two ways to work around this: 1) You can keep calling ToUnicode with the same info until it is cleared out and then call it one more time to put the state back where it was if you had never typed anything, or 2) You can load all of the keyboard info ahead of time and then when they type information you can look up in your own info cache what the keystrokes mean, without having to call APIs later. I'm not quite sure how to do either of those things (keyboards and internationalization are far from my strong point), so any help would be greatly appreciated. Thanks
The first part of the answer is entirely information-free. However, the second part does make sense. ToUnicode() should have been a pure function, which merely acts as a lookup. However, it isn't. But you can call it repeatedly for all expected inputs, store those in your own lookup table and access that. I'd recommend that Microsoft adds a lookDontTouch flag to the wFlags parameter; that would be a trivial non-breaking API fix.
2,604,715
2,612,145
Add functions in gdb at runtime
I'm trying to debug some STL based C++ code in gdb. The code has something like int myfunc() { std::map<int,int> m; ... } Now in gdb, inside myfunc using "print m" gives something very ugly. What I've seen recommended is compiling something like void printmap( std::map<int,int> m ) { for( std::map<int,int>::iterator it = ... ) { printf("%d : %d", it->first, it->second ); } } Then in gdb doing (gdb) call printmap( m ) This seems like a good way to handle the issue... but can I put printmap into a seperate object file (or even dynamic library) that I then load into gdb at runtime rather than compiling it into my binary - as recompiling the binary every time I want to look at another STL variable is not fun .. while compiling and loading a single .o file for the print routine may be acceptable. UPDATE: Prompted by Nikolais suggestion I'm looking at dlopen/dlsym. So I haven't yet got this working but it feels like I'm getting closer. In printit.cpp #include <stdio.h> extern "C" void printit() { printf("OMG Fuzzies"); } Compile to a .so using g++ -Wall -g -fPIC -c printit.cpp g++ -shared -Wl,-undefined,dynamic_lookup -o printit.so printit.o Start my test application and load the .so using dlopen ( 2 = RTLD_NOW ) then try to get the symbol for a debugging function using dlsym. (gdb) break main (gdb) run (gdb) print (void*) dlopen("printit.so", 2 ) $1 = (void *) 0x100270 (gdb) print (void*) dlsym( 0x100270, "_printit" ) $2 = (void *) 0x0 So close but for some reason I cant get that symbol... ( I cant even get it if I put the dlopen/dlsym calls in my executable) I'm guessing I'm either compiling the lib wrong or using dlsym incorrectly. If I can get the symbol I'm assuming I can call the function using something like (gdb) print (( void(*)() )(0x....))() I'm compiling this on OS X 10.4, which might be causing some of my .so woes... any pointers would be appreciated. Found out how to get all this working. Have posted as a solution below.
So my solution is to load a shared object containing my debugging routines at run time, using dlopen. Turns out it is even simpler than I thought when you get all the compile flags right. On OS X this means you compile your application and debugging object like this: all : application.x debug_helper.so application.x : application.cpp g++ -g application.cpp -o application.x -fPIC debug_helper.so : debug_helper.o g++ -dynamiclib -o debug_helper.so debug_helper.o debug_helper.o : debug_helper.cpp g++ -Wall -g -fPIC -c debug_helper.cpp The -fPIC on the application is critical, as is the -dynamiclib (rather than trying the linux -shared flag ) An example debug_helper.cpp might look like this #include <map> #include <stdio.h> extern "C" void printMap( const std::map<int,int> &m ) { printf("Map of size %d\n", int(m.size()) ); for( std::map<int,int>::const_iterator it = m.begin(); it!=m.end(); ++it ) { printf("%d : %d \n", it->first, it->second ); } fflush(stdout); } Don't know why I chose to use stdio rather than iostream stuff... I guess you can use either. (just don't forget to flush the streams...) Now my application file looks like this: #include <map> int main() { std::map<int,int> m; m[1]=2; m[2]=5; m[3]=10; m[4]=17; } And here's an example debugging session (some output removed) Start the application and break at an interesting point (gdb) break main (gdb) run Reading symbols for shared libraries +++. done Breakpoint 1, main () at test.cpp:5 5 std::map<int,int> m; Load in the debug helper library (gdb) print (void*) dlopen("./debug_helper.so",2) Reading symbols for shared libraries . done $1 = (void *) 0x100270 (gdb) n 6 m[1]=2; GDB is smart and catches all the new symbols for us so we don't need to use dlsym etc. We can just call the functions directly. (gdb) call printMap(m) Map of size 0 (gdb) n (gdb) n (gdb) n 9 m[4]=17; (gdb) call printMap(m) Map of size 3 1 : 2 2 : 5 3 : 10 Let's add some more info to printMap. First, unload the library. (gdb) print (int) dlclose($1) $2 = 0 Edit the source to add in the sum of the entries. Recompile and then load the new library back into gdb (without restarting the executable or gdb ) (gdb) print (void*) dlopen("./debug_helper.so",2) Reading symbols for shared libraries . done $3 = (void *) 0x100270 Use the modified function (gdb) call printMap(m) Map of size 3 1 : 2 2 : 5 3 : 10 SUM = 17 I think this does everything that I need.
2,604,748
2,604,766
operator+ overload returning object causing memory leaks, C++
The problem I think is with returning an object when i overload the + operator. I tried returning a reference to the object, but doing so does not fix the memory leak. I can comment out the two statements: dObj = dObj + dObj2; and cObj = cObj + cObj2; to free the program of memory leaks. Somehow, the problem is with returning an object after overloading the + operator. #include <iostream> #include <vld.h> using namespace std; class Animal { public : Animal() {}; virtual void eat() = 0 {}; virtual void walk() = 0 {}; }; class Dog : public Animal { public : Dog(const char * name, const char * gender, int age); Dog() : name(NULL), gender(NULL), age(0) {}; virtual ~Dog(); Dog operator+(const Dog &dObj); private : char * name; char * gender; int age; }; class MyClass { public : MyClass() : action(NULL) {}; void setInstance(Animal &newInstance); void doSomething(); private : Animal * action; }; Dog::Dog(const char * name, const char * gender, int age) : // allocating here, for data passed in ctor name(new char[strlen(name)+1]), gender(new char[strlen(gender)+1]), age(age) { if (name) { size_t length = strlen(name) +1; strcpy_s(this->name, length, name); } else name = NULL; if (gender) { size_t length = strlen(gender) +1; strcpy_s(this->gender, length, gender); } else gender = NULL; if (age) { this->age = age; } } Dog::~Dog() { delete name; delete gender; age = 0; } Dog Dog::operator+(const Dog &dObj) { Dog d; d.age = age + dObj.age; return d; } void MyClass::setInstance(Animal &newInstance) { action = &newInstance; } void MyClass::doSomething() { action->walk(); action->eat(); } int main() { MyClass mObj; Dog dObj("Scruffy", "Male", 4); // passing data into ctor Dog dObj2("Scooby", "Male", 6); mObj.setInstance(dObj); // set the instance specific to the object. mObj.doSomething(); // something happens based on which object is passed in dObj = dObj + dObj2; // invoke the operator+ return 0; }
you need to declare copy constructor since you are returning object in overloaded operator +, the compiler automatically generates one for you if you dont explicitly define it, but compiler are stupid enough to not do deep copy on pointers to summarize your mistake in the code posted: 1.) No Copy-Constructor/Assignment-Operator defined (deallocation exception/ memory leak here) Since you are dealing with pointers, the compiler generated functions only perform shallow copy. It is you job to make sure such behavior is intended, otherwise redefine it yourself into : Dog::Dog(const Dog& ref) : _name( strdup(ref._name) ), _gender( strdup(ref._gender) ), _age( ref._age ) { } Dog& Dog::operator=(const Dog &dObj) { if (this != &dObj) { free (_name); free (_gender); _name = strdup( dObj._name ); _gender = strdup( dObj._gender ); _age = dObj._age; } return *this; } 2.) Poor handling on pointer passed in (Memory leak here) You performed allocation before verifying null state on input parameters. It is smart move to additionally extra allocate 1 char of memory but you do not deallocate them after finding input parameters are null. A simple fix similar to copy-constructor above will be : Dog::Dog(const char * name, const char * gender, int age) : _name( strdup(name) ), _gender( strdup(gender) ), _age( age ) { } 3.) Improper pairing of allocator/deallocator (Potential memory leak here) Array allocation with new[] should match with array deallocation delete[], otherwise destructor for array element will not be handled correctly. However, to be consistent with sample code posted above using strdup (which internally make use of malloc), your destructor should be as below : Dog::~Dog() { free (_name); free (_gender); _age = 0; }
2,604,847
2,604,859
How to read values from file. tokenizer
I have a file in which each line contains two numbers. The problem is that the two number are separated by a space, but the space can be any number of blank spaces. either one, two, or more. I want to read the line and store each of the numbers in a variable, but I'm not sure how to tokenize it. i.e 1 5 3 2 5 6 3 4 83 54 23 23 32 88 8 203
Read each line, stick the contents of the line into a stringstream, and then read the two int out of the line: std::string line; while (std::getline(myfilestream, line)) { std::stringstream ss(line); int i, j; if (ss >> i >> j) { // use i and j } } If you know for a fact that each line will have exactly two ints (i.e., you absolutely, positively trust your source), you can read the values directly from the stream.
2,605,099
2,605,108
c++ process always on foreground in window OS
I have a c++ process, I want that process should always remain on foreground, kindly guide me how can I make it possible?
It is not possible since user always has an option to switch to another application. This is by design. Good link from Billy ONeal: How do I create a window that is never covered by any other windows, not even other topmost windows? Imagine if this were possible and imagine if two programs did this. Program A creates a window that is "super-topmost" and so does Program B. Now the user drags the two windows so that they overlap. What happens? You've created yourself a logical impossibility. One of those two windows must be above the other, contradicting the imaginary "super-topmost" feature.
2,605,352
2,605,370
How is destroying local variables when a block is exited normally called in C++?
C++ automagically calls destructors of all local variables in the block in reverse order regardless of whether the block is exited normally (control falls through) or an exception is thrown. Looks like the term stack unwinding only applies to the latter. How is the former process (the normal exit of the block) called concerning destroying local variables?
An object is automatically destructed when it "goes out of scope". This could be referred to as "automatic storage reclamation", but that actually refers to garbage collection (there are several papers with that phrase in their name that use the term to mean garbage collection). When it is used to ensure proper pairing of open/close, lock/unlock, or other forms of resource acquisition with their appropriate release, then it is known as the design pattern of Resource Acquisition is Initialization (RAII), which is somewhat ironic given that the main aspect of RAII is not the resource initialization or acquisition, but rather its destruction.
2,605,427
2,606,152
C++ How to get a filename (and path) of the executing .so module in Unix
C++ How to get a filename (and path) of the executing .so module in Unix? Something similar to GetModuleFileName on Windows.
Although it is not a POSIX standard interface, the dladdr() function is available on many systems including Linux, Solaris, Darwin/Mac OS X, FreeBSD, HP-UX, and IRIX. This function takes an address, which could be a pointer to a static function within the module for example (if cast to void *), and fills in a Dl_info structure with information including the path name of the shared object containing that address (in the dli_fname member).
2,605,520
2,605,559
C++ where to initialize static const
I have a class class foo { public: foo(); foo( int ); private: static const string s; }; Where is the best place to initialize the string s in the source file?
Anywhere in one compilation unit (usually a .cpp file) would do: foo.h class foo { static const string s; // Can never be initialized here. static const char* cs; // Same with C strings. static const int i = 3; // Integral types can be initialized here (*)... static const int j; // ... OR in cpp. }; foo.cpp #include "foo.h" const string foo::s = "foo string"; const char* foo::cs = "foo C string"; // No definition for i. (*) const int foo::j = 4; (*) According to the standards you must define i outside of the class definition (like j is) if it is used in code other than just integral constant expressions. See David's comment below for details.
2,605,593
2,605,918
What's the correct way to do a 'catch all' error check on an fstream output operation?
What's the correct way to check for a general error when sending data to an fstream? UPDATE: My main concern regards some things I've been hearing about a delay between output and any data being physically written to the hard disk. My assumption was that the command "save_file_obj << save_str" would only send data to some kind of buffer and that the following check "if (save_file_obj.bad())" would not be any use in determining if there was an OS or hardware problem. I just wanted to know what was the definitive "catch all" way to send a string to a file and check to make certain that it was written to the disk, before carrying out any following actions such as closing the program. I have the following code... int Saver::output() { save_file_handle.open(file_name.c_str()); if (save_file_handle.is_open()) { save_file_handle << save_str.c_str(); if (save_file_handle.bad()) { x_message("Error - failed to save file"); return 0; } save_file_handle.close(); if (save_file_handle.bad()) { x_message("Error - failed to save file"); return 0; } return 1; } else { x_message("Error - couldn't open save file"); return 0; } }
Everything except for the check after the close seems reasonable. That said, I would restructure things slightly differently and throw an exception or use a bool, but that is simply a matter of preference: bool Saver::output() { std::fstream out(_filename.c_str(),std::ios::out); if ( ! out.is_open() ){ LOG4CXX_ERROR(_logger,"Could not open \""<<filename<<"\""); return false; } out << _savestr << std::endl; if ( out.bad() ){ LOG4CXX_ERROR(_logger,"Could not save to \""<<filename<<"\""); out.close(); return false; } out.close(); return true; } I should also point out that you don't need to use save_str.c_str(), since C++ iostreams (including fstream, ofstream, etc.) are all capable of outputting std::string objects. Also, if you construct the file stream object in the scope of the function, it will automatically be closed when it goes out of scope.
2,605,603
2,605,623
Declaration and initialization of local variables - what is most C++ like?
I did not find any suitable questions answered yet, so I'd like to know what is "better" C++ style in the mean of performance and/or memory. Both codes are inside a method. The question is: When to declare long prio? And what are the implications? Code 1 while (!myfile.eof()) { getline(myfile, line); long prio = strtol(line); // prio is declared here // put prio in map... // some other things } Code 2 long prio; // prio is declared here while (!myfile.eof()) { getline(myfile, line); prio = strtol(line); // put prio in map... // some other things }
There is no difference in performance in this case. If you compare the generated code, it will very likely be the same for both cases. I think the most common style is to declare the variable as close to its first use as possible, but as with all matters of style, it can be very subjective what is "best". As others have mentioned, if possible it's better to confine each variable to as tight a scope as possible. Doing so reduces the risk of the variable being used in the wrong context, overwritten by mistake, and so on. It also reduces the amount of code you need to read in order to figure out where a variable is being used, which aids understanding of the code. One advantage of declaring late is that for cases like these, where the value read is not modified during the rest of the body, it can be made const which helps clarity and readability. Since a const variable cannot be assigned to after being declared, this only works in the former style.
2,605,630
2,605,731
Having a destructor take different actions depending on whether an exception occurred
I have some code to update a database table that looks like try { db.execute("BEGIN"); // Lots of DELETE and INSERT db.execute("COMMIT"); } catch (DBException&) { db.execute("ROLLBACK"); } I'd like to wrap the transaction logic in an RAII class so I could just write { DBTransaction trans(db); // Lots of DELETE and INSERT } but how would I write the destructor for it?
Use following: transaction tr(db); ... tr.commit(); When tr.commit() completes it sets the state to "commit done" and destructor does nothing, otherwise it rollbacks. Checking for exception is bad idea, consider: transaction tr(db); ... if(something_wrong) return; // Not throw ... tr.commit(); In this case you probably expect rather rollback then commit but commit would be done. Edit: but if you still want it badly, take a look on std::uncaught_exception() but read this first http://www.gotw.ca/gotw/047.htm
2,605,674
2,608,349
How to properly rewrite ASSERT code to pass /analyze in msvc?
Visual Studio added code analysis (/analyze) for C/C++ in order to help identify bad code. This is quite a nice feature but when you deal with and old project you may be overwhelmed by the number of warnings. Most of the problems are generating because the old code is doing some ASSERT at the beginning of the method or function. I think this is the ASSERT definition used in the code (from afx.h) #define ASSERT(f) DEBUG_ONLY((void) ((f) || !::AfxAssertFailedLine(THIS_FILE, __LINE__) || (AfxDebugBreak(), 0))) Example code: ASSERT(pBytes != NULL); *pBytes = 0; // <- warning C6011: Dereferencing NULL pointer 'pBytes' I'm looking for an easy, clean and safe solution to solve these warnings that does not imply disabling these warnings. Did I mention that there are lots of occurrences in current codebase?
PREFast is telling you that you have a defect in your code; don't ignore it. You do in fact have one, but you have only skittered around acknowleging it. The problem is this: just because pBytes has never been NULL in development & testing doesn't mean it won't be in production. You don't handle that eventuality. PREfast knows this, and is trying to warn you that production environments are hostile, and will leave your code a smoking, mutilated mass of worthless bytes. /rant There are two ways to fix this: the Right Way, and a hack. The right way is to handle NULL pointers at runtime: void DoIt(char* pBytes) { assert(pBytes != NULL); if( !pBytes ) return; *pBytes = 0; } This will silence PREfast. The hack is to use an annotation. For example: void DoIt(char* pBytes) { assert(pBytes != NULL); __analysis_assume( pBytes ); *pBytes = 0; } EDIT: Here's a link describing PREfast annotations. A starting point, anyway.
2,605,689
2,605,759
Character pointers and integer pointers (++)
I have two pointers, char *str1; int *str2; If I look at the size of both the pointers let’s assume str1=4 bytes str2=4 bytes str1++ will increment by 1 byte, but if str2++ it will increment 4 bytes. What is the concept behind this?
Simple, in the provided scenario: char is 1 byte long int (in your platform) is 4 bytes long The ++ operator increments the pointer by the size of the pointed type.
2,606,216
2,607,076
Exposing a C++ API to C#
So what I have is a C++ API contained within a *.dll and I want to use a C# application to call methods within the API. So far I have created a C++ / CLR project that includes the native C++ API and managed to create a "bridge" class that looks a bit like the following: // ManagedBridge.h #include <CoreAPI.h> using namespace __CORE_API; namespace ManagedAPIWrapper { public ref class Bridge { public: int bridge_test(void); int bridge_test2(api_struct* temp); } } . // ManagedBridge.cpp #include <ManagedBridge.h> int Bridge::bridge_test(void) { return test(); } int Bridge::bridge_test2(api_struct* temp) { return test2(temp); } I also have a C# application that has a reference to the C++/CLR "Bridge.dll" and then uses the methods contained within. I have a number of problems with this: I can't figure out how to call bridge_test2 within the C# program, as it has no knowledge of what a api_struct actually is. I know that I need to marshal the object somewhere, but do I do it in the C# program or the C++/CLR bridge? This seems like a very long-winded way of exposing all of the methods in the API, is there not an easier way that I'm missing out? (That doesn't use P/Invoke!) EDIT: Ok, so I've got the basics working now thanks to responses below, however my struct (call it "api_struct2" for this example) has both a native enum and union in the C++ native code, like the following: typedef struct { enum_type1 eEnumExample; union { long lData; int iData; unsigned char ucArray[128]; char *cString; void *pvoid; } uData; } api_struct2; I think I have figured out how to get the enum working; I've re-declared it in managed code and am performing a "native_enum test = static_cast(eEnumExample)" to switch the managed version to native. However the union has got me stumped, I'm not really sure how to attack it.. Ideas anyone?
Yes, you are passing an unmanaged structure by reference. That's a problem for a C# program, pointers are quite incompatible with garbage collection. Not counting the fact that it probably doesn't have the declaration for the structure either. You can solve it by declaring a managed version of the structure: public value struct managed_api_struct { // Members... }; Now you can declare the method as int bridge_test2(managed_api_struct temp); // pass by value or int bridge_test2(managed_api_struct% temp); // pass by reference Pick the latter if the structure has more than 4 fields (~16 bytes). The method needs to copy the structure members, one-by-one, into an unmanaged api_struct and call the unmanaged class method. This is unfortunately necessary because the memory layout of a managed structure is not predictable. This is all pretty mechanical, you might get help from SWIG. Haven't used it myself, not sure if it is smart enough to deal with a passed structure. A completely different approach is to make the wrapper class cleaner by giving it a constructor and/or properties that lets you build the content of an api_struct. Or you could declare a wrapper ref class for the structure, much like you would in managed code.
2,606,705
2,607,831
Objective-C++ compiles for iPhone, but not simulator
I have a C++ library I want to add to my iphone project. In one header file I declare @interface a { cppvirtualclass V; } This compiles fine for the iPhone device with Release settings. However it refuses to compile for the Simulator with or without debug info. It give the error error: type 'V' has virtual member functions. Is there a way out of this or do I have to define only concrete C++ classes?
By default Objective C does not run constructors on C++ instance variables when it creates Objective C objects. This means (I think) that the C++ object's vtable will not get initialised correctly. Try making your instance variable a pointer and allocating it in the init method (and destroying it in dealloc/finalize). Or try setting "Call C++ default Ctors/Dtors in Ovjective-C" in your target code generation settings. (GCC_OBJC_CALL_CXX_CDTORS, -fobjc-call-cxx-cdtors)
2,607,010
8,792,991
Linux, how to capture screen, and simulate mouse movements
I need to capture screen (as print screen) in the way so I can access pixel color data, to do some image recognition, after that I will need to generate mouse events on the screen such as left click, drag and drop (moving mouse while button is pressed, and then release it). Once its done, image will be deleted. Note: I need to capture whole screen everything that user can see, and I need to simulate clicks outside window of my program (if it makes any difference) Spec: Linux ubuntu Language: C++ Performance is not very important,"print screen" function will be executed once every ~10 sec. Duration of the process can be up to 24 hours so method needs to be stable and memory leaks free (as usuall :) I was able to do in windows with win GDI and some windows events, but I'ev no idea how to do it in Linux. Thanks a lot
//sg //Solution using Xlib for those who use Linux #include <X11/Xlib.h> #include<stdio.h> #include<unistd.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <X11/Xlib.h> #include <X11/Xutil.h> void mouseClick(int button) { Display *display = XOpenDisplay(NULL); XEvent event; if(display == NULL) { fprintf(stderr, "Cannot initialize the display\n"); exit(EXIT_FAILURE); } memset(&event, 0x00, sizeof(event)); event.type = ButtonPress; event.xbutton.button = button; event.xbutton.same_screen = True; XQueryPointer(display, RootWindow(display, DefaultScreen(display)), &event.xbutton.root, &event.xbutton.window, &event.xbutton.x_root, &event.xbutton.y_root, &event.xbutton.x, &event.xbutton.y, &event.xbutton.state); event.xbutton.subwindow = event.xbutton.window; while(event.xbutton.subwindow) { event.xbutton.window = event.xbutton.subwindow; XQueryPointer(display, event.xbutton.window, &event.xbutton.root, &event.xbutton.subwindow, &event.xbutton.x_root, &event.xbutton.y_root, &event.xbutton.x, &event.xbutton.y, &event.xbutton.state); } if(XSendEvent(display, PointerWindow, True, 0xfff, &event) == 0) fprintf(stderr, "Error\n"); XFlush(display); usleep(100000); event.type = ButtonRelease; event.xbutton.state = 0x100; if(XSendEvent(display, PointerWindow, True, 0xfff, &event) == 0) fprintf(stderr, "Error\n"); XFlush(display); XCloseDisplay(display); } int main(int argc,char * argv[]) { int x , y; x=atoi(argv[1]); y=atoi(argv[2]); Display *display = XOpenDisplay(0); Window root = DefaultRootWindow(display); XWarpPointer(display, None, root, 0, 0, 0, 0, x, y); mouseClick(Button1); XFlush(display); XCloseDisplay(display); return 0; } Build it and then to simulate a click at x ,y do: $ ./a.out x y i.e. $ g++ -lX11 sgmousesim2.cpp $ ./a.out 123 13 Just in case you are still interested.
2,607,235
2,607,255
append set to another set
Is there a better way of appending a set to another set than iterating through each element ? i have : set<string> foo ; set<string> bar ; ..... for (set<string>::const_iterator p = foo.begin( );p != foo.end( ); ++p) bar.insert(*p); Is there a more efficient way to do this ?
You can insert a range: bar.insert(foo.begin(), foo.end());
2,607,236
2,607,277
Constructing / destructing QApplication causes QWebView to mess up rendering of HTML
We need to create & destroy instances of QApplication, as we want to use Qt in a plug-in to an existing host application. void multiQT() { int argc = 0; QApplication app(argc, NULL); QWebView view; view.setHtml("<html><head><title>Title</title></head><body><h1>Hello World</h1></body></html>"); view.show(); app.exec(); } main(int argc, char** argv) { // First call works fine, QWebView renders the HTML just fine multiQT(); // Second call fails, QWebView strips HTML tags from HTML text and // and renders "TitleHello World" multiQT(); } When showing the QWebView the second time, it does not render the HTML properly. Do we need to do some additional (re-)initializations in QApplication or QWebView?
You might have run into something that has been very lightly tested, the QApplication object among others creates/holds some of the rendering context information of widgets, I don't think it was ever planned for people to take it down and put it back up again. There might be some static content that does not get reinitialised correctly when somebody tries what you are trying to do.
2,607,524
2,607,584
C question on casting
Can anybody explain me this statement! pin.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr;
Takes hp->h_addr, and casts it to struct in_addr*. The cast may have different reasons. Perhaps hp->h_addr is void* and the cast is needed to tell the compiler what type it should use for finding s_addr. It may also be another struct that has an in_addr as its first member struct in_addr { struct saddr_t s_addr; }; struct socket { struct in_addr addr; }; struct server { struct socket *h_addr; }; server *hp; Then, casting socket* to in_addr* would be valid because on its address there is a in_addr at the beginning. After the cast, the member s_addr is accessed. These types are common in network programming under POSIX, and don't look like in my above example, but the above could have been the situation at hand.
2,607,895
2,607,988
c++ opengl: how can i combine 2 different projection types for 3d graphics and 2d menus?
I would like to use Oblique projection for menus and perspective projection for the 3d-scene. is there a way to combine between this two projections ? In general I'm asking how can I create menus in opengl for my 3d scene. Programming using the c++ language. Thanks!
No problem. Just draw your 3D scene with appropriate modelview and projection matrices loaded. Then load up 2D matrices, turn off depth test, and render your menus. Here's an example of what it might look like. glEnable(GL_DEPTH_TEST) glMatrixMode(GL_MODELVIEW); --code to load my Perspective Modelview Matrix glMatrixMode(GL_PROJECTION); --code to load my Perspective Projection Matrix --code to draw my 3D scene glMatrixMode(GL_MODELVIEW) glLoadIdentity() glMatrixMode(GL_PROJECTION); --code to setup my "menu" coords, probably something like gluOrtho2D glDisable(GL_DEPTH_TEST) --code to draw the menus
2,608,283
2,937,821
Direct2D window black when not in focus
I have a Direct2D window which paints fine when in focus; however, when focus moves to another window (same application or another), the entire window goes black. I pinned the issue down to the use of ID2D1HwndRenderTarget::Clear. This function is vital to my application as without it, painting becomes rather... weird. Is there a way an un-focused Direct2D window can paint as normal (note: WM_PAINT is being called as usual, as is Clear, BeginPaint, etc. all without error) Thanks in advance.
With my experience with DirectX, if the screen turns back its because DX lost the device it was 'painting' to. This happens a lot - for instance - when switching between a full-screen DirectX window to another application, and vice-versa. So what you need to do is re-intialize the DX device so it can resume painting operations. This might help some more (not my website, but a quick Google search turned it up) http://www.programmersheaven.com/2/FAQ-DIRECTX-Avoid-task-switching
2,608,381
2,608,480
Boost graph libraries: setting edge weight values
I am investigating the use of the boost graph libraries in order to apply them to various network problems I have in mind. In the examples I have been looking at the graph edge values ("weights") are always initialized as integers, such as in these Bellman-Ford and Kruskal algorithms eg: int weights[] = { 1, 1, 2, 7, 3, 1, 1, 1 }; My problem is if I try and change the weights to double, I get a heap of warning messages about conversions etc, which so far I have not been able to figure out how to overcome. Does anyone see a way around this?
It's caused by a mismatch between the weights[] array and the type used for edge weights by your boost graph/algorithm. In the first linked sample, eg, you should also change struct EdgeProperties { int weight; }; [...] property_map<Graph, int EdgeProperties::*>::type to struct EdgeProperties { double weight; }; [...] property_map<Graph, double EdgeProperties::*>::type In the second typedef adjacency_list < vecS, vecS, undirectedS, no_property, property < edge_weight_t, int > > Graph; to typedef adjacency_list < vecS, vecS, undirectedS, no_property, property < edge_weight_t, double > > Graph;
2,608,596
2,608,635
std::deque: How do I get an iterator pointing to the element at a specified index?
I have a std::deque, and I want to insert an element at a specified index (I'm aware that std::list would be better at this). The deque::insert() function takes an iterator to specify the location to insert. Given an index, how can I get an iterator pointing to that location, so that I can pass that iterator to insert()? For example: void insertThing ( deque<Thing> & things, Thing thing, size_t index ) { deque<Thing>::iterator it = /* what do I do here? */ things.insert ( it, thing ); } I'm sure this is a very basic question, and I apologize for it. It's been a long time since I've used the STL, and I don't see anything in std::deque's member list that obviously does what I want. Thanks.
void insertThing ( deque<Thing> & things, Thing thing, size_t index ) { deque<Thing>::iterator it = things.begin() + index; things.insert ( it, thing ); }
2,608,696
14,800,172
C++ Formatting like Visual Studio C# formatting
I like the way Visual Studio (2008) formats C# code; unfortunately it seems it doesn't behave in the same way when writing C++ code. For example, when I write a code in this way: class Test { public: int x; Test() {this->x=20;} ~Test(){} }; in C# (ok this is C++ but you can understand what I mean), this part: Test() {this->x=20;} Will become: Test() { this->x=20; } This is obviously a stupid example, but there are a lot of things where putting brackets in correct position, indenting code and other things with my own hands becomes boring. I can obviously change editor if you suggest me a good one for C++ code, I would like to find something with these features: Intellisense (like vs, at least similar) Custom class coloring (in C=C# they are cyan, why are they black in C++?) Wordwrap (possibly) Documentation when you mouse over a method/variable Auto formatting (when you close a bracket like "}" in C# you'll get everything well formatted) Obviously I can find other features, but this is what is in my mind at the moment. Thanks for any suggestion.
I'm using AStyle extension for VS2012 and I'm happy with it. It's free :)
2,609,104
2,609,113
Why isn't strlen working for me?
char p[4]={'h','g','y'}; cout<<strlen(p); This code prints 3. char p[3]={'h','g','y'}; cout<<strlen(p); This prints 8. char p[]={'h','g','y'}; cout<<strlen(p); This again prints 8. Please help me as I can't figure out why three different values are printed by changing the size of the array.
strlen starts at the given pointer and advances until it reaches the character '\0'. If you don't have a '\0' in your array, it could be any number until a '\0' is reached. Another way to reach the number you're looking for (in the case you've shown) is by using: int length = sizeof(p)/sizeof(*p);, which will give you the length of the array. However, that is not strictly the string length as defined by strlen. As @John Dibling mentions, the reason that strlen gives the correct result on your first example is that you've allocated space for 4 characters, but only used 3; the remaining 1 character is automatically initialized to 0, which is exactly the '\0' character that strlen looks for.
2,609,145
2,612,125
Interpreters: Handling includes/imports
I've built an interpreter in C++ and everything works fine so far, but now I'm getting stuck with the design of the import/include/however you want to call it function. I thought about the following: Handling includes in the tokenizing process: When there is an include found in the code, the tokenizing function is recursively called with the filename specified. The tokenized code of the included file is then added to the prior position of the include. Disadvantages: No conditional includes(!) Handling includes during the interpreting process: I don't know how. All I know is that PHP must do it this way as conditional includes are possible. Now my questions: What should I do about includes? How do modern interpreters (Python/Ruby) handle this? Do they allow conditional includes?
This problem is easy to solve if you have a clean design and you know what you're doing. Otherwise it can be very hard. I have written at least 6 interpreters that all have this feature, and it's fairly straightforward. Your interpreter needs to maintain an environment that knows about all the global variables, functions, types and so on that have been defined. You might feel more comfortable calling this the "symbol table". You need to define an internal function that reads a file and updates the environment. Depending on your language design, you might or might not do some evaluation the moment you read things in. My interpreters are very dynamic and evaluate each definition as soon as it is read in. Your life will be infinitely easier if you structure your interpreter in layers: Tokenizer (breaks input into tokens) Parser (reads one token at a time, converts to abstract-syntax tree) Evaluator (reads the abstract syntax and updates the environment) The abstract-syntax tree is really the key. If you have this, when you encounter the import/include construct in the input, you just make a recursive call and get more abstract syntax back. You can do this in the parser or the evaluator. If you want conditional import, you have to do it in the evaluator, since only the evaluator can compute a condition. Source code for my interpreters is on the web. Two of them are written in C; the others are written in Standard ML.
2,609,207
2,609,293
How to use linked resource with eclipse CDT?
I found it very difficult to configure linked resource in Eclipse CDT. Folder "wspolne" is located somewhere in the system, I'd like to use .cpp .h files from it in my current project, but avoid copying it. From what I read about Linked Resources is a solution, but I can't build a projct :/ I followed instuctions described here with out any result: What's wrong ? Image that shows problem: alt text http://img260.imageshack.us/img260/1629/eclipsen.jpg
I am not sure linked folder are always adequately indexed by the CDT (update October 2012, it has gotten better with recent CDT releases) A workaround would be, as in this thread: If you want CDT to manage the builds you need to move the sub-folders into there own project folder and create dependencies between them.