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,399,644
2,400,673
What does DetourAttach(&(PVOID &)BindKeyT, BindKeyD); mean? Attaching a detour to a memory address
This is just a simple question. I've been reading the source of something which attaches to a memory address of a subroutine using DetourAttach(&(PVOID &)BindKeyT, BindKeyD); where BindKeyT is the address to a subroutine in memory. I'm curious, what exactly does (&(PVOID &) mean in english? I understand that PVOID is a void pointer, but how does this get translated into a function which can be used to attach a detour to?
Terry Mahaffey is right, what you are passing is a pointer to a pointer to the function. This is commonly used whenever the function you are passing the pointer to (in this case, DetourAttach) wants to return more than one value, and one of those returned values is a pointer. Since functions in C/C++ can only return a single value, the only way to obtain multiple values from them is via pointers. A simple example would be when one wishes to return a pointer to a block of allocated memory. Then one can write a function like: int allocstr(int len, char **retptr) { char *p = malloc(len + 1); /* +1 for \0 */ if(p == NULL) return 0; *retptr = p; return 1; } To answer your other question, of how to setup a memory address to be used as a function, one can do it like so: void* (void * BindKeyT)(const char* key) = actual_BindKeyT; // actual_BindKeyT is a pointer to a function that will be defined elsewhere, // and whose declaration you will include in your project through a header file // or a dll import void * BindKeyD(const char* key) { // Code for your hook function } DetourAttach(&(PVOID&)BindKeyT, BindKeyD); (taken from http://zenersblog.blogspot.com/2008/04/api-hooking-with-detours-part-1.html) Bear in mind that the declarations for BindKeyT and BindKeyD should match.
2,399,744
2,399,755
Root base class in C++
Every object in .NET inherits (directly or indirectly) from the common root base "Object". Is there such a common object root in C++? How do I pass any object to a function? public void DoSomeStuff(object o) { ... } EDIT: To clarify, the purpose: In that function I want to invoke a pointer to member function. For that I need the object instance and pointer to the required function. To simplify readability I want to make a wrapper containing the both required information. I'm not sure if that is the best way, but it is the background idea.
There is no common root class. Use either void* to pass any object into a function, or better define some base class.
2,400,083
2,400,124
Open source libraries for sound effects in games
does aybody know about an open source sound library in C++ or some other popular language that can be used in open source games for recreating sounds and especifically in car racing games to recreate engine sound? Thanks
A long time ago, there was OpenAL and was moderately successful on Linux. It's fairly easy, modelled around the OpenGL library principles.
2,400,157
2,400,205
The intersection of two sorted arrays
Given two sorted arrays: A and B. The size of array A is La and the size of array B is Lb. How to find the intersection of A and B? If La is much bigger than Lb, then will there be any difference for the intersection finding algorithm?
Use set_intersection as here. The usual implementation would work similar to the merge part of merge-sort algorithm.
2,400,458
2,401,137
Is there a boost::weak_intrusive_pointer?
For legacy reasons I need to use intrusive pointers, as I need the ability to convert raw pointers to smart pointers. However I noticed there is no weak intrusive pointer for boost. I did find a talk about it on the boost thread list, however nothing concrete. Does anyone know of a thread safe implementation of weak intrusive pointer? Thanks Rich
It does not make any sense. To elaborate: weak_ptr points to the same instance of a counter object that shared_ptr do. When the shared_ptr goes out of scope, the instance of the counter stays (with a count effectively at 0), which allows the weak_ptr instances to check that they effectively point to a freed object. With Intrusive Counting, the counter is integrated within the object. When the count reaches 0, the object is usually either recycled or deleted... but the point is the counter is no longer available. The rationale is that this allow for a more efficient storage (1 single chunk) and greater speed (cache locality). If you need Weak Reference counting and do not care for the benefits of intrusive counting, you can use a combination of shared_ptr and weak_ptr. The idea is to deassociate the counter from the objects. class Counted { // bla private: boost::shared_ptr<int> mCounter; }; Now you can return weak handles: class WeakHandle { public: explicit WeakHandle(Counted& c): mCounter(c.mCounter), mObject(&c) {} bool expired() const { return mCounter.expired(); } private: boost::weak_ptr<int> mCounter; Counted* mObject; }; Here, we deassociate the lifetime of the counter from the lifetime of the object, so that it will survive the destruction of the object... partially. Thus making the weak_ptr effectively possible. And of course, using shared_ptr and weak_ptr this is Thread Safe ;)
2,400,690
2,400,717
Why callback functions needs to be static when declared in class
I was trying to declare a callback function in class and then somewhere i read the function needs to be static but It didn't explain why? #include <iostream> using std::cout; using std::endl; class Test { public: Test() {} void my_func(void (*f)()) { cout << "In My Function" << endl; f(); //Invoke callback function } static void callback_func() {cout << "In Callback function" << endl;} }; int main() { Test Obj; Obj.my_func(Obj.callback_func); }
A member function is a function that need a class instance to be called on. Members function cannot be called without providing the instance to call on to. That makes it harder to use sometimes. A static function is almost like a global function : it don't need a class instance to be called on. So you only need to get the pointer to the function to be able to call it. Take a look to std::function (or std::tr1::function or boost::function if your compiler doesn't provide it yet), it's useful in your case as it allow you to use anything that is callable (providing () syntax or operator ) as callback, including callable objects and member functions (see std::bind or boost::bind for this case).
2,400,766
2,400,793
Linking C and CXX files in CMake
I'm building C++ app with CMake. But it uses some source files in C. Here is simplified structure: trunk/CMakeLists.txt: project(myapp) set(CMAKE_CXX_FLAGS "${CMAKE_C_FLAGS} -g -Wall") add_subdirectory (src myapp) trunk/src/main.cpp: #include "smth/f.h" int main() { f(); } trunk/src/CMakeLists.txt: add_subdirectory (smth) link_directories (smth) set(APP_SRC main) add_executable (myapp ${APP_SRC}) target_link_libraries (myapp smth) trunk/src/smth/f.h: #ifndef F_H #define F_H void f(); #endif trunk/src/smth/f.c: #include "f.h" void f() {} trunk/src/smth/CMakeLists.txt set (SMTH_SRC some_cpp_file1 some_cpp_file2 f) add_library (smth STATIC ${SMTH_SRC}) The problem is: i run gmake, it compiles all the files and when it links all libs together, i get: undefined reference to `f()` in main.cpp if i rename f.c into f.cpp everything goes just fine. What's the difference and how to handle it? Thanks
Change f.h to: #ifndef F_H #define F_H #ifdef __cplusplus extern "C" { #endif void f(); #ifdef __cplusplus } #endif #endif
2,401,046
2,401,108
Avoid stuck calling callback
This is a question about generic c++ event driven applications design. Lets assume that we have two threads, a "Dispatcher" (or "Engine"...) and a "Listener" (or "Client"...). Let's assume that I write the Dispatcher code, and release it as a library. I also write the Listener interface, of course. When the Dispatcher executes (after Listener registration) listenerInstance.onSomeEvent(); the event handling code will actually be executed by the Dispatcher thread, so if the person that implements the Listener writes something like void Listener::onSomeEvent() { while(true) ; } The Dispatcher will stuck forever. Is there a "plain old c++" (I mean no boost or libsigc++) way to "decouple" the two classes, so I can be sure that my Dispatcher will work fine whatever the Listeners does in the callbacks? bye and thanks in advance, Andrea
Well if the event gets invoked in the same thread (as I seem to understand can be a requirement), then there isn't much you can do about it. If this is under a Win32 app with a message pump, you could register a windows message and call PostMessage with data representing this event and you can patch the message loop to interpret that message and call the event. What you gain is a decoupling of sorts, the event call is asynchronous (ie the event call will return no matter what). But later on when you process your messages and actually call the event, your main thread will still be stalled and nothing else will run until the event handler is ready. Another alternative is just creating a new thread (or using a thread pool) for your call. This won't work for events that require a certain thread (ie ui updating threads). Additionally this adds synchronization overhead and thread spawning overhead AND you might starve the system of threads and/or cpu time. But really, I don't think it's your job as the library designer to anticipate and avoid these problems. If the end-user wants to create a long event handler, let him spawn a new thread on his own. If he doesn't and just wants his specific thread to handle an event, let him. It simplifies your job and doesn't add any overhead that's not needed.
2,401,225
2,401,253
Template classes and include guards in C++
Is it wise to have include guards around template classes? Aren't template classes supposed to be reparsed each time you reference them with a different implementation? N.B In Visual C++ 2008 I get no errors combining the two...
Templates definitions are supposed to be parsed once (and things like two phases name lookup are here so that as much errors as possible can be given immediately without having an instantiation). Instantiations are done using the internal data structure built at that time. Templates definitions are usually (i.e. if you aren't using export or doing something special) in header files which should have their include guard. Adding one for template definition is useless but not harmful.
2,401,241
2,403,005
Is it worth using std::tr1 in production?
I'm using MS VC 2008 and for some projects Intel C++ compiler 11.0. Is it worth using tr1 features in production? Will they stay in new standard? For example, now I use stdext::hash_map. TR1 defines std::tr1::unordered_map. But in MS implementation unordered_map is just theirs stdext::hash_map, templatized in another way.
My advice would be to use an alias for the namespace containing the TR1 items you use. This way, you'll be able to "move" from using the TR1 version to the standard version when your compiler supports it. namespace cpp0x = std::tr1; cpp0x::unordered_map<std::string, int> mymap; for a C++0x compiler, the first line becomes: namespace cpp0x = std; and you can leave the rest alone.
2,401,710
2,407,538
Not receiving clear list notifications from Call log
I have been using CLogViewRecent and MLogViewChangeObserver to monitor call log on S60 5th edition phones. MLogViewChangeObserver has three functions: virtual void HandleLogViewChangeEventAddedL(TLogId aId, TInt aViewIndex, TInt aChangeIndex, TInt aTotalChangeCount); virtual void HandleLogViewChangeEventChangedL(TLogId aId, TInt aViewIndex, TInt aChangeIndex, TInt aTotalChangeCount); virtual void HandleLogViewChangeEventDeletedL(TLogId aId, TInt aViewIndex, TInt aChangeIndex, TInt aTotalChangeCount); However, only the first two get called regularly, while HandleLogViewChangeEventDeletedL gets called only sometimes. E.g. HandleLogViewChangeEventDeletedL is not called when I choose "Clear List" from the menu in "Received calls" list in Call log application. Can anyone point to the reason why this is happening, and how to correct this? Thank you.
Reading the Symbian^3 logcli source, "list cleared" is an event different from "event deleted". It's not reflected in the MLogViewChangeObserver callback mixin, only in MLogViewChangeObserverInternal as HandleLogViewChangeEventLogClearedL(). That's why it's happening. Sorry, cannot offer you a workaround, short of implementing your own logsrv client that handles ELogChangeTypeLogCleared change types the way you want. Maybe you could describe what you are trying to achieve on the big picture level so it could be possible to offer other alternatives.
2,401,800
2,403,082
MinGW/G++/g95 link error - libf95 undefined reference to `MAIN_'
Summing up, my problem consists on compiling g95 objects inside a C++ application. Actually, I'm constructing an interface for an old fortran program. For this task, I'm using the wxWidgets GUI library, and calling fortran subroutines when necessary. At the beginning, I was developing the entire project compiling my fortran files with gfortran (which comes with GCC) and linking them with my app by the g++ -o... command. Everything was working fine but some numbers values calculated by my fotran subroutines returned NAN values. Doing some research, I realized that compiling my fortran files with gfortran with the -m32 flag, generates this NAN values problem. Although compiling with -m64 flag, my code works properly well. The only trouble here is that my App should be 32bits and then I tryed another compiller. Here I found g95 Fortran compiler, which compiles my fortran code and gives the right output on a 32bits environment. But when I'm trying to link these g95 objects into my program I see this following error: g++ -oCyclonTechTower.exe src\fortran\Modulo_Global.o src\fortran\Prop_Fisicas.o src\fortran\inversa.o src\fortran\tower.o src\fortran\PredadeCarga.o src\fortran\gota.o src\fortran\tadi.o src\view\SimulationORSATCustomDialog.o src\view\SimulationChildGUIFrame.o src\view\ParentGUIFrame.o src\view\ClientGUIFrame.o src\model\TowerData.o src\controller\SimulationController.o src\THEIACyclonTechTower.o ..\Resource\resource.o -Lc:\wxWidgets-2.6.4\lib -Lc:\MinGW\lib\gcc-lib\i686-pc-mingw32\4.1.2 -Bdynamic -Wl,--subsystem,windows -mwindows c:\wxWidgets-2.6.4\lib\libwx_mswu-2.6.a -lwxregexu-2.6 -lwxexpat-2.6 -lwxtiff-2.6 -lwxjpeg-2.6 -lwxpng-2.6 -lwxzlib-2.6 -lrpcrt4 -loleaut32 -lole32 -luuid -lwinspool -lwinmm -lshell32 -lcomctl32 -lcomdlg32 -lctl3d32 -ladvapi32 -lwsock32 -lgdi32 -lgcc -lf95 **c:\MinGW\lib\gcc-lib\i686-pc-mingw32\4.1.2/libf95.a(main.o):(.text+0x32): undefined reference to `MAIN_' collect2: ld returned 1 exit status** Build error occurred, build is stopped Time consumed: 1531 ms. I have already read the g95 Manual for integration with C++ and I'm actually calling these functions bellow for controlling the fortran environment: void g95_runtime_start(int argc, char *argv[]); void g95_runtime_stop(); I also included the g95 Fortran Runtime Library libf95.a and the libgcc.a into my linker command. Finishing, I don't have a main method implemented because this is managed by wxWidgets, and my fortran subroutines can not have a main function because this is a C++ program calling fortran functions. Can some of you guys help me with this problem? How can I fix this undefined reference to MAIN__ problem? Any idea will be much appreciated.
I'm answering my own question because I got the solution. The problem wasn't with my g95 intergration. I just overwrite the wxWidgets main macro for an int main function initialization as presented bellow: // Give wxWidgets the means to create a MyApp object //IMPLEMENT_APP(MyApp); int main(int argc, char *argv[]) { //MyWxApp derives from wxApp MyApp *myapp = new MyApp(); wxApp::SetInstance( myapp ); wxEntryStart( argc, argv ); myapp->OnInit(); myapp->OnRun(); myapp->OnExit(); wxEntryCleanup(); } By the way, the required main function is now defined and my app is now working properly well without NAN values. I hope that this question can help others.
2,401,976
2,402,103
Very simple application fails with "multiple target patterns" from Eclipse
Since I'm more comfortable using Eclipse, I thought I'd try converting my project from Visual Studio. Yesterday I tried a very simple little test. No matter what I try, make fails with "multiple target patterns". (This is similar to this unanswered question.) I have three files: Application.cpp: using namespace std; #include "Window.h" int main() { Window *win = new Window(); delete &win; return 0; } Window.h: #ifndef WINDOW_H_ #define WINDOW_H_ class Window { public: Window(); ~Window(); }; #endif Window.cpp: #include <cv.h> #include <highgui.h> #include "Window.h" const char* WINDOW_NAME = "MyApp"; Window::Window() { cvNamedWindow(WINDOW_NAME, CV_WINDOW_AUTOSIZE); cvResizeWindow(WINDOW_NAME, 200, 200); cvMoveWindow(WINDOW_NAME, 0, 0); int key = 0; while (true) { key = cvWaitKey(0); if (key==27 || cvGetWindowHandle(WINDOW_NAME)==0) { break; } } } Window::~Window() { cvDestroyWindow(WINDOW_NAME); } I have added the following paths to the compiler include path (-I): "$(OPENCV)/cv/include" "$(OPENCV)/cxcore/include" "$(OPENCV)/otherlibs/highgui" I have added the following libraries to the linker (-l): cv cxcore highgui And the following library search path (-L): "$(OPENCV)/lib/" Eclipse, the compiler and the linker all succeed in including the headers and libraries. I am using the GNU C/C++ compiler & linker from Cygwin. When compiling, I get the following make error: src/Window.d:1: *** multiple target patterns. Stop. Window.d contains: src/Window.d src/Window.o: ../src/Window.cpp \ C:/Program\ Files/OpenCV/cv/include/cv.h \ C:/Program\ Files/OpenCV/cxcore/include/cxcore.h \ C:/Program\ Files/OpenCV/cxcore/include/cxtypes.h \ C:/Program\ Files/OpenCV/cxcore/include/cxerror.h \ C:/Program\ Files/OpenCV/cxcore/include/cvver.h \ C:/Program\ Files/OpenCV/cxcore/include/cxcore.hpp \ C:/Program\ Files/OpenCV/cv/include/cvtypes.h \ C:/Program\ Files/OpenCV/cv/include/cv.hpp \ C:/Program\ Files/OpenCV/cv/include/cvcompat.h \ C:/Program\ Files/OpenCV/otherlibs/highgui/highgui.h \ C:/Program\ Files/OpenCV/cxcore/include/cxcore.h ../src/Constants.h \ ../src/Window.h C:/Program\ Files/OpenCV/cv/include/cv.h: C:/Program\ Files/OpenCV/cxcore/include/cxcore.h: C:/Program\ Files/OpenCV/cxcore/include/cxtypes.h: C:/Program\ Files/OpenCV/cxcore/include/cxerror.h: C:/Program\ Files/OpenCV/cxcore/include/cvver.h: C:/Program\ Files/OpenCV/cxcore/include/cxcore.hpp: C:/Program\ Files/OpenCV/cv/include/cvtypes.h: C:/Program\ Files/OpenCV/cv/include/cv.hpp: C:/Program\ Files/OpenCV/cv/include/cvcompat.h: C:/Program\ Files/OpenCV/otherlibs/highgui/highgui.h: C:/Program\ Files/OpenCV/cxcore/include/cxcore.h: ../src/Window.h: I tried removing all OpenCV headers from Window.d (from line 2 onwards), but the error remains. Also, I've updated Eclipse and OpenCV, all to no avail. Do you have any ideas worth trying? I'm willing to try anything!
Are you working from a Cygwin installation? I've seen this problem before using Cygwin--basically, make sees the : in the path and thinks it is another target definition, hence the error. If you are working from a Cygwin installation, you might try replacing the c:/ with /cygdrive/c/. If not, you might try using relative paths or using a network mount and see if that fixes it.
2,402,374
2,402,588
Qt - reloading widget contents
I'm trying to modify the fridge magnets example by adding a button that will reload the widget where the draggable labels are drawn, reflecting any changes made to the text file it reads. I defined another class that would contain the button and the DragWidget object, so there would be an instance of this class instead of DragWidget in main(): class wrapWidget: public QWidget { Q_OBJECT public: wrapWidget(); }; wrapWidget::wrapWidget() { QGridLayout *gridlayout = new QGridLayout(); DragWidget *w = new DragWidget(); QPushButton *b = new QPushButton("refresh"); gridlayout ->addWidget(w,0,0); gridlayout ->addWidget(b,1,0); setLayout(gridlayout ); connect(b,SIGNAL(clicked()),w,SLOT(draw())); } The call to connect is where I'm trying to do the refresh thing. In the original fridge magnets example, all the label drawing code was inside the constructor of the DragWidget class. I moved that code to a public method that I named 'draw()', and called this method from the constructor instead. Here's DragWidget definition and implementation: #include <QWidget> QT_BEGIN_NAMESPACE class QDragEnterEvent; class QDropEvent; QT_END_NAMESPACE class DragWidget : public QWidget { public: DragWidget(QWidget *parent = 0); public slots: void draw(); protected: void dragEnterEvent(QDragEnterEvent *event); void dragMoveEvent(QDragMoveEvent *event); void dropEvent(QDropEvent *event); void mousePressEvent(QMouseEvent *event); void paintEvent(QPaintEvent *event); }; DragWidget::DragWidget(QWidget *parent) : QWidget(parent) { draw(); QPalette newPalette = palette(); newPalette.setColor(QPalette::Window, Qt::white); setPalette(newPalette); setMinimumSize(400, 100);//qMax(200, y)); setWindowTitle(tr("Fridge Magnets")); setAcceptDrops(true); } void DragWidget::draw(){ QFile dictionaryFile(":/dictionary/words.txt"); dictionaryFile.open(QFile::ReadOnly); QTextStream inputStream(&dictionaryFile); int x = 5; int y = 5; while (!inputStream.atEnd()) { QString word; inputStream >> word; if (!word.isEmpty()) { DragLabel *wordLabel = new DragLabel(word, this); wordLabel->move(x, y); wordLabel->show(); wordLabel->setAttribute(Qt::WA_DeleteOnClose); x += wordLabel->width() + 2; if (x >= 245) { x = 5; y += wordLabel->height() + 2; } } } } I thought that maybe calling draw() as a slot would be enough to reload the labels, but it didn't work. Putting the draw() call inside the widget's overriden paintEvent() instead of the constructor didn't work out as well, the program would end up in an infinite loop. What I did was obviously not the right way of doing it, so what should I be doing instead?
My quick guess is, you haven't added Q_OBJECT macro to dragwidget.h header, the moc file for DragWidget class wasn't generated and the connect failed with "no such slot as draw()" error. It might be also a good idea to add "CONFIG += console" to .pro file - you'll see all warning messages (like the one about connect error), so tracking such mistakes would be easier. You might also check return value of connect.
2,402,579
2,402,607
Function pointer to member function
I'd like to set up a function pointer as a member of a class that is a pointer to another function in the same class. The reasons why I'm doing this are complicated. In this example, I would like the output to be "1" class A { public: int f(); int (*x)(); } int A::f() { return 1; } int main() { A a; a.x = a.f; printf("%d\n",a.x()) } But this fails at compiling. Why?
The syntax is wrong. A member pointer is a different type category from a ordinary pointer. The member pointer will have to be used together with an object of its class: class A { public: int f(); int (A::*x)(); // <- declare by saying what class it is a pointer to }; int A::f() { return 1; } int main() { A a; a.x = &A::f; // use the :: syntax printf("%d\n",(a.*(a.x))()); // use together with an object of its class } a.x does not yet say on what object the function is to be called on. It just says that you want to use the pointer stored in the object a. Prepending a another time as the left operand to the .* operator will tell the compiler on what object to call the function on.
2,402,636
2,402,670
Object not declared in scope
I'm using Xcode for C++ on my computer while using Visual Studio at school. The following code worked just fine in Visual Studio, but I'm having this problem when using Xcode. clock c1(2, 3, 30); Everything works just fine, but it keeps giving me this error that says "Expected ';' before 'c1'" Fine, I put the ';' .. but then, it gives me this error: "'c1' was not declared in this scope" Here's the whole header code: #include <iostream> using namespace std; class clock { private: int h; int m; int s; public: clock(int hr, int mn, int sec); }; clock::clock(int hr, int mn, int sec) { h = hr; m = mn; s = sec; } Here's the whole .cpp code: #include "clock.h" int main() { clock c1(2, 3, 30); return 0; } I stripped everything down to where I had the problem. Everything else, as far as I know, is irrelevant since the problem remains the same with just the mentioned above. Thanks in advance!
There is a function clock that will hide your clock class of the same name. You can work this around by saying class clock c1(2, 3, 30); It's very bad practice to do using namespace std; in a header. Instead put that line into the cpp file only. It may solve your problem if you remove that line (if the name comes from namespace std:: instead of from the global namespace originally).
2,402,803
2,402,827
Creating a window application that will perform certain action after every 10 minutes
I was wondering would I still need to use a basic game loop for this particular operation?
You could create a timer and perform that action on WM_TIMER message handling or on timer proc function you specify when creating the timer. See SetTimer and WM_TIMER.
2,403,020
2,403,026
Why doesn't the C++ default destructor destroy my objects?
The C++ specification says the default destructor deletes all non-static members. Nevertheless, I can't manage to achieve that. I have this: class N { public: ~N() { std::cout << "Destroying object of type N"; } }; class M { public: M() { n = new N; } // ~M() { //this should happen by default // delete n; // } private: N* n; }; Then this should print the given message, but it doesn't: M* m = new M(); delete m; //this should invoke the default destructor
What makes you think the object n points to should be deleted by default? The default destructor destroys the pointer, not what it's pointing to. Edit: I'll see if I can make this a little more clear. If you had a local pointer, and it went out of scope, would you expect the object it points to to be destroyed? { Thing* t = new Thing; // do some stuff here // no "delete t;" } The t pointer is cleaned up, but the Thing it points to is not. This is a leak. Essentially the same thing is happening in your class.
2,403,330
2,403,628
Does COM automatically unload DLLs when there are no more object references?
For example, in language X: let x = CreateOject( "MyProgID" ) x.LateBoundCall() x.Release() // (or setting x to Nothing in VB-like language, etc) What happens to the DLL MyProgID lives in? Does COM unload DLLs automatically? EDIT This is assuming that the code above is in an executable that does not expose any COM.
Yes, but not in a deterministic way. Windows periodically asks every loaded DLL "is it safe to unload you now?" Any DLL that responds "Yes" is unloaded. Note a remark from MSDN : If a DLL loaded through a call to CoGetClassObject fails to export DllCanUnloadNow, the DLL will not be unloaded until the application calls the CoUninitialize function to release the OLE libraries. See this Old New Thing article.
2,403,354
2,403,503
How do I guarantee cleanup code runs in Windows C++ (SIGINT, bad alloc, and closed window)
I have a Windows C++ console program, and if I don't call ReleaseDriver() at the end of my program, some pieces of hardware enter a bad state and can't be used again without rebooting. I'd like to make sure ReleaseDriver() gets runs even if the program exits abnormally, for example if I hit Ctrl+C or close the console window. I can use signal() to create a signal handler for SIGINT. This works fine, although as the program ends it pops up an annoying error "An unhandled Win32 exception occurred...". I don't know how to handle the case of the console window being closed, and (more importantly) I don't know how to handle exceptions caused by bad memory accesses etc. Thanks for any help!
Under Windows, you can create an unhandled exception filter by calling SetUnhandledExceptionFilter(). Once done, any time an exception is generated that is not handled somewhere in your application, your handler will be called. Your handler can be used to release resources, generate dump files (see MiniDumpWriteDump), or whatever you need to make sure gets done. Note that there are many 'gotchas' surrounding how you write your exception handler function. In particular: You cannot call any CRT function, such as new You cannot perform any stack-based allocation If you do anything in your handler which causes an exception, Windows will immediately terminate your application by ripping the bones out of its back. You get no further chances to shut down gracefully. You can call many Windows API functions. But you can't sprintf, new, delete... In short, if it isn't a WINAPI function, it probably isn't safe. Because of all of the above, it is advisable to make all the variables in your handler function static variables. You won't be able to use sprintf, so you will have to format strings ahead of time, during initialization. Just remember that the machine is in a very unstable state when your handler is called.
2,403,355
2,403,395
Memory allocation in case of static variables
I am always confused about static variables, and the way memory allocation happens for them. For example: int a = 1; const int b = 2; static const int c = 3; int foo(int &arg){ arg++; return arg; } How is the memory allocated for a,b and c? What is the difference (in terms of memory) if I call foo(a), foo(b) and foo(c)?
I am always confused about static variables In global scope, static only means it will not be visible to other files when linking. How is the memory allocated for a,b and c? All of them will live in the executable file (e.g. the __DATA segment) which will be mapped into the RAM on execution. If the compiler is good, b and c will live in the read-only data region (e.g. the __TEXT segment), or even eliminated in optimization. What is the difference (in terms of memory) if I call foo(a), foo(b) and foo(c)? foo(b) and foo(c) will be compiler error because const int& cannot be converted to int&. Otherwise no difference. Pass by reference is equivalent to pass by pointer in the CPU's sense. So the address of each memory is taken, and foo is called.
2,403,371
2,407,005
Why do I get LNK2005 errors when compiling a PHP extension DLL
I'm trying to compile a PHP extension in VS2008. It is dependent on 3 other projects which I link statically. It used to work fine when I had all my code in one .cpp file. I separated the code into several files to make it more manageable and now it won't compile. I'm getting several (~100 per file) linker errors, LNK2005 (already defined). All of them are runtime library related I think. So far I've tried Clean rebuild. Made sure the /MTd flag is the same on all 4 projects. Made sure that all headers are guarded. Any ideas? EDIT: Here are some of the errors: Some errors: MPQBlock.obj : error LNK2005: _getwchar already defined in MPQArchive.obj MPQBlock.obj : error LNK2005: _putwchar already defined in MPQArchive.obj MPQBlock.obj : error LNK2005: _acosl already defined in MPQArchive.obj MPQBlock.obj : error LNK2005: _asinl already defined in MPQArchive.obj etc. MPQFile.obj : error LNK2005: _asinf already defined in MPQArchive.obj MPQFile.obj : error LNK2005: _atanf already defined in MPQArchive.obj MPQFile.obj : error LNK2005: _atan2f already defined in MPQArchive.obj MPQFile.obj : error LNK2005: _ceilf already defined in MPQArchive.obj MPQFile.obj : error LNK2005: _cosf already defined in MPQArchive.obj etc. PHPExtension.obj : error LNK2005: _acosl already defined in MPQArchive.obj PHPExtension.obj : error LNK2005: _asinl already defined in MPQArchive.obj PHPExtension.obj : error LNK2005: _atanl already defined in MPQArchive.obj PHPExtension.obj : error LNK2005: _atan2l already defined in MPQArchive.obj etc. zlibd.lib(zutil.obj) : warning LNK4217: locally defined symbol _malloc imported in function _zcalloc zlibd.lib(zutil.obj) : warning LNK4217: locally defined symbol _free imported in function _zcfree D:\Server\PHP\ext\php_mpq_library.dll : fatal error LNK1169: one or more multiply defined symbols found
change the order of the link libraries that might help... can you post the some errors... it will make picture more clearer... click Settings. click to select the project configuration that is getting the link errors. On the Link tab, click to select Input in the Category combo box. In the Ignore libraries box, insert the library names (for example, Nafxcwd.lib;Libcmtd.lib). Note The linker command-line equivalent in /NOD:. In the Object/library modules box, insert the library names. You must make sure that these are listed in order and as the first two libraries in the line (for example, Nafxcwd.lib Libcmtd.lib).
2,403,391
2,403,409
How does an extern "C" declaration work?
I'm taking a programming languages course and we're talking about the extern "C" declaration. How does this declaration work at a deeper level other than "it interfaces C and C++"? How does this affect the bindings that take place in the program as well?
extern "C" is used to ensure that the symbols following are not mangled (decorated). Example: Let's say we have the following code in a file called test.cpp: extern "C" { int foo() { return 1; } } int bar() { return 1; } If you run gcc -c test.cpp -o test.o Take a look at the symbols names: 00000010 T _Z3barv 00000000 T foo foo() keeps its name.
2,403,421
2,406,953
Get Pixel with Magic++
Can anybody show me an example how i get the pixel values of an Image ? I want to read an Image and iterate over it .. and print out the actual "red" value. Can anyone help ? i'm a beginner :(
There is a direct function in magic++ called read in the image class: image::read i.e image.read( 640, 480, "RGB", CharPixel, pixels ); in which pixels will give you arrays of pixel values... that you can use later. Or you can access direct low level pixels.. Here is how... http://www.imagemagick.org/Magick++/Image++.html#Raw%20Image%20Pixel%20Access
2,403,536
2,404,259
Pthreads in Visual C++
I'm experimenting with multithreading in Windows and was wondering whether I should use Win32 API use POSIX Threads for Windows Learning Pthreads would be useful if I tried to develop such applications on different platforms - but am I losing anything by not learning Win32 API? Or are both similar enough so that learning one allows me to figure out the other easily?
Use Boost Threads. When C++0x comes along, we will have std::threads. Boost threads has the closest implementation to std threads. else use pthreads. Pthreads is second closest to std::threads, and formed the main basis of std threads and boost threads. else do windows threading directly. You can still learn how threads work, and form a mental model of things. It just tends to use synchronization primitives that are a bit non-standard.
2,403,567
2,403,623
VC++ project: MSXML vs any other XML libraries
We are aware of MSXML, based on COM technologies. We want to use it for a VC++ project starting soon. Are there any other XML libraries do good compared to MSXML?
TinyXML - A C++ open source library
2,403,660
2,405,517
Determine processor support for SSE2?
I need to do determine processor support for SSE2 prior installing a software. From what I understand, I came up with this: bool TestSSE2(char * szErrorMsg) { __try { __asm { xorpd xmm0, xmm0 // executing SSE2 instruction } } #pragma warning (suppress: 6320) __except (EXCEPTION_EXECUTE_HANDLER) { if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION) { _tcscpy_s(szErrorMsg,MSGSIZE, _T("Streaming SIMD Extensions 2(SSE2) is not supported by the CPU.\r\n Unable to launch APP")); return false; } _tcscpy_s(szErrorMsg,MSGSIZE, _T("Streaming SIMD Extensions 2(SSE2) is not supported by the CPU.\r\n Unable to launch APP")); return false; } return true; } Would this work? I'm not really sure how to test, since my CPU supports it, so I don't get false from the function call. How do I determine processor support for SSE2?
Call CPUID with eax = 1 to load the feature flags in to edx. Bit 26 is set if SSE2 is available. Some code for demonstration purposes, using MSVC++ inline assembly (only for x86 and not portable!): inline unsigned int get_cpu_feature_flags() { unsigned int features; __asm { // Save registers push eax push ebx push ecx push edx // Get the feature flags (eax=1) from edx mov eax, 1 cpuid mov features, edx // Restore registers pop edx pop ecx pop ebx pop eax } return features; } // Bit 26 for SSE2 support static const bool cpu_supports_sse2 = (cpu_feature_flags & 0x04000000)!=0;
2,403,741
2,403,777
Get last/newly added element in std::set
can you get the last or newly added element in std::set? for example say if the loop runs to collect the elements to fill in the std::set. if on the first run the set was, [0] "A" [1] "B" [2] "D" and, on second run, the set becomes [0] "A" [1] "B" [2] "C" [3] "D" How would you check if 'C' is the new element that was added?
set::insert returns an iterator to the newly inserted item. Hold on to that iterator if you're interested in that item.
2,403,924
2,403,946
Call by reference in C++
What is actually passed in call by reference to a function? void foo(int &a,int &b) when I write foo(p,q) what is actually passed to the function. Is it the address of p and q?
What's actually passed to the function is a reference. The named parameter b becomes a synonym for the argument object q. How the compiler probably implements this that the caller places the address of q on the stack or in a register before calling, and the callee uses that value to effect all accesses to b. But it could be misleading to describe that as "actually passing" a pointer, because parameter passing is a concept at the level of the C++ language, and at that level it is not the same concept as passing a pointer. For instance, when you pass a pointer you can pass a null pointer, but when you pass a reference you cannot (validly). So it'd be wrong to say they're same thing. That said, the person implementing the compiler might describe it as "actually passing a pointer", and you know what they mean. For comparison, if char variables occupy 4-byte stack slots in the calling convention, they might say that the compiler is "actually passing an int". So it depends what "actually" is supposed to mean.
2,403,928
2,405,478
Partial template specialization of free functions - best practices
As most C++ programmers should know, partial template specialization of free functions is disallowed. For example, the following is illegal C++: template <class T, int N> T mul(const T& x) { return x * N; } template <class T> T mul<T, 0>(const T& x) { return T(0); } // error: function template partial specialization ‘mul<T, 0>’ is not allowed However, partial template specialization of classes/structs is allowed, and can be exploited to mimic the functionality of partial template specialization of free functions. For example, the target objective in the last example can be achieved by using: template <class T, int N> struct mul_impl { static T fun(const T& x) { return x * N; } }; template <class T> struct mul_impl<T, 0> { static T fun(const T& x) { return T(0); } }; template <class T, int N> T mul(const T& x) { return mul_impl<T, N>::fun(x); } It's more bulky and less concise, but it gets the job done -- and as far as users of mul are concerned, they get the desired partial specialization. My questions is: when writing templated free functions (that are intended to be used by others), should you automatically delegate the implementation to a static method function of a class, so that users of your library may implement partial specializations at will, or do you just write the templated function the normal way, and live with the fact that people won't be able to specialize them?
As litb says, ADL is superior where it can work, which is basically whenever the template parameters can be deduced from the call parameters: #include <iostream> namespace arithmetic { template <class T, class S> T mul(const T& x, const S& y) { return x * y; } } namespace ns { class Identity {}; // this is how we write a special mul template <class T> T mul(const T& x, const Identity&) { std::cout << "ADL works!\n"; return x; } // this is just for illustration, so that the default mul compiles int operator*(int x, const Identity&) { std::cout << "No ADL!\n"; return x; } } int main() { using arithmetic::mul; std::cout << mul(3, ns::Identity()) << "\n"; std::cout << arithmetic::mul(5, ns::Identity()); } Output: ADL works! 3 No ADL! 5 Overloading+ADL achieves what you would have achieved by partially specializing the function template arithmetic::mul for S = ns::Identity. But it does rely on the caller to call it in a way which allows ADL, which is why you never call std::swap explicitly. So the question is, what do you expect users of your library to have to partially specialize your function templates for? If they're going to specialize them for types (as is normally the case with algorithm templates), use ADL. If they're going to specialize them for integer template parameters, as in your example, then I guess you have to delegate to a class. But I don't normally expect a third party to define what multiplication by 3 should do - my library will do all the integers. I could reasonably expect a third party to define what multiplication by an octonion will do. Come to think of it, exponentiation might have been a better example for me to use, since my arithmetic::mul is confusingly similar to operator*, so there's no actual need to specialize mul in my example. Then I'd specialize/ADL-overload for the first parameter, since "Identity to the power of anything is Identity". Hopefully you get the idea, though. I think there is a downside to ADL - it effectively flattens namespaces. If I want to use ADL to "implement" both arithmetic::sub and sandwich::sub for my class, then I could be in trouble. I don't know what the experts have to say about that. By which I mean: namespace arithmetic { // subtraction, returns the difference of lhs and rhs template<typename T> const T sub(const T&lhs, const T&rhs) { return lhs - rhs; } } namespace sandwich { // sandwich factory, returns a baguette containing lhs and rhs template<typename SandwichFilling> const Baguette sub(const SandwichFilling&lhs, const SandwichFilling&rhs) { // does something or other } } Now, I have a type ns::HeapOfHam. I want to take advantage of std::swap-style ADL to write my own implementation of arithmetic::sub: namespace ns { HeapOfHam sub(const HeapOfHam &lhs, const HeapOfHam &rhs) { assert(lhs.size >= rhs.size && "No such thing as negative ham!"); return HeapOfHam(lhs.size - rhs.size); } } I also want to take advantage of std::swap-style ADL to write my own implementation of sandwich::sub: namespace ns { const sandwich::Baguette sub(const HeapOfHam &lhs, const HeapOfHam &rhs) { // create a baguette, and put *two* heaps of ham in it, more efficiently // than the default implementation could because of some special // property of heaps of ham. } } Hang on a minute. I can't do that, can I? Two different functions in different namespaces with the same parameters and different return types: not usually a problem, that's what namespaces are for. But I can't ADL-ify them both. Possibly I'm missing something really obvious. Btw, in this case I could just fully specialize each of arithmetic::sub and sandwich::sub. Callers would using one or the other, and get the right function. The original question talks about partial specialization, though, so can we pretend that specialization is not an option, without me actually making HeapOfHam a class template?
2,404,094
2,404,126
How do I get characters common to two vectors in C++?
I am trying to compare two vector objects, and return a single vector containing all the chars which appear in both vectors. How would I go about this without writing some horribly complex manual method which compares every char in the first vector to every char in the second vector and using an if to add it to a third vector (which would be returned) if they match. Maybe my lack of real experience with vectors is making me imagine this will be harder than it really is, but I suspect there is some simplier way which I have been unable to find through searching.
I think you're looking for std::set_intersection. The source vectors have to be sorted though. If you don't care about the order of your output vector, you could always run it on sorted copies of your source vectors. And BTW, the manual naive way isn't horribly complex. Given two source vectors s1 and s2, and a destination vector dest, you could write something that looks like this: for (std::vector<char>::iterator i = s1.begin(); i != s1.end(); ++i) { if (std::find(s2.begin(), s2.end(), *i) != s2.end()) { dest.push_back(*i); } } You have a lot of options for the find step depending on your choice of data structure.
2,404,103
2,404,566
ExpandEnvironmentStrings Not Expanding My Variables
I have a process under the Run key in the registry. It is trying to access an environment variable that I have defined in a previous session. I'm using ExpandEnvironmentStrings to expand the variable within a path. The environment variable is a user profile variable. When I run my process on the command line it does not expand as well. If I call 'set' I can see the variable. Some code... CString strPath = "\\\\server\\%share%" TCHAR cOutputPath[32000]; DWORD result = ExpandEnvironmentStrings((LPSTR)&strPath, (LPSTR)&cOutputPath, _tcslen(strPath) + 1); if ( !result ) { int lastError = GetLastError(); pLog->Log(_T( "Failed to expand environment strings. GetLastError=%d"),1, lastError); } When debugging Output path is exactly the same as Path. No error code is returned. What is goin on?
One problem is that you are providing the wrong parameters to ExpandEnvironmentStrings and then using a cast to hide that fact (although you do need a cast to get the correct type out of a CString). You are also using the wrong value for the last parameter. That should be the size of the output buffer, not the size of the input length (from the documentation the maximum number of characters that can be stored in the buffer pointed to by the lpDst parameter) Putting that altogether, you want: ExpandEnvironmentStrings((LPCTSTR)strPath, cOutputPath, sizeof(cOuputPath) / sizeof(*cOutputPath));
2,404,115
2,404,148
Is auto_ptr deprecated?
Will auto_ptr be deprecated in incoming C++ standard? Should unique_ptr be used for ownership transfer instead of shared_ptr? If unique_ptr is not in the standard, then do I need to use shared_ptr instead?
UPDATE: This answer was written in 2010 and as anticipated std::auto_ptr has been deprecated. The advice is entirely valid. In C++0x std::auto_ptr will be deprecated in favor of std::unique_ptr. The choice of smart pointer will depend on your use case and your requirements, with std::unique_ptr with move semantics for single ownership that can be used inside containers (using move semantics) and std::shared_ptr when ownership is shared. You should try to use the smart pointer that best fits the situation, choosing the correct pointer type provides other programmers with insight into your design.
2,404,150
2,404,229
Save all file names in a directory to a vector
I need to save all ".xml" file names in a directory to a vector. To make a long story short, I cannot use the dirent API. It seems as if C++ does not have any concept of "directories". Once I have the filenames in a vector, I can iterate through and "fopen" these files. Is there an easy way to get these filenames at runtime?
Something like this (Note, Format is a sprintf:ish funciton you can replace) bool MakeFileList(const wchar_t* pDirectory,vector<wstring> *pFileList) { wstring sTemp = Format(L"%s\\*.%s",pDirectory,L"xml"); _wfinddata_t first_file; long hFile = _wfindfirst(sTemp.c_str(),&first_file); if(hFile != -1) { wstring sFile = first_file.name; wstring sPath = Format(L"%s%s",pDirectory,sFile.c_str()); pFileList->push_back(sPath); while(_wfindnext(hFile,&first_file) != -1) { wstring sFile = first_file.name; wstring sPath = Format(L"%s%s",pDirectory,sFile.c_str()); pFileList->push_back(sPath); } _findclose(hFile); }else return false; return true; }
2,404,221
2,404,302
The question regarding cerr cout and clog
Can anybody explain the difference between cerr cout and clog and why does different objects are proposed? I know the differences are as below: 1) cout can redirected but cerr can't 2) clog can use buffer. I am confused about the point 2, I am grateful if anybody can elaborate it more.
Buffered output is typically much faster than unbuffered. So if you wanted to write a vast amount of data quickly to a log (but didn't care if it actually ended up there), you would use clog rather than cerr. And all streams can normally be redirected, assuming a vaguely competent operating system, but this is outwith the C++ standard, which has no such concept as "redirection".
2,404,288
2,404,329
How are exceptions allocated on the stack caught beyond their scope?
In the following code, the stack-based variable 'ex' is thrown and caught in a function beyond the scope in which ex was declared. This seems a bit strange to me, since (AFAIK) stack-based variables cannot be used outside the scope in which they were declared (the stack is unwound). void f() { SomeKindOfException ex(...); throw ex; } void g() { try { f(); } catch (SomeKindOfException& ex) { //Handling code... } } I've added a print statement to SomeKindOfException's destructor and it shows that ex is destructed once it goes out of scope in f() but then it's caught in g() and destructed again once it goes out of scope there as well. Any help?
The exception object is copied to a special location to survive the stack unwinding. The reason you see two destructions is because when you exit f() the original exception is destroyed and when you exit g() the copy is destroyed.
2,404,439
2,404,474
How do I bit shift a long by more than 32 bits?
It seems like I should be able to perform bit shift in C/C++ by more than 32 bits provided the left operand of the shift is a long. But this doesn't seem to work, at least with the g++ compiler. Example: unsigned long A = (1L << 37) gives A = 0 which isn't what I want. Am I missing something or is this just not possible? -J
Re-try this using a variable of type uint64_t (from stdint.h) instead of long. uint64_t is guaranteed to be 64 bits long and should behave as you expect.
2,404,567
2,404,600
How to reliably get size of C-style array?
How do I reliably get the size of a C-style array? The method often recommended seems to be to use sizeof, but it doesn't work in the foo function, where x is passed in: #include <iostream> void foo(int x[]) { std::cerr << (sizeof(x) / sizeof(int)); // 2 } int main(){ int x[] = {1,2,3,4,5}; std::cerr << (sizeof(x) / sizeof(int)); // 5 foo(x); return 0; } Answers to this question recommend sizeof but they don't say that it (apparently?) doesn't work if you pass the array around. So, do I have to use a sentinel instead? (I don't think the users of my foo function can always be trusted to put a sentinel at the end. Of course, I could use std::vector, but then I don't get the nice shorthand syntax {1,2,3,4,5}.)
In C array parameters in C are really just pointers so sizeof() won't work. You either need to pass in the size as another parameter or use a sentinel - whichever is most appropriate for your design. Some other options: Some other info: for C++, instead of passing a raw array pointer, you might want to have the parameter use something that wraps the array in a class template that keeps track of the array size and provides methods to copy data into the array in a safe manner. Something like STLSoft's array_proxy template or Boost's boost::array might help. I've used an array_proxy template to nice effect before. Inside the function using the parameter, you get std::vector like operations, but the caller of the function can be using a simple C array. There's no copying of the array - the array_proxy template takes care of packaging the array pointer and the array's size nearly automatically. a macro to use in C for determining the number of elements in an array (for when sizeof() might help - ie., you're not dealing with a simple pointer): Is there a standard function in C that would return the length of an array?
2,404,781
2,404,933
Insert an element to std::set using constructor
is it possible to insert a new element to std::set like in case of std::list for example: //insert one element named "string" to sublist of mylist std::list< std::list<string> > mylist; mylist.push_back(std::list<string>(1, "string")); Now, mylist has one element of type std::string in its sub-list of type std::list. How can you do the same in if std::set is the sub-set of std::list my list i.e std::list<std::set <string>> mylist; if you can't then why not?
I think this should do the trick: int main() { string s = "test"; set<string> mySet(&s, &s+1); cout << mySet.size() << " " << *mySet.begin(); return 0; } For clarification on the legality and validity of treating &s as an array, see this discussion: string s; &s+1; Legal? UB?
2,404,880
2,480,467
Graph algorithms (lib) with input graph in read-only shared memory on C/++
I would like to have a manager process sharing graphs via shared memory, read-only for other processes which will run various graph algorithms on these graphs. I would like to ask some questions emerged while researching the issue: Are there any graph libraries which are able to operate on (possibly their own) graph structures in read-only shm? That is, the algorithms would need to have their workspace and result buffers in the local process memory, and not use any buffers declared in the graph structure. Two libs which I know are famous are igraph and Boost. I don't know much about the C interface of the former and haven't used Boost yet. Any experience in the topic (regarding shm compatibility)? When looking in the Boost docs, I see that there is a Boost.Interprocess package with shm support. At first I thought about using manually crafted shm with mmapped shm (Linux platform). Is Boost superior and recommended over this method? Does the Boost Graph library plays nice along with manual shm or Interprocess? Apart from insights about these questions I would be glad to read about your experience regarding graph processing and shared memory. Thanks!
In Boost Graph Library the various graph types are just concepts ( http://www.boost.org/doc/libs/1_42_0/libs/graph/doc/graph_concepts.html ). You should be able to implement your own graph structure, adhere to the concept you need and apply any BGL algorithm on your own data (or perhaps just wrap your shared data in an edge_list class http://www.boost.org/doc/libs/1_42_0/libs/graph/doc/edge_list.html ). Since you are looking at shared memory you might also be interested in the Parallel BGL ( http://www.boost.org/doc/libs/1_42_0/libs/graph_parallel/doc/html/index.html ) HTH
2,405,045
2,405,074
C++ class with char pointers returning garbage
I created a class "Entry" to handle Dictionary entries, but in my main(), I create the Entry() and try to cout the char typed public members, but I get garbage. When I look at the Watch list in debugger, I see the values being set, but as soon as I access the values, there is garbage. Can anyone elaborate on what I might be missing? #include <iostream> using namespace std; class Entry { public: Entry(const char *line); char *Word; char *Definition; }; Entry::Entry(const char *line) { char tmp[100]; strcpy(tmp, line); Word = strtok(tmp, ",") + '\0'; Definition = strtok(0,",") + '\0'; } int main() { Entry *e = new Entry("drink,What you need after a long day's work"); cout << "Word: " << e->Word << endl; cout << "Def: " << e->Definition << endl; cout << endl; delete e; e = 0; return 0; }
Word and Definition both point into tmp, which has gone out of scope and so contains garbage.
2,405,115
2,405,139
Questions regarding ordering of catch statements in catch block - compiler specific or language standard?
I am currently using Visual Studio Express C++ 2008, and have some questions about catch block ordering. Unfortunately, I could not find the answer on the internet so I am posing these questions to the experts. I notice that unless catch (...) is placed at the end of a catch block, the compilation will fail with error C2311. For example, the following would compile: catch (MyException) { } catch (...) { } while the following would not: catch (...) { } catch (MyException) { } a. Could I ask if this is defined in the C++ language standard, or if this is just the Microsoft compiler being strict? b. Do C# and Java have the same rules as well? c. As an aside, I have also tried making a base class and a derived class, and putting the catch statement for the base class before the catch statement for the derived class. This compiled without problems. Are there no language standards guarding against such practice please?
According to the standard, the order is significant. Basically the first catch that matches the exception will be caught. a) Because catch(...) will make any following catches irrelevant, the standard only allows it to be the last catch. b) C# and Java have similar rules. c) catch (by reference or pointer) of a base before a derived class will make the code for the derived irrelevant. However, the standard does allow this
2,405,214
2,406,475
Optimize CUDA with Thrust in a loop
Given the following piece of code, generating a kind of code dictionary with CUDA using thrust (C++ template library for CUDA): thrust::device_vector<float> dCodes(codes->begin(), codes->end()); thrust::device_vector<int> dCounts(counts->begin(), counts->end()); thrust::device_vector<int> newCounts(counts->size()); for (int i = 0; i < dCodes.size(); i++) { float code = dCodes[i]; int count = thrust::count(dCodes.begin(), dCodes.end(), code); newCounts[i] = dCounts[i] + count; //Had we already a count in one of the last runs? if (dCounts[i] > 0) { newCounts[i]--; } //Remove thrust::detail::normal_iterator<thrust::device_ptr<float> > newEnd = thrust::remove(dCodes.begin()+i+1, dCodes.end(), code); int dist = thrust::distance(dCodes.begin(), newEnd); dCodes.resize(dist); newCounts.resize(dist); } codes->resize(dCodes.size()); counts->resize(newCounts.size()); thrust::copy(dCodes.begin(), dCodes.end(), codes->begin()); thrust::copy(newCounts.begin(), newCounts.end(), counts->begin()); The problem is, that i've noticed multiple copies of 4 bytes, by using CUDA visual profiler. IMO this is generated by The loop counter i float code, int count and dist Every access to i and the variables noted above This seems to slow down everything (sequential copying of 4 bytes is no fun...). So, how i'm telling thrust, that these variables shall be handled on the device? Or are they already? Using thrust::device_ptr seems not sufficient for me, because i'm not sure whether the for loop around runs on host or on device (which could also be another reason for the slowliness).
for every reiteration of i, size, index, code, etc. have to be copied from host to device.. the way you have your program, there is not much you can do. For best results, consider moving entire i loop on the device, this way you will not have host to device copies. Trust is great for some things, however where performance is concerned and algorithm does not quite fit available functions, you may have to rewrite for best performance without using thrust algorithms explicitly.
2,405,242
2,405,285
Cartesian product of several vectors
similar questions have been asked before but I cant find an exact match to my question. I have 4 vectors each of which hold between 200-500 4 digit integers. The exact number of elements in each vector varies but I could fix it to a specific value. I need to find all possible combinations of the elements in these 4 vectors. eg: v1[10, 30] v2[11, 45] v3[63, 56] v4[82, 98] so I'd get something like this: [10, 11, 63, 82]; [30, 11, 63, 82]; [10, 45, 63, 82]; [10, 45, 56, 82] etc.. Is there a common name for this algorithm so I can find some references to it online? Otherwise any tips on implementing this in C++ would be helpful. Performance isn't much of an issue as I only need to run the algorithm once. Is there anything built into the STL?
Not much of an algorithm... for(vector<int>::const_iterator i1 = v1.begin(); i1 != v1.end(); ++i1) for(vector<int>::const_iterator i2 = v2.begin(); i2 != v2.end(); ++i2) for(vector<int>::const_iterator i3 = v3.begin(); i3 != v3.end(); ++i3) for(vector<int>::const_iterator i4 = v4.begin(); i4 != v4.end(); ++i4) cout << "[" << *i1 << "," << *i2 << "," << *i3 << "," << *i4 << "]" << endl;
2,405,555
2,405,582
string s; &s+1; Legal? UB?
Consider the following code: #include <cstdlib> #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main() { string myAry[] = { "Mary", "had", "a", "Little", "Lamb" }; const size_t numStrs = sizeof(myStr)/sizeof(myAry[0]); vector<string> myVec(&myAry[0], &myAry[numStrs]); copy( myVec.begin(), myVec.end(), ostream_iterator<string>(cout, " ")); return 0; } Of interest here is &myAry[numStrs]: numStrs is equal to 5, so &myAry[numStrs] points to something that doesn't exist; the sixth element in the array. There is another example of this in the above code: myVec.end(), which points to one-past-the-end of the vector myVec. It's perfecly legal to take the address of this element that doesn't exist. We know the size of string, so we know where the address of the 6th element of a C-style array of strings must point to. So long as we only evaluate this pointer and never dereference it, we're fine. We can even compare it to other pointers for equality. The STL does this all the time in algorithms that act on a range of iterators. The end() iterator points past the end, and the loops keep looping while a counter != end(). So now consider this: #include <cstdlib> #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main() { string myStr = "Mary"; string* myPtr = &myStr; vector<string> myVec2(myPtr, &myPtr[1]); copy( myVec2.begin(), myVec2.end(), ostream_iterator<string>(cout, " ")); return 0; } Is this code legal and well-defined? It is legal and well-defined to take the address of an array element past the end, as in &myAry[numStrs], so should it be legal and well-defined to pretend that myPtr is also an array?
It is legal and not UB to have a pointer to "one past the end" of an array, and any single object can be treated as if it were in an array of length 1; however, you need to use ptr + 1 instead due to the technicality of &ptr[1] dereferencing and then taking the address. This also applies to &array[size] becoming array + size. What you have will work as you expect on all platforms of which I'm aware, but given how easy it is to use the unambiguously correct form, I see no reason not to do that instead.
2,405,722
2,405,781
Why is it not possible to access the size of a new[]'d array?
When you allocate an array using new [], why can't you find out the size of that array from the pointer? It must be known at run time, otherwise delete [] wouldn't know how much memory to free. Unless I'm missing something?
In a typical implementation the size of dynamic memory block is somehow stored in the block itself - this is true. But there's no standard way to access this information. (Implementations may provide implementation-specific ways to access it). This is how it is with malloc/free, this is how it is with new[]/delete[]. In fact, in a typical implementation raw memory allocations for new[]/delete[] calls are eventually processed by some implementation-specific malloc/free-like pair, which means that delete[] doesn't really have to care about how much memory to deallocate: it simply calls that internal free (or whatever it is named), which takes care of that. What delete[] does need to know though is how many elements to destruct in situations when array element type has non-trivial destructor. And this is what your question is about - the number of array elements, not the size of the block (these two are not the same, the block could be larger than really required for the array itself). For this reason, the number of elements in the array is normally also stored inside the block by new[] and later retrieved by delete[] to perform the proper array element destruction. There are no standard ways to access this number either. (This means that in general case, a typical memory block allocated by new[] will independently, simultaneously store both the physical block size in bytes and the array element count. These values are stored by different levels of C++ memory allocation mechanism - raw memory allocator and new[] itself respectively - and don't interact with each other in any way). However, note that for the above reasons the array element count is normally only stored when the array element type has non-trivial destructor. I.e. this count is not always present. This is one of the reasons why providing a standard way to access that data is not feasible: you'd either have to store it always (which wastes memory) or restrict its availability by destructor type (which is confusing). To illustrate the above, when you create an array of ints int *array = new int[100]; the size of the array (i.e. 100) is not normally stored by new[] since delete[] does not care about it (int has no destructor). The physical size of the block in bytes (like, 400 bytes or more) is normally stored in the block by the raw memory allocator (and used by raw memory deallocator invoked by delete[]), but it can easily turn out to be 420 for some implementation-specific reason. So, this size is basically useless for you, since you won't be able to derive the exact original array size from it.
2,405,731
2,410,608
Using ACE_Service_Object
I'm trying to use the ACE_Service_Object or the ACE_Shared_Object. I'm not sure which one is applicable. I'm trying to encapsulate some functionality in a DLL so a consumer of the DLL would open the library, create an instance of the exported class, call some functions on the class, and then destroy the class. A basic plug-in architecture of sorts. What would be the best way to go about this using the ACE classes. They seem to wrap a lot of the DLL loading, lookup & unloading minutia, which would be nice to use. The code below is basically what I want to mimic using the ACE classes. void* handle = dlopen("./libdllbaseclass.so", RTLD_LAZY); DllBaseClass* (*create)(); void (*destroy)(DllBaseClass*); create = (DllBaseClass* (*)())dlsym(handle, "create_object"); destroy = (void (*)(DllBaseClass*))dlsym(handle, "destroy_object"); DllBaseClass* myClass = (DllBaseClass*)create(); myClass->DoSomething(); destroy( myClass );
If all you need is to load, unload, and call some functions in a shared library, you could use the ACE_DLL class instead. That's what ACE_Shared_Object ends up using under the covers.
2,405,776
2,405,800
Programmatically monitor files on Windows
I'm looking for a way to monitor which processes are using (or attempting to access) a file over a duration of time. What are some good Windows APIs or tools to achieve this?
FileSystemWatcher is not suitable for determining the process. There already was a different question. look here, this solution fits your needs.
2,405,849
2,405,882
How does one modify the thread scheduling behavior when using Threading Building Blocks (TBB)?
Does anyone know how to modify the thread scheduling (specifically affinity) when using TBB? Doing a high level analysis on a simple parallel-for application, it seems like TBB is specifying the underlying threads' affinity in a way that reduces performance. Specifically, the cores I'm running on have hyper-threading enabled, and it looks like TBB is affinitizing threads to the same core even if there is a different core left completely unloaded. FWIW, I realize it's likely that TBB is doing the "right thing" and that changing the threads' affinity will only reduce performance. I'd just like to experiment with it to see if that's really the case.
TBB 2.1 added an affinity partitioner which assigns tasks to threads based on cache affinity. Using this partitioner instead of the default one might help out. You can also dive into individual tasks and use tbb::task::set_affinity (documentation here). The scheduler can notify you if the task happens to run on a thread other than the one indicated by its affinity if your subclass of tbb::task implements the note_affinity() callback.
2,405,871
2,405,891
Temporary non-const istream reference in constructor (C++)
It seems that a constructor that takes a non-const reference to an istream cannot be constructed with a temporary value in C++. #include <iostream> #include <sstream> using namespace std; class Bar { public: explicit Bar(std::istream& is) {} }; int main() { istringstream stream1("bar1"); Bar bar1(stream1); // OK on all platforms // compile error on linux, Mac gcc; OK on Windows MSVC Bar bar2(istringstream("bar2")); return 0; } This compiles fine with MSVC, but not with gcc. Using gcc I get a compile error: g++ test.cpp -o test test.cpp: In function ‘int main()’: test.cpp:18: error: no matching function for call to ‘Bar::Bar(std::istringstream)’ test.cpp:9: note: candidates are: Bar::Bar(std::istream&) test.cpp:7: note: Bar::Bar(const Bar&) Is there something philosophically wrong with the second way (bar2) of constructing a Bar object? It looks nicer to me, and does not require that stream1 variable that is only needed for a moment. EDIT: In response to Johannes Schaub's comment I'd like to give a bit more context. First, this is not the first time I have been annoyed by this behavior of C++, so I am genuinely interested in the higher level philosophical discussion of this issue. That said, in this particular case I have a class that reads in a file that contains data used to construct the object. I also like to write automated tests that use a string instead of the file. But using the file for construction is the primary use case. So I decided to make a constructor that takes an istream, so I could use either a file(stream), or a string(stream). That is how I got here. My test programs construct objects directly from strings, to simulate reading files. This saves me the trouble of creating separate data files for each little test.
This is just how C++ works currently: you cannot bind non-const references to temporary objects. MSVC is non-standard in allowing this. C++0x will have r-value references and change things around a bit here. There are various philosophical interpretations people have tried to apply—for both sides of the issue—but I haven't found one that is wholly convincing. It seems more of "you just have to pick one behavior and stick to it", which explains both current C++ and 0x's changes: the chosen behavior has shifted.
2,406,060
2,406,088
Virtual Function Implementation
I have kept hearing this statement. Switch..Case is Evil for code maintenance, but it provides better performance(since compiler can inline stuffs etc..). Virtual functions are very good for code maintenance, but they incur a performance penalty of two pointer indirections. Say i have a base class with 2 subclasses(X and Y) and one virtual function, so there will be two virtual tables. The object has a pointer, based on which it will choose a virtual table. So for the compiler, it is more like switch( object's function ptr ) { case 0x....: X->call(); break; case 0x....: Y->call(); }; So why should virtual function cost more, if it can get implemented this way, as the compiler can do the same in-lining and other stuff here. Or explain me, why is it decided not to implement the virtual function execution in this way? Thanks, Gokul.
The compiler can't do that because of the separate compilation model. At the time the virtual function call is being compiled, there is no way for the compiler to know for sure how many different subclasses there are. Consider this code: // base.h class base { public: virtual void doit(); }; and this: // usebase.cpp #include "base.h" void foo(base &b) { b.doit(); } When the compiler is generating the virtual call in foo, it has no knowledge of which subclasses of base will exist at runtime.
2,406,095
2,406,138
Does boost::asio::deadline_timer use a thread for each timer?
I have a list of items that I need to update on different intervals. The list can grow to be thousands of items long. Each item could potentially have a different interval. If I create one timer per item, am I going to saturate the system with threads? I was thinking it might be better to create one timer equal to the smallest interval in the set of items, and then on each update increment a counter, and then check to see if the counter is now equal to any other intervals. This should work provided the smallest interval is a multiple of all the other intervals. Any suggestions?
Boost does not use a thread per timer, it keeps a timer queue. Every timer is created with boost::asio::io_service object that does the actual work. This object can dispatch its work in one or more threads, when you run boost::asio::io_service::run() explicitly from multiple threads, but there is no one-to-one correspondence between timers and threads, and Asio will not create threads behind your back.
2,406,144
2,406,153
C++ overide global operator comma gives error
the second function gives error C2803 http://msdn.microsoft.com/en-us/library/zy7kx46x%28VS.80%29.aspx : 'operator ,' must have at least one formal parameter of class type. any clue? template<class T,class A = std::allocator<T>> class Sequence : public std::vector<T,A> { public: Sequence<T,A>& operator,(const T& a) { this->push_back(a); return *this; } Sequence<T,A>& operator,(const Sequence<T,A>& a) { for(Sequence<T,A>::size_type i=0 ; i<a.size() ; i++) { this->push_back(a.at(i)); } return *this; } }; //this works! template<typename T> Sequence<T> operator,(const T& a, const T&b) { Sequence<T> seq; seq.push_back(a); seq.push_back(b); return seq; } //this gives error C2803! Sequence<double> operator,(const double& a, const double& b) { Sequence<double> seq; seq.push_back(a); seq.push_back(b); return seq; }
Change that to: Sequence<double> operator,(const Sequence<double>& a, const double& b) { Sequence<double> seq(a); seq.push_back(b); return seq; } or (based on this article): Sequence<double> operator,(Sequence<double> seq, const double& b) { seq.push_back(b); return seq; }
2,406,168
2,413,673
Constraining window position to desktop working area
I want to allow a user to drag my Win32 window around only inside the working area of the desktop. In other words, they shouldn't be able to have any part of the window extend outside the monitor(s) nor should the window overlap the taskbar. I'd like to do it in a way that does cause any stuttering. Handling WM_MOVE messages and calling MoveWindow() to reposition the window if it goes off works, but I don't like the flickering effect that's caused by MoveWindow(). I also tried handling WM_MOVING which prevents the need to call MoveWindow() by altering the destination rectangle before the move actually happens. This resolves the flickering problem, but another issue I run into is that the cursor some times gets aways from the window when a drag occurs allowing the user to drag the window around while the cursor is not even inside the window. How do I constrain my window without running into these issues?
Keep in mind that users with multi-monitor setups may have a desktop that extends into negative x- and y-coordinates, or that is not rectangular. Also, some users use alternative window managers such as LiteStep, which implement virtual desktops by moving them off-screen; if you try to fight this, your application will break for these users.
2,406,211
2,443,727
What libraries should I use to manipulate archives from C++?
I want to manipulate .zip and .rar files from C++. What libraries should I use?
zlib and minizip, yes. minizip was last updated in 2005. Some facts about version 1.01e: This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g, WinZip, InfoZip tools and compatible. Multi volume ZipFile (span) are not supported. Encryption compatible with pkzip 2.04g only supported Old compressions used by old PKZip 1.x are not supported boost::iostreams also is a good choice. Open Source Ogre3d has implementation of zip decompressor, you can read it.
2,406,224
2,433,527
Cross Platform C++ webserver Library
I am looking for a cross platform Library in C++ that can run a web server. Does any one know if tntnet can work on windows computers. or libmicrohttpd
POCO has a HTTP server, among lots of other useful stuff. Runs on Windows, Linux, etc.
2,406,247
2,406,514
How to skip integers in C++ taken from a fstream txt file?
I need to create a function that uses a loop. This function will open a text file and then must be able to skip a variable number of leading random integers. The program must be able to handle any number of leading random integers. Example if the opened file reads this on its first line: 100 120 92 82 38 49 102 and the SKIP_NUMBER variable is assigned 3 the number the function would grab is 82. The function must continue to grab the integers every SKIP_NUMBER until it reaches the end of the file. These integers taken from the txt file are then placed into another text file. Please help I'm really lost on how to create this loop! :D Here is my function so far... //Function skips variables and returns needed integer int skipVariable (int SKIP_NUMBER) { return 0; //temporary return } These are my program variables: // initialize function/variables ifstream fin; string IN_FILE_NAME, OUT_FILE_NAME; int SKIP_NUMBER;
If I were you, I would approach this problem like this: 1. create ifstream object m_strm 2. open the file 3. whie (m_strm.good()) (a.) use ifstream's getline() to read a line from the file (b.) use strtok() function to tokenize the string (for whitespaces) (c.) maintain a counter when you keep getting tokens (d.) Now you can skip whenever you like. 4. Done with file, so close the stream!
2,406,372
2,406,544
Test Driven Development with C++: How to test a class which depends on other classes?
Suppose I have a class A which depends on 3 other classes X, Y and Z, either A uses these through a reference or a pointer or say A is templated to be instantiated with X, Y and Z doesn't matter, the key is that in order to test A, I need to have X, Y and Z. So I need to have fakes for A, B and C. Suppose I write them. Now, how do I swap real and fake objects easily? I can see that this works very easily in the case of templates. In order to make it work when A depends on X, Y and Z through a reference or a pointer, I would need to have a base class say X_Interface from which I can inherit X_Real and X_Fake. So basically, I would end up in having 3 times the number of classes for every class that would need to have a fake. I am most likely missing something. There has to be a simpler way to do this. Having a base class X_Interface is also quite expensive as I will be using more space and making virtual calls. I guess I could use CRTP as I know whether its a X_Real or X_Fake at compile time but still there must be a better way.
First make sure that the objects you depend on (X, Y & Z) are passed in at the constructor, this way you can easily pass in 'fakes' when you are testing. (I really hope you are using a unit test framework, like CUnit) Now when you are writing the test, all you need to do is make up 'fakes' for the objects the class under test depends on. Often you can just pass in 'null', but if you really need to do something with that 'fake' you can simply instantiate it (you made sure all its dependencies are passed in at the constructor too, right? right!). Or in an extreme case you might extend the class that is depended upon and reimplement some key methods to suit your test. So now in most cases you don't need a 'fake', sometimes you simply instantiate a real 'fake', and in rare cases you have an extra class that resides only in your test code. Look at this video for a much better explanation. There are more on this topic from GoogleTechTalks, but you'll manage from here.
2,406,410
2,412,265
SWIG_NewPointerObj and values always being nil
I'm using SWIG to wrap C++ objects for use in lua, and Im trying to pass data to a method in my lua script, but it always comes out as 'nil' void CTestAI::UnitCreated(IUnit* unit){ lua_getglobal(L, "ai"); lua_getfield(L, -1, "UnitCreated"); swig_module_info *module = SWIG_GetModule( L ); swig_type_info *type = SWIG_TypeQueryModule( module, module, "IUnit *" ); SWIG_NewPointerObj(L,unit,type,0); lua_epcall(L, 1, 0); } Here is the lua code: function AI:UnitCreated(unit) if(unit == nil) then game:SendToConsole("I CAN HAS nil ?") else game:SendToConsole("I CAN HAS UNITS!!!?") end end unit is always nil. I have checked and in the C++ code, the unit pointer is never invalid/null I've also tried: void CTestAI::UnitCreated(IUnit* unit){ lua_getglobal(L, "ai"); lua_getfield(L, -1, "UnitCreated"); SWIG_NewPointerObj(L,unit,SWIGTYPE_p_IUnit,0); lua_epcall(L, 1, 0); } with identical results. Why is this failing? How do I fix it?
When you use the colon in function AI:UnitCreated(unit), it creates a hidden self parameter that receives the AI instance. It actually behaves like this: function AI.UnitCreated(self, unit) So when calling that function from C, you need to pass both parameters: the ai instance and the unit parameter. Since you passed only one parameter, self was set to it and unit was set to nil.
2,406,485
2,406,515
What is an overloaded operator in C++?
I realize this is a basic question but I have searched online, been to cplusplus.com, read through my book, and I can't seem to grasp the concept of overloaded operators. A specific example from cplusplus.com is: // vectors: overloading operators example #include <iostream> using namespace std; class CVector { public: int x,y; CVector () {}; CVector (int,int); CVector operator + (CVector); }; CVector::CVector (int a, int b) { x = a; y = b; } CVector CVector::operator+ (CVector param) { CVector temp; temp.x = x + param.x; temp.y = y + param.y; return (temp); } int main () { CVector a (3,1); CVector b (1,2); CVector c; c = a + b; cout << c.x << "," << c.y; return 0; } From http://www.cplusplus.com/doc/tutorial/classes2/ but reading through it I'm still not understanding them at all. I just need a basic example of the point of the overloaded operator (which I assume is the "CVector CVector::operator+ (CVector param)"). There's also this example from wikipedia: Time operator+(const Time& lhs, const Time& rhs) { Time temp = lhs; temp.seconds += rhs.seconds; if (temp.seconds >= 60) { temp.seconds -= 60; temp.minutes++; } temp.minutes += rhs.minutes; if (temp.minutes >= 60) { temp.minutes -= 60; temp.hours++; } temp.hours += rhs.hours; return temp; } From "http://en.wikipedia.org/wiki/Operator_overloading" The current assignment I'm working on I need to overload a ++ and a -- operator. Thanks in advance for the information and sorry about the somewhat vague question, unfortunately I'm just not sure on it at all.
Operator overloading is the technique that C++ provides to let you define how the operators in the language can be applied to non-built in objects. In you example for the Time class operator overload for the + operator: Time operator+(const Time& lhs, const Time& rhs); With that overload, you can now perform addition operations on Time objects in a 'natural' fashion: Time t1 = some_time_initializer; Time t2 = some_other_time_initializer; Time t3 = t1 + t2; // calls operator+( t1, t2) The overload for an operator is just a function with the special name "operator" followed by the symbol for the operator being overloaded. Most operators can be overloaded - ones that cannot are: . .* :: and ?: You can call the function directly by name, but usually don't (the point of operator overloading is to be able to use the operators normally). The overloaded function that gets called is determined by normal overload resolution on the arguments to the operator - that's how the compiler knows to call the operator+() that uses the Time argument types from the example above. One additional thing to be aware of when overloading the ++ and -- increment and decrement operators is that there are two versions of each - the prefix and the postfix forms. The postfix version of these operators takes an extra int parameter (which is passed 0 and has no purpose other than to differentiate between the two types of operator). The C++ standard has the following examples: class X { public: X& operator++(); //prefix ++a X operator++(int); //postfix a++ }; class Y { }; Y& operator++(Y&); //prefix ++b Y operator++(Y&, int); //postfix b++ You should also be aware that the overloaded operators do not have to perform operations that are similar to the built in operators - being more or less normal functions they can do whatever you want. For example, the standard library's IO stream interface uses the shift operators for output and input to/from streams - which is really nothing like bit shifting. However, if you try to be too fancy with your operator overloads, you'll cause much confusion for people who try to follow your code (maybe even you when you look at your code later). Use operator overloading with care.
2,406,642
2,409,303
Monitoring processes of the Windows OS using the C language
I want to make an application in C or C++ which have to monitor some specific processes. How can I make it possible in C?
You said that you have tomaonitor "some specific processes". If your application started the processes, you can extract the process handles from the PROCESS_INFORMATION structure (field hProcess) you passed to the CreateProcess function. If the process you want to track has been launched in some different way, you need the process' ID (PID), and use it as third argument of OpenProcess to obtain an handle. So you can use the WaitForSingleObject or WaitForMultipleObjects functions to wait for the process completion. Optionally you can obtain the process' exit code with the GetExitCodeProcess function. There are other ways by which an application can start a new process (e.g. by the _system() library function), but I strongly suggest to use CreateProcess directly in your code, since you can control the child process' behaviour completely (e.g. you can select the priority, pass stdin/stdout/stderr handles, decide the startup window's characteristics...). Suggested example: http://msdn.microsoft.com/en-us/library/ms682512%28VS.85%29.aspx
2,406,764
2,406,807
What happens when we combine RAII and GOTO?
I'm wondering, for no other purpose than pure curiosity (because no one SHOULD EVER write code like this!) about how the behavior of RAII meshes with the use of goto (lovely idea isn't it). class Two { public: ~Two() { printf("2,"); } }; class Ghost { public: ~Ghost() { printf(" BOO! "); } }; void foo() { { Two t; printf("1,"); goto JUMP; } Ghost g; JUMP: printf("3"); } int main() { foo(); } When running the following code in Visual Studio 2005 I get the following output. 1,2,3 BOO! However I imagined, guessed, hoped that 'BOO!' wouldn't actually appear as the Ghost should have never been instantiated (IMHO, because I don't know the actual expected behavior of this code). What's up? I just realized that if I instantiate an explicit constructor for Ghost the code doesn't compile... class Ghost { public: Ghost() { printf(" HAHAHA! "); } ~Ghost() { printf(" BOO! "); } }; Ah, the mystery ...
The standard talks about this explicitly - with an example; 6.7/3 "Declaration statement" (emphasis added by me): Variables with automatic storage duration are initialized each time their declaration-statement is executed. Variables with automatic storage duration declared in the block are destroyed on exit from the block. It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type and is declared without an initializer. [Example: void f() { //... goto lx; //ill-formed: jump into scope of a //... ly: X a = 1; //... lx: goto ly; //OK, jump implies destructor //call for a, followed by construction //again immediately following label ly } —end example] So it seems to me that MSVC's behavior is not standards compliant - Ghost is not a POD type, so the compiler should issue an error when the the goto statement is coded to jump past it. A couple other compilers I tried (GCC and Digital Mars) issue errors. Comeau issues a warning (but in fairness, my build script for Comeau has it configured for high MSVC compatibility, so it might be following Microsoft's lead intentionally).
2,406,972
2,407,873
Problem in passing arrays from C# to C++
I have an application in which I need to pass an array from C# to a C++ DLL. What is the best method to do it? I did some search on Internet and figured out that I need to pass the arrays from C# using ref. The code for the same: status = IterateCL(ref input, ref output); The input and output arrays are of length 20. and the corresponding code in C++ DLL is IterateCL(int *&inArray, int *&outArray) This works fine for once. But if I try to call the function from C# in a loop the second time, the input array in C# is showing up as an array of one element. Why is this happening and please help me how I can call this function iteratively from C#. Thanks, Rakesh.
You need to use: [DllImport("your_dll")] public extern void IterateCL([In, MarshalAs(UnmanagedType.LPArray)] int[] arr1, [Out, MarshalAs(UnmanagedType.LPArray)] int[] arr2);
2,407,077
2,407,145
Read from cin or a file
When I try to compile the code istream in; if (argc==1) in=cin; else { ifstream ifn(argv[1]); in=ifn; } gcc fails, complaining that operator= is private. Is there any way to set an istream to different values based on a condition?
You can replace cin's streambuf with another, and in some programs this is simpler than the general strategy of passing around istreams without referring to cin directly. int main(int argc, char* argv[]) { ifstream input; streambuf* orig_cin = 0; if (argc >= 2) { input.open(argv[1]); if (!input) return 1; orig_cin = cin.rdbuf(input.rdbuf()); cin.tie(0); // tied to cout by default } try { // normal program using cin } catch (...) { if (orig_cin) cin.rdbuf(orig_cin); throw; } return 0; } Even though it's extremely rare to use cin after control leaves main, the above try-catch avoids undefined behavior if that's something your program might do.
2,407,257
2,407,417
Disable keyboard keys when the console of c Run using c or c++
I want to disable keyboard when my program Run, means that no one can use alt+F4 etc. How I can make it possible using c in window OS.
Handle WM_SYSKEYUP , WM_SYSKEYDOWN and return 0 Here's the WndProc to handle these messages LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_SYSKEYDOWN: case WM_SYSKEYUP: case WM_KEYDOWN: case WM_KEYUP: return 0; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
2,407,451
2,409,438
Find unique vertices from a 'triangle-soup'
I am building a CAD-file converter on top of two libraries (Opencascade and DWF Toolkit). However, my question is plattform agnostic: Given: I have generated a mesh as a list of triangular faces form a model constructed through my application. Each Triangle is defined through three vertexes, which consist of three floats (x, y & z coordinate). Since the triangles form a mesh, most of the vertices are shared by more then one triangle. Goal: I need to find the list of unique vertices, and to generate an array of faces consisting of tuples of three indices in this list. What i want to do is this: //step 1: build a list of unique vertices for each triangle for each vertex in triangle if not vertex in listOfVertices Add vertex to listOfVertices //step 2: build a list of faces for each triangle for each vertex in triangle Get Vertex Index From listOfvertices AddToMap(vertex Index, triangle) While I do have an implementation which does this, step1 (the generation of the list of unique vertices) is really slow in the order of O(n!), since each vertex is compared to all vertices already in the list. I thought "Hey, lets build a hashmap of my vertices' components using std::map, that ought to speed things up!", only to find that generating a unique key from three floating point values is not a trivial task. Here, the experts of stackoverflow come into play: I need some kind of hash-function which works on 3 floats, or any other function generating a unique value from a 3d-vertex position.
Dump all the vertices in an array, then do unique(sort(array)). This should be O(k n log(n)), where k is the average number of triangles that share a vertex, usually k<7. The only caveat I can think of is that your unique function should be able to take a pointer to a comparison function, since you probably want to consider your vertices equal if distance(vertex1, vertex2) < threshold but that seems to be OK.
2,407,558
2,407,677
pthreads: reader/writer locks, upgrading read lock to write lock
I'm using read/write locks on Linux and I've found that trying to upgrade a read locked object to a write lock deadlocks. i.e. // acquire the read lock in thread 1. pthread_rwlock_rdlock( &lock ); // make a decision to upgrade the lock in threads 1. pthread_rwlock_wrlock( &lock ); // this deadlocks as already hold read lock. I've read the man page and it's quite specific. The calling thread may deadlock if at the time the call is made it holds the read-write lock (whether a read or write lock). What is the best way to upgrade a read lock to a write lock in these circumstances.. I don't want to introduce a race on the variable I'm protecting. Presumably I can create another mutex to encompass the releasing of the read lock and the acquiring of the write lock but then I don't really see the use of read/write locks. I might as well simply use a normal mutex. Thx
What else than a dead lock do you want in the following scenario? thread 1 acquire read lock thread 2 acquire read lock thread 1 ask to upgrade lock to write thread 2 ask to upgrade lock to write So I'd just release the read lock, acquire the write lock and check again if I've to make the update or not.
2,407,690
2,410,363
Lookin' for a container and memory pool solution
In an embedded program I have a screen object that needs to manage a list of items to display. The initial list of items will be pulled from a simple DB on screen load and the list will be updated via "Add" and "Remove" events. This list needs to be sorted according to certain criteria. I am looking of a container class that can help me accomplish this. Furthermore there is no dynamic memory in the system so I need to have a memory pool of empty items that I can load into container and return to the free pool when I am done with the item. Anyone know of anything appropriate in the C++ Standard Library or Boost? Or perhaps another solution?
If you use a standard container (such as std::map or std::set) you need to worry about different dynamic allocations: the allocation of the internal container data structures and the allocation of your own data you want to store in the container. The allocation of the internal data structures can be customized by supplying your own std::allocator (I'm sure you'll be able to find one fitting your needs, there are plenty of those available). The allocation of your own data structures needs to be handled separately, most commonly by implementing type specific new and delete operators. Scott Meyers has a nice article about this in one of his books. Another solution would be to utilize Boost.Intrusive, a set of containers where all the internal data items needed for the container are stored in your own data structures (that's why they are called intrusive). This relieves you from having two different allocation schemes in place, as you need to worry about your own data allocation only.
2,407,711
2,408,105
Avoiding improper std::string initialization with NULL const char* using g++
A there any g++ options which can detect improper initialization of std::string with NULL const char*? I was in the process of turning some int fields into std::string ones, i.e: struct Foo { int id; Foo() : id(0) {} }; ...turned into: struct Foo { std::string id; Foo() : id(0) {} //oooops! }; I completely overlooked bad 'id' initialization with 0 and g++ gave me no warnings at all. This error was detected in the run time(std::string constructor threw an exception) but I'd really like to detect such stuff in the compile time. Is there any way?
I think it is actually undefined behavior and not checked by the compiler. You are lucky that this implementation throws an exception. However, you can avoid such problems by specifying that you want default or zero-initialization in a type-agnostic way: struct Foo { X id; Foo() : id() {} //note empty parenthesis };
2,407,724
2,407,809
Is delete p where p is a pointer to array always a memory leak?
following a discussion in a software meeting I've set out to find out if deleting a dynamically allocated, primitives array with plain delete will cause a memory leak. I have written this tiny program and compiled it with visual studio 2008 running on windows XP: #include "stdafx.h" #include "Windows.h" const unsigned long BLOCK_SIZE = 1024*100000; int _tmain() { for (unsigned int i =0; i < 1024*1000; i++) { int* p = new int[1024*100000]; for (int j =0;j<BLOCK_SIZE;j++) p[j]= j % 2; Sleep(1000); delete p; } } I than monitored the memory consumption of my application using task manager, surprisingly the memory was allocated and freed correctly, allocated memory did not steadily increase as was expected I've modified my test program to allocate a non primitive type array : #include "stdafx.h" #include "Windows.h" struct aStruct { aStruct() : i(1), j(0) {} int i; char j; } NonePrimitive; const unsigned long BLOCK_SIZE = 1024*100000; int _tmain() { for (unsigned int i =0; i < 1024*100000; i++) { aStruct* p = new aStruct[1024*100000]; Sleep(1000); delete p; } } after running for for 10 minutes there was no meaningful increase in memory I compiled the project with warning level 4 and got no warnings. is it possible that the visual studio run time keep track of the allocated objects types so there is no different between delete and delete[] in that environment ?
delete p, where p is an array is called undefined behaviour. Specifically, when you allocate an array of raw data types (ints), the compiler doesnt have a lot of work to do, so it turns it into a simple malloc(), so delete p will probably work. delete p is going to fail, typically, when: p was a complex data type - delete p; won't know to call individual destructors. a "user" overloads operator new[] and delete[] to use a different heap to the regular heap. the debug runtime overloads operator new[] and delete[] to add extra tracking information for the array. the compiler decides it needs to store extra RTTI information along with the object, which delete p; won't understand, but delete []p; will.
2,407,939
2,416,716
IShockwaveFlashEvents: how to handle getURL("javascript:?
I wrote a simple WinAPI application in C++ which embeds the Abode Flash ActiveX control. It works fine. Next task that i have to do it is handle getURL("javascript:somefoo(someparam)", "")in C++ I don't understand the right way to do this. I create connection point to listen to _IShockwaveFlashEvents and my STDMETHODIMP Invoke(...) was called 3 times(!) but I still don't understand how to get the params of getURL... And after calling getURL(). IE starts. How do I avoid that?
I solved this question. you cannot handle getURL flash must use fscommand to pass data to host application
2,407,972
2,408,009
Cannot convert const char * to char *
Visual Studio c++ 2005 I am getting an error on the last line of this code. int Utils::GetLengthDiff ( const char * input, int & num_subst ) { int num_wide = 0, diff = 0 ; const char * start_ptr = input ; num_subst = 0 ; while ( ( start_ptr = strstr ( start_ptr, enc_start ) ) != NULL ) { char * end_ptr = strstr ( start_ptr, enc_end ); // Error So I changed the line to this and it worked ok const char * end_ptr = strstr ( start_ptr, enc_end ); So why would I need to declare end_ptr as a const as well? Many thanks,
C++ has two overloaded versions of this function. http://www.cplusplus.com/reference/clibrary/cstring/strstr/ const char * strstr ( const char * str1, const char * str2 ); char * strstr ( char * str1, const char * str2 ); Since your start_ptr is const char * the C++ compiler resolves to call the version that takes a const char * as the first parameter, that version also returns a const char *, so you have to change your return value to match.
2,407,976
2,409,782
Doxygen, too heavy to maintain?
I am currently starting using doxygen to document my source code. I have notice that the syntax is very heavy, every time I modify the source code, I also need to change the comment and I really have the impression to pass too much time modifying the comment for every change I make in the source code. Do you have some tips to document my source code efficiently ? Does some editor (or plugin for existing editor) for doxygen to do the following exist? automatically track unsynchronized code/comment and warn the programmer about it. automatically add doxygen comment format (template with parameter name in it for example) in the source code (template) for every new item PS: I am working on a C/C++ project.
Is it the Doxygen syntax you find difficult? Or is it the fact that you have to comment all of the functions now. If it's the former, there may be a different tool that fits your coding style better. Keep in mind that Doxygen supports multiple commenting styles, so experiment until you find one you like. If it's the latter, then tough it out. As a good programming practice, every public-facing function should have a comment header that explains: What the function does The parameters The return codes Any major warnings/limitations about the function. This is true regardless of the documentation tool you use. My big tip: Avoid the temptation to comment too much. Describe what you need, and no more. Doxygen gives you lots of tags, but you don't have to use them all. You don't always need a @brief and a detailed description. You don't need to put the function name in the comments. You don't need to comment the function prototype AND implementation. You don't need the file name at the top of every file. You don't need a version history in the comments. (You're using a version control tool, right?) You don't need a "last modified date" or similar. As for your question: Doxygen has some configuration options to trigger warnings when the comments don't match the code. You can integrate this into your build process, and scan the Doxygen output for any warnings. This is the best way I have found to catch deviations in the code vs comments.
2,408,038
2,408,059
What does "-Wall" in "g++ -Wall test.cpp -o test" do?
-o changes the output filename (I found that using --help) But I can't find out what -Wall does?
It's short for "warn all" -- it turns on (almost) all the warnings that g++ can tell you about. Typically a good idea, especially if you're a beginner, because understanding and fixing those warnings can help you fix lots of different kinds of problems in your code.
2,408,179
2,409,069
Memory allocation while insertion into a map
#include <stdio.h> #include <stdlib.h> #include <memory.h> #include <vector> #include <string> #include <iostream> #include <map> #include <utility> #include <algorithm> void * GetMemory(size_t n) { void *ptr = malloc(n); printf("getMem n %d ptr 0x%x\n", n, reinterpret_cast<unsigned int> (ptr)); return ptr; } void FreeMemory(void *p) { free(p); } void* operator new (size_t n) { void *p = GetMemory(n); return p; } void* operator new [] (size_t n) { void *p = GetMemory(n); return p; } void operator delete (void *p) { FreeMemory(p); } void operator delete [] (void *p) { FreeMemory(p); } typedef std::vector<int> vec; int main(int argc, char *argv[]) { std::map<int, vec> z; vec x; z.insert(std::pair<int,vec>(1,x)); } Compile with g++ -Wall -ansi test.cpp -o test Run test. Why are there three calls to GetMemory with n = 0?
Stick some tracing in FreeMemory and change main to this: int main(int argc, char *argv[]) { printf("map\n"); std::map<int, vec> z; printf("vec\n"); vec x; printf("pair\n"); std::pair<int,vec> y(1,x); printf("insert\n"); z.insert(y); printf("inserted 1\n"); y.first = 2; printf("insert\n"); z.insert(y); printf("inserted 2\n"); } Output: $ make mapinsert CXXFLAGS=-O3 -B && ./mapinsert g++ -O3 mapinsert.cpp -o mapinsert map vec pair getMem n 0 ptr 0x6b0258 insert getMem n 0 ptr 0x6b0268 getMem n 32 ptr 0x6b0278 getMem n 0 ptr 0x6b02a0 FreeMemory ptr 0x6b0268 inserted 1 insert getMem n 0 ptr 0x6b0268 getMem n 32 ptr 0x6b02b0 getMem n 0 ptr 0x6b02d8 FreeMemory ptr 0x6b0268 inserted 2 FreeMemory ptr 0x6b0258 FreeMemory ptr 0x6b02d8 FreeMemory ptr 0x6b02b0 FreeMemory ptr 0x6b02a0 FreeMemory ptr 0x6b0278 So of your 3 0-sized allocations: One is to copy the empty vector into the pair. One is to store a copy of the empty vector in the map. These two are clearly necessary. What I'm not sure about is this: One is to copy the vector somewhere in the call to insert, and this is also freed in the call to insert. It's as if insert (or something it calls internally) is taking its parameter by value instead of by reference, or insert is explicitly taking a copy into an automatic variable some time before it allocates the new map node. Firing up a debugger is effort for me at the moment, I'll leave it to someone else. Edit: mystery solved. insert takes a std::pair<const int, vec>, not a std::pair<int, vec>. The extra copy of an empty vector is because the pair you construct has to be converted to a(nother) temporary, then a reference to that temporary is passed to insert. std::pair has a constructor template that lets you get away with almost anything. 20.2.2/4: template<class U, class V> pair(const pair<U,V> &p); Effects: initializes members from the corresponding members of the argument, performing implicit conversions as needed. I also observe that in my implementation, vec x; doesn't call getMem, but vec x(0); does. So actually: z[1] = vec(); Is less code and denies you the opportunity to make the extra copy (although it calls operator= instead). It does still make 2 0-sized allocations, at least for me. The C++ standard defines operator[] to return the result of a specified expression involving a call to insert. I'm not certain whether this means the effects of operator[] are "as if" make_pair and insert were called (that is, the standard is as good as specifying what the source must be for operator[]), or just that the value returned is the same value as the specified expression would yield. If the latter then perhaps an implementation could do it with a single 0-sized allocation. But certainly map has no guaranteed way to create an entry without first creating a pair that contains the mapped type, so 2 allocations should be expected. Or more properly, 2 copies of the desired mapped value: the fact that copying a 0-sized vector makes a 0-sized allocation is implementation-dependent. So, if you had a case where the value was really expensive to copy, but really cheap to default-construct (like a container with lots of elements), then the following might be useful: std::map<int, vec> z; vec x(1000); z[1] = x; // i.e. (*(z.insert(std::pair<const int, vec>(1,vec())).first)).second = x; makes 2 allocations of size 4000 and 2 of size 0, whereas: std::map<int, vec> z; vec x(1000); z.insert(std::pair<const int, vec>(2, x)); makes 3 of size 4000 and none of size 0. Eventually the size is big enough that the extra allocation in the first code is cheaper than the extra copying in the second code. It's possible that move-constructors in C++0x will help with this, I'm not sure.
2,408,181
2,408,225
dual map structure implementation?
I'm looking for a standard dual-map structure - is there one implemented in std/boost/another standard C++ library? When I say "dual-map" I mean a map which can be indexed efficiently both by the key and the "value" (it actually has two key types instead of one key type and one value type). for example: dualmap<int,string> m; m[1] = "foo"; m["bar"] = 2 int a = m["bar"]; // a = 2 Thanks, Dan
There's boost bimap if you don't want all the horsepower of boost multi index.
2,408,414
2,408,434
Changing contents of ItemData
I store objects of a custom data type in QStandardListItems. I recover these objects by calling: i.data(Qt::UserRole + 1).value<LiteReach>(); This only creates a new object in the stack. Any changes I do to them would be temporary. Is there a way to get the base object stored in itemData so that it could be manipulated directly? If not what would be the preferred method to change itemData? I would like not to call setData each time an object is modified since it would consume a lot of resources.
You could use pointers that allow access to the concrete data objects instead of copying the whole data into a QVariant like above. The problem is that value() returns a copy of your data. So if you make any modifications, they will be gone as soon as the copy is removed from stack. If you don't want to use pointers, I guess you'll have to stick with setData().
2,408,523
2,410,137
Detect modification of variable at runtime in C/C++
I am developing a library in C++ where users/programmer will extend a class BaseClass that has a method initArray. This method should be implemented by the user/programmer and it should normally initialize all elements of the array m_arr. Here is a snipplet, modified to this example: class BaseClass { public: BaseClass(int n) { m_arr = new double[n]; size = n; }; virtual ~BaseClass(); int size; double* m_arr; virtual int initArray(); }; Sometimes, the user/programmer implements a initArray that does not initialize some elements of m_arr. What I would like is to create a function in my library that checks if initArray did initialize all elements of m_arr. This function should be called by a sanity-check rutine at runtime. My question: is it possible to detect changes on this array? I can only think of initializing the array with some invalid values (like NaN or Inf), call initArray and check that all values have changed. Thanks for your ideas, David Edit Here is an example of the client code that I am trying to detect: // .h: class MyExample : public BaseClass { public: MyExample(); virtual ~MyExample(); virtual int initArray(); }; // .cpp: MyExample::MyExample() : BaseClass(3) { } MyExample::~MyExample() { } int MyExample::initArray() { m_arr[0] = 10; //m_arr[1] = 11; // let's say someone forgot this line m_arr[2] = 12; return 0; } So, by forgetting the m_arr[1] this element is not initialized and could cause problems in future calculations. That's what I would like to check.
I don't see a straightforward way of doing this in C++. What you are intending to implement is filters in Ruby on Rails where before accessing any method, the filters are invoked. Alternatively you can wrap your array inside a structure and inside this structure overload the [] operator for both assignment and access. Now : 1) Inside the overloaded [] operator for assignment, maintain a counter and increment the counter for each initialization. 2) Inside the overloaded [] access operator, check the counter before you access the array contents if it is equal to total number of elements. If not, throw error. Hope this helps.
2,409,138
2,409,171
DllRegisterServer error 0xc0000005, (C++ COM Dll). how do I debug my DllRegisterServer function in Visual Studio 2008?
I have written a COM dll, and wish to register it using regsvr32 myComdll.dll I get an error : DllRegisterServer failed, Return code was: 0xc0000005 I want to debug my DllRegsiterServer function, but I do not know how to set up Visual Studio 2008 to run regsvr32 in debug mode... Thanks Roey
Project + Properties, Debugging, set Command = Regsvr32.exe $(TargetPath). Set a breakpoint on your DllRegisterServer function or use Debug + Exceptions, check Win32 Exceptions. Press F5 to get it going.
2,409,456
2,409,677
Can a QT window be completely styled, including the menu bar when running on Windows 7 or Vista?
I noticed that the sample apps from QT show their menu bar as opaque, and with a color that doesn't match any of the styling on the window. It seems as if the windows being created by QT when running on Vista or Windows 7 don't pick up the translucency that are no the mainstay of the new Windows look and feel. Is there a way to override this in QT, or even have a custom painted menu?
On Windows 7 there is a special flag that activates the "Glass" Look&Feel: Here is some more detailed information: http://labs.trolltech.com/blogs/2009/09/15/using-blur-behind-on-windows/ Screenshot http://labs.trolltech.com/blogs/wp-content/uploads/2009/09/blurbehind2.png From what I see, only the Qt::WA_TranslucentBackground flag is involved.
2,409,504
13,394,183
Using C++ filestreams (fstream), how can you determine the size of a file?
I'm sure I've just missed this in the manual, but how do you determine the size of a file (in bytes) using C++'s istream class from the fstream header?
You can open the file using the ios::ate flag (and ios::binary flag), so the tellg() function will directly give you directly the file size: ifstream file( "example.txt", ios::binary | ios::ate); return file.tellg();
2,409,539
2,437,741
Getting Parent Layout in Qt
quick question. Is there any way to (easily) retrieve the parent layout of a widget in Qt? PS: QObject::parent() won't work, for logical reasons. EDIT: I'm positive the widget has a parent layout, because I added it to a layout earlier in the code. Now, I have many other layouts in the window and while it is possible for me to keep track of them, I just want to know if there is an easy and clean way to get the parent layout. EDIT2: Sorry, "easy and clean" was probably not the best way of putting. I meant using the Qt API. EDIT3: I'm adding the widget to the layout like this: QHBoxLayout* layout = new QHBoxLayout; layout->addWidget(button);
After some exploration, I found a "partial" solution to the problem. If you are creating the layout and managing a widget with it, it is possible to retrieve this layout later in the code by using Qt's dynamic properties. Now, to use QWidget::setProperty(), the object you are going to store needs to be a registered meta type. A pointer to QHBoxLayout is not a registered meta type, but there are two workarounds. The simplest workaround is to register the object by adding this anywhere in your code: Q_DECLARE_METATYPE(QHBoxLayout*) The second workaround is to wrap the object: struct Layout { QHBoxLayout* layout; }; Q_DECLARE_METATYPE(Layout) Once the object is a registered meta type, you can save it this way: QHBoxLayout* layout = new QHBoxLayout; QWidget* widget = new QWidget; widget->setProperty("managingLayout", QVariant::fromValue(layout)); layout->addWidget(widget); Or this way if you used the second workaround: QHBoxLayout* layout = new QHBoxLayout; QWidget* widget = new QWidget; Layout l; l.layout = layout; widget->setProperty("managingLayout", QVariant::fromValue(l)); layout->addWidget(widget); Later when you need to retrieve the layout, you can retrieve it this way: QHBoxLayout* layout = widget->property("managingLayout").value<QHBoxLayout*>(); Or like this: Layout l = widget->property("managingLayout").value<Layout>(); QHBoxLayout* layout = l.layout; This approach is applicable only when you created the layout. If you did not create the layout and set it, then there is not a simple way of retrieving it later. Also you will have to keep track of the layout and update the managingLayout property when necessary.
2,409,775
2,444,346
Mapping Java Native Methods to C++ Member Functions
The examples for JNI i've seen map Java native methods to implementation by C++ global functions. Is there a way to set the native methods implementation to be the member functions of a C++ object instead?
JNI doesn't know anything about your C++ classes. It just allows you to implement the methods of your Java classes using native code. The C++ functions you write are the methods of a Java class so it doesn't make sense to simultaneously make them methods of a different C++ class. If you are worried about namespace pollution you can use RegisterNatives to manually set up the link to the native methods. Doing so would allow you to name the functions the way you want, put your native functions into a namespace, or declare them as static to keep their symbols from being exported. I suppose you could use this approach to link to a static method of a C++ class but I seriously doubt it would make your code any easier to understand, especially if on the Java side the method is non-static.
2,409,819
2,409,853
C++: constructor initializer for arrays
I'm having a brain cramp... how do I initialize an array of objects properly in C++? non-array example: struct Foo { Foo(int x) { /* ... */ } }; struct Bar { Foo foo; Bar() : foo(4) {} }; array example: struct Foo { Foo(int x) { /* ... */ } }; struct Baz { Foo foo[3]; // ??? I know the following syntax is wrong, but what's correct? Baz() : foo[0](4), foo[1](5), foo[2](6) {} }; edit: Wild & crazy workaround ideas are appreciated, but they won't help me in my case. I'm working on an embedded processor where std::vector and other STL constructs are not available, and the obvious workaround is to make a default constructor and have an explicit init() method that can be called after construction-time, so that I don't have to use initializers at all. (This is one of those cases where I've gotten spoiled by Java's final keyword + flexibility with constructors.)
Edit: see Barry's answer for something more recent, there was no way when I answered but nowadays you are rarely limited to C++98. There is no way. You need a default constructor for array members and it will be called, afterwards, you can do any initialization you want in the constructor.
2,409,840
2,409,868
Determining files in a directory
I come from a C# background and I am working on a C++ project. I need to open files in a directory, then process that data in the files. The problem is on my target environment (Greenhills Integrity), I cannot access a "directory". It seems C++ does not have a concept of a directory. Why not? This problem is simple in C#. I cannot link to any big library(BOOST or dirent) to get the files. I can open a file using fopen, but I won't always know the file names, so I have to "strcat" the directory to each filename in order to "fopen" the files. I need a way to just get the file names in a directory without using an external API. Is that possible?
No, it's not possible. C++ has no "built-in" directory functionality - you need to use a library of some sort.
2,409,956
2,410,084
Convert HTML to Plain Text using c++
I am doing mail parsing application which required to convert the HTML file to Plain Text. regarding this i have found some scripts which does conversion. I want to do same thing in C++. So please suggest me any Cross platform and open source C++ libraries for converting HTML to Plain Text. Thanks in advance Regards Subbi
Try using regular expression extracting html tags and save result as file text. But it not simple. Use this help class DEELX - Regular Expression Engine.
2,410,191
2,410,203
getting around const in an init method
So I can't use initializers in my class constructor because of using arrays, so I decided to use an init() method instead. Now I have a different problem. I have a class like this: class EPWM { private: volatile EPWM_REGS* const regs; public: void init(volatile EPWM_REGS* _regs); }; where I need to implement init() by initializing regs = _regs; but I can't because of the const. Is there a way to force the assignment in my init method? I would like to keep the const keyword so I don't accidentally reassign elsewhere. edit: as much as I would like to use a constructor + initializer, which would solve this problem (my code used to do this), I cannot because I have another class which has an array of EPWM objects, and I can't initialize those objects because C++ does not support initializers for array members. (again, see the other question I asked a little while ago on this subject.) Context for using EPWM is something like this: class PwmGroup { private: EPWM *epwm; void init(EPWM *_epwm) { epwm = _epwm; } }; /* ... */ // main code: EPWM epwm[3]; PwmGroup pwmGroup; { // EPwm1Regs, EPwm2Regs, EPwm3Regs are structs // defined by TI's include files for this processor epwm[0].init(&EPwm1Regs); epwm[1].init(&EPwm2Regs); epwm[2].init(&EPwm3Regs); pwmGroup.init(epwm); }
You could consider const_cast and pointers, but it's something best used very rarely. Something like... EPWM_REGS** regsPP = const_cast<EPWM_REGS**>(&regs); *regsPP = _regs;
2,410,300
2,410,728
How to use wxTheApp macro outside the module it is declared?
I'm using wxWidgets 2.8.9, built with the default settings under Windows XP, VC9. And I have absolutely standard EXE with IMPLEMENT_APP like this: #include <wx/wx.h> #include <wx/image.h> #include "MainFrame.h" class MyMainApp: public wxApp { public: bool OnInit(); }; IMPLEMENT_APP(MyMainApp) bool MyMainApp::OnInit() { wxInitAllImageHandlers(); wxFrame* frame_mainFrame = new MainFrame(NULL, wxID_ANY, wxEmptyString); SetTopWindow(frame_mainFrame); frame_mainFrame->Show(); return true; } The MainFrame is a wxFrame with a "HelloWorld" text. This works fine when everything is linked in the EXE. The problem is, I would like to reuse this MainFrame class in another application and therefore I would like to have it in a DLL, so I can use the DLL code from everywhere. Because my DLL has different export macro than wxWidgets, I can't export any derived from wxFrame class outside my Dll, so I make a factory class, which simply has one static method create(), returning new MainFrame(NULL, wxID_ANY, wxEmptyString); So far so good. I have now a DLL, containing the MainFrame class, and one more FrameFactory class. Only the FrameFactory class is exported from my DLL and I can create the MainFrame in the EXE, in the OnInit() method like this: wxFrame* frame_mainFrame = FrameFactory::create(); The problem is that the constructor of the base class wxFrame calls wxTopLevelWindowMSW::CreateFrame(...), where the macro wxTheApp is invoked. This wxTheApp macro is actually a call to wxApp::GetInstance(). I was surprised that my wxApp instance is NULL when MainFrame is not in the EXE. Could somebody familiar with wxWidgets help me what am I doing wrong? I made several more expreriments and always wxTheApp is NULL when the code using this instance variable is used in a different module, than the one where macro IMPLEMENT_APP is called.
I don't use wxWidgets myself (go Qt!) But did you by any chance statically link your DLL to wxWidgets, such that the EXE and the DLL each have their own copy of the lib...? http://wiki.wxwidgets.org/Creating_A_DLL_Of_An_Application That would explain why your DLL's global variables for tracking the instance would be null (while the EXEs were set up in app initialization). If this is the case I'd be concerned about your SetInstance() workaround...who knows what other singletons there are: When to use dynamic vs. static libraries
2,410,532
2,410,696
C++: How can I avoid "invalid covariant return type" in inherited classes without casting?
I have a quite complex class hierarchy in which the classes are cross-like depending on each other: There are two abstract classes A and C containing a method that returns an instance of C and A, respectively. In their inherited classes I want to use a co-variant type, which is in this case a problem since I don't know a way to forward-declare the inheritance relation ship. I obtain a "test.cpp:22: error: invalid covariant return type for ‘virtual D* B::outC()’"-error since the compiler does not know that D is a subclass of C. class C; class A { public: virtual C* outC() = 0; }; class C { public: virtual A* outA() = 0; }; class D; class B : public A { public: D* outC(); }; class D : public C { public: B* outA(); }; D* B::outC() { return new D(); } B* D::outA() { return new B(); } If I change the return type of B::outC() to C* the example compiles. Is there any way to keep B* and D* as return types in the inherited classes (it would be intuitive to me that there is a way)?
I know of no way of having directly coupled covariant members in C++. You'll have either to add a layer, or implement covariant return yourself. For the first option class C; class A { public: virtual C* outC() = 0; }; class C { public: virtual A* outA() = 0; }; class BI : public A { public: }; class D : public C { public: BI* outA(); }; class B: public BI { public: D* outC(); }; D* B::outC() { return new D(); } BI* D::outA() { return new B(); } and for the second class C; class A { public: C* outC() { return do_outC(); } virtual C* do_outC() = 0; }; class C { public: virtual A* outA() = 0; }; class D; class B : public A { public: D* outC(); virtual C* do_outC(); }; class D : public C { public: B* outA(); }; D* B::outC() { return static_cast<D*>(do_outC()); } C* B::do_outC() { return new D(); } B* D::outA() { return new B(); } Note that this second option is what is done implicitly by the compiler (with some static checks that the static_cast is valid).
2,410,609
2,410,847
c++ exception parameter
I have a question regarding the following code snippet I came across in one of our older libraries. try { throw "this is an error message"; } catch( char* error ) { cout << "an exception occured: " << error << endl; } My understanding of the behavior in this case is, that the error message is thrown by value, which means a copy of the text "this is an error message" is thrown. The catch clause specifies a pointer to char as expected type of exception. Can some enlighten me, why this works? Another question in this context concerns the memory allocated for the error message. Since the exception type is pointer to char* one could assume, that the memory for the error message has been allocated dynamically on the heap and has to be deleted by the user? Thanks in advance
In throw context arrays decay to pointers. And string literal is an array of characters. This means that: (1) What is "thrown by value" in this case is a const char * pointer to the existing string literal. No copy of string literal is made. No additional memory is allocated by this throw. There's no need to deallocate anything. (2) In order to catch this exception you need a catch (const char *) handler. Your char * handler will not catch it, unless your compiler has a bug in it (this is a known persistent bug in MSVC++ compilers, which is not even fixed by /Za option).
2,410,631
2,731,574
Movement towards continuous integration in progress, any suggestions?
We have a bunch of C/C++ modules and projects for QNX4, QNX6 and Linux. All of these are written in Eclipse/QNX Momentics and we use Project Sets (psf files) to combine different modules into projects as required. The projects are built using make. The psf files specify which modules are required for a certain project. I have looked at two CI/Nightly build systems (BuildBot, Apache Continuum), but neither works particularly well with psf files, or supports them directly. Does any one know of a CI system that would allow me to work with them, without having to use scripts to check stuff out, etc? Btw, we are using CVS for versioning.
I ended up using Hudson along with Ant and ant4eclipse plugin. Ant4Eclipse works with ProjectSet files, so it is perfect. Ant can also do Telnet and so I use it for QNX4
2,410,683
2,410,713
What's the connection between the heap used in dynamic memory allocation and the data structure?
Possible Duplicate: Why are two different concepts both called “heap”? I've googled around, but cannot find the answer for this question; what's the connection between the heap used in dynamic memory allocation and the data structure? Is memory organized on the heap in a way which is similar the the heap data structure? If so, this seems very strange, since fetching memory should be random access AFAIK (i.e, O(1)), but finding an item from a heap is not done in constant time. So, is this just an overloaded meaning of heap, so to speak, or is there some kind of connection?
Heap is a synonym for what the standard calls the free-store. In contrast to stacks, which is used for function calls, and function-local object storage, heaps grow in the opposite direction (top to bottom) on many implementations (as opposed to stacks -- which grow from bottom to top). Of course, none of these are required by the standard. The heap data structure, on the other hand is completely different -- it is a specialized tree structure with certain properties. It is possible some implementations use the heap data structure for free-store management, whence the name may have been derived. (See buddy memory allocation.)
2,411,017
2,411,508
Using custom and built-in properties in Boost::Graph
I am building a graph class based on the following suggestion: Modifying vertex properties in a Boost::Graph Unfortunately, I realized an unexpected behavior. When using my own vertex-properties (for simplicity please ignore the edge properties), the built-in properties seem not to be used. So for example, when I have: typedef adjacency_list< setS, // disallow parallel edges listS, // vertex container undirectedS, // undirected graph property<vertex_properties_t, VERTEXPROPERTIES>, property<edge_properties_t, EDGEPROPERTIES> > GraphContainer; I can retrieve my custom properties without any problem, but when I want to retrieve the vertex_index-property I always get the same value for each vertex, meaning a value of 0. The nodes are distinct, which is confirmed by num_vertices(MyGraph). Then I thought that this might be due to missing the built-in properties, so I tried: typedef adjacency_list< setS, // disallow parallel edges listS, // vertex container undirectedS, // undirected graph property<vertex_index_t, unsigned int , property< vertex_properties_t, VERTEXPROPERTIES> >, property<edge_properties_t, EDGEPROPERTIES> > GraphContainer; Again, when wanting to retrieve the index of whatever vertex, I get a value of 0. Is this behavior normal? Does one have to set the built-in properties also, when using custom properties?
Been a long time since I've used Boost.Graph, but Googling "vertex_index_t", in hit #5 Andrew Sutton says : Just declaring a vertex index as a property (either bundled or interior, as here) won't buy you any new functionality. It just provides a place where you can assign an index for each vertex or edge. The problem that this half-solves is that nearly every algorithm in the distro requires a vertex index map (or edge index map, more rarely), and providing this will allow the default arguments to automatically extract a property map for vertices/edges. It won't - or shouldn't??? automatically assign indices. Also, if you remove a vertex or edge, you may have to renumber vertices. So seems the idea is to standardize the concept across algorithms that want to read the numbers, but you still have to do the writing yourself.
2,411,043
2,411,114
Design question regarding threads
I have class A and classes B and C. class B runs one thread and class C runs n threads. class A should start the threads and than wait for a signal from the user (say Ctrl-c in Linux) - class A will stop all threads (of classes B and C), do some final work and the application will exit. The question is: how should class A sleep until signal received? what is the best implementation?
Sounds like a job for a condition variable. There's a tutorial on how to use pthreads condition variables here and another one on wikipedia here The basic approcah is that all the threads that you want to kill periodically call pthread_cond_timedwait to check if a signal has been sent from class A. In pseudocode each of your threads in classes B and C would look something like this while (!pthread_cond_timedwait(/*some args (including a timeout)*/ ) { doSomeSmallUnitOfWork; } then in class A's signal handler that catches the CTRL-C (or whatever signal) pthread_cont_signal(/*some more args*/);
2,411,098
2,411,132
Help with char input and printing in C++
i want to read characters from the console and print them one after another only if they have a certain value. Well i tried using something like this: char c; while (c != '\n') { c = getch(); if (printable(c)) cout << c; // where printable is a function which checks // if the character is of a certain value } But this doesn't work as it prints all the characters, so any ideas what should i use? Thanks a lot! Edit Well i want to make polynomial calculator in which the user inputs the terms until pressed Enter, but if for example the user inputs 'r' or 'R' it will reset the input or 'q' and 'Q' to quit the program and also even if the user inputs illegall characters like '@',',',';', etc (also i don't want 'r' or 'q' printed) it won't print them on screen. Also here's the printable function: bool printable(char c) { return ( ((int(c) > 42 && int(c) < 123) || isspace(c)) && int(c) != 44 && int(c) != 46 && int(c) != 47 && int(c) != 58 && int(c) != 59 && int(c) != 60 && int(c) != 61 && int(c) != 62 && int(c) != 63 && int(c) != 64 && int(c) != 65 && int(c) != 91 && int(c) != 92 && int(c) != 93 && int(c) != 95 && int(c) != 96 ); }
You may want to change your cout statement to cout << "You just typed: " << c; That way you can actually see if you've hit the if condition successfully. Also post printable(). Here is a sample of just grabbing a char, not sure why you are using getch() you should use cin.get, but anyhow for your example: bool isPrintable(char c) { bool isItPrintable=false; if ((int)c >= 65) isItPrintable=true; return isItPrintable; } int main() { char c; while (c != '\r') { c=getch(); if (isPrintable(c)) { cout << "You just entered: " << c << endl; } } return 0; } For anyone wondering, getch() is available in conio.h. In my case I am just checking the int representation of the character and if it is > 65 returning true else false. EDIT Vlad the reason why w and z both show up is their decimal representation of w is 119 and z is 123. Now your isPrintable function has an if condition which allows for this: (int(c) > 42 && int(c) < 123) This will evaluate to TRUE so if you do not want a w you need to restrict that range.
2,411,315
2,411,425
How to convert for loop to STL for_each statement
I would like to convert my for loop to STL std::for_each loop. bool CMyclass::SomeMember() { int ii; for(int i=0;i<iR20;i++) { ii=indexR[i]; ishell=static_cast<int>(R[ii]/xStep); theta=atan2(data->pPOS[ii*3+1], data->pPOS[ii*3]); al2[ishell] += massp*cos(fm*theta); } } Actually I was planning to use parallel STL from g++4.4 g++ -D_GLIBCXX_PARALLEL -fopenmp which is allow to run code in parallel without changes if the code is written in standard STL library.
You need to seperate out the loop body into a seperate function or functor; I've assumed all the undeclared variables are member variables. void CMyclass::LoopFunc(int ii) { ishell=static_cast<int>(R[ii]/xStep); theta=atan2(data->pPOS[ii*3+1], data->pPOS[ii*3]); al2[ishell] += massp*cos(fm*theta); } bool CMyclass::SomeMember() { std::for_each(&indexR[0],&indexR[iR20],std::tr1::bind(&CMyclass::LoopFunc,std::tr1::ref(*this)); }
2,411,556
2,411,761
Cleaning up threads referencing an object when deleting the object (in C++)
I have an object (Client * client) which starts multiple threads to handle various tasks (such as processing incoming data). The threads are started like this: // Start the thread that will process incoming messages and stuff them into the appropriate queues. mReceiveMessageThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)receiveRtpMessageFunction, this, 0, 0); These threads all have references back to the initial object, like so: // Thread initialization function for receiving RTP messages from a newly connected client. static int WINAPI receiveRtpMessageFunction(LPVOID lpClient) { LOG_METHOD("receiveRtpMessageFunction"); Client * client = (Client *)lpClient; while(client ->isConnected()) { if(client ->receiveMessage() == ERROR) { Log::log("receiveRtpMessageFunction Failed to receive message"); } } return SUCCESS; } Periodically, the Client object gets deleted (for various good and sufficient reasons). But when that happens, the processing threads that still have references to the (now deleted) object throw exceptions of one sort or another when trying to access member functions on that object. So I'm sure that there's a standard way to handle this situation, but I haven't been able to figure out a clean approach. I don't want to just terminate the thread, as that doesn't allow for cleaning up resources. I can't set a property on the object, as it's precisely properties on the object that become inaccessible. Thoughts on the best way to handle this?
You don't have much leeway because of the running threads. No combination of shared_ptr + weak_ptr may save you... you may call a method on the object when it's valid and then order its destruction (using only shared_ptr would). The only thing I can imagine is to first terminate the various processes and then destroy the object. This way you ensure that each process terminate gracefully, cleaning up its own mess if necessary (and it might need the object to do that). This means that you cannot delete the object out of hand, since you must first resynchronize with those who use it, and that you need some event handling for the synchronization part (since you basically want to tell the threads to stop, and not wait indefinitely for them). I leave the synchronization part to you, there are many alternatives (events, flags, etc...) and we don't have enough data. You can deal with the actual cleanup from either the destructor itself or by overloading the various delete operations, whichever suits you.
2,411,704
2,411,720
C++, vector of objects
In c++, is using a vector of objects a good idea? If not, what's wrong with this c++ code? #include <vector> using namespace std; class A {}; int main() { vector<A*> v ( new A); return 0; } from g++: 13: error: invalid conversion from A*' tounsigned int'
The constructor for std::vector takes an initial length, not an element. This means you'd normally do: vector<A*> v(1); // Initialize to length 1 v.push_back( new A() ); // Add your element... You're getting the compiler error you are because, on your system, size_type is defined as an unsigned int. It's trying to use that constructor, but failing, since you're passing it a pointer to an A.
2,412,238
2,412,266
When do c++ stream objects use mutexes?
In the answer to this question ovanes states: Please be aware that boost::lexical_cast is much slower as atoi. I also use it very often in a performance non-critical code. The problem with lexical_cast is that it uses stringstream for conversion. If you are working in a multi-threaded environement any stream class from the standard lib will use locks on a mutex for every character being inserted, even if the stream object is used from a single thread.Your number consisting of 17 chars will involve 17 mutex locks when put into stream. – ovanes Jun 22 at 11:59 Which begs the question, when do <iostream> objects lock a mutex? Is this true for objects from <sstream> as well? If so can this be prevented?
The current C++ standard (C++03) does not contain anything about multi-threading. Because of this, how a library uses mutexes would depend on the specific implementation.
2,412,240
2,412,511
Free numerical libraries, C++, Windows
I am totally new to math/numerical analysis programming and I was looking all over the internet to find appropriate libraries. What I stumbled upon are CLAPACK, Boost::uBLAS, ATLAS. I need to solve SLEs (system of linear equations) so I guess BLAS itself would not be sufficient without some implementation of LAPACK. None of them seem to have easy and intuitive way to work on Windows platform. Would there be any recommendations? Intel MKL seems tempting but I cannot buy it because it is an academic project. As far, as I understand the best way is to use Cygwin and compile ATLAS for my system and use LAPACK extension. Thanks in advance for any thoughts. EDIT I decided upon using Eigen and trying Intel MKL under linux one day. Also, this seems to be a good brief overview of possible options http://gears.aset.psu.edu/hpc/software/numlib/
Mkl libraries are available free of charge under noncommercial license, search Google and you will find it. http://software.intel.com/en-us/articles/non-commercial-software-development/ I do not know what SEL are, system linear equations? boost ublas has LU decompose which you can use to solve a few problems. Ublas is fairly straightforward to install on Windows.