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
207,881
208,425
Hide a tab previously added to Qt TabWidget
I've a dialog which contains a Qt TabWidget with a number of tabs added. I'd like to hide one of the tabs. _mytab->hide() doesn't work. I don't want to just delete the tab and all its widgets from the .ui file because other code relies on the widgets within the tab. However, it would be fine to generate the tab code but somehow not ::insertTab in the generated uic_mydialog.cpp. Setting the hidden property in the ui file does not work either. I'm using Qt 3.3
I would use QTabDialog::removePage(QWidget* pTabPage) which does not delete pTabPage, which is what you want. _myTabDlg->removePage(_mytab); I'm using it and it works fine !
207,965
255,524
General way to reset a member variable to its original value using the stack?
I came across a class instance function that needed to temporarily change a class instance variable, and then restore it when the function completed. The function had return statements all over the place, and before each return there was a restoring statement. That seemed messy to me, not to mention scary when a exception is thrown. As an improvement I came up with this generalization using a inner class definition. Here is a sample driver program (class restorer). class Unwind { private: bool b_active_; ///< the thing I want to be restored template<typename T> class restorer { T* ref_; T save_; public: restorer(T* perm) : ref_(perm), save_(*ref_) {}; ~restorer() { *ref_ = save_; } }; public: Unwind() : b_active_(false) {}; void a() { out("a in"); b(); out("a end"); } void b() { out("b in"); { restorer<bool> trust_in_the_stack(&b_active_); // "restorer" created on the stack b_active_ = true; // change b_active_ only while "within" b() c(); out("b inner end"); } out("b end"); } void c() { out("c in"); d(); out("c end"); } void d() { out("d in"); cout << "deepest" << endl; out("d end"); } void out(const std::string& msg) { std::cout << msg << ": " << b_active_ << std::endl; } }; int main() { Unwind u; u.a(); return 0; } The output using g++ 4.2.3 (-Wall) was: a in: 0 b in: 0 c in: 1 d in: 1 deepest d end: 1 c end: 1 b inner end: 1 b end: 0 a end: 0 Which is what I expect at "b end". I felt that defining the class restorer inside the class Unwind helps to discourage misuse. My question is, is there a general and safer way to do this? I am worried about lifetime issues. Edit: Please assume that there are no threads, but "downstream" methods on the stack that change behavior based on this b_active_ flag.
I revised the sample a bit more based on the comments, and placed as an Community Wiki answer instead of editing the question. /// c++ code sample #ifndef UTIL_RESTORER_HPP #define UTIL_RESTORER_HPP namespace Utility { /// A Restorer instance ("inst") uses the stack to restore a saved /// value to the named variable when the instance "inst" goes out of /// scope. /// /// Restorer is designed to be an auto variable, not allocated on any /// other memory resource like a heap or in-place. template<typename T> class restorer { T& ref_; T save_; public: restorer(T& perm) : ref_(perm), save_(perm) {} ~restorer() { ref_ = save_; } }; }//NAMESPACE #endif//UTIL_RESTORER_HPP
207,994
209,101
How do i specify a bold version of the theme's default font?
I'm having problems with cross theme compatibility in windows forms. If you don't set the font for a control on a windows form, it will use the system font with correct typeface and size. If you want to make the font bold, it hard codes in the rest of the system font values for the current theme you're programming with. For instance: System::Windows::Forms::Label^ label1 = gcnew System::Windows::Forms::Label(); this->label1->AutoSize = true; this->label1->Location = System::Drawing::Point(9, 12); this->label1->Name = L"lblExample"; this->label1->Size = System::Drawing::Size(44, 13); this->label1->TabIndex = 3; this->label1->Text = L"Example Text"; If I then change the properties of this via the properties editor so that bold = true, it adds in this line: this->label1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); Is there a way of using the default font, but making it bold? Further yet, is there a way of using the system font, but making the size 3 or 4 points larger?
You can put the modified font initialization directly after the InitializeComponent call in your constructor. Also, you can you one of the many, many constructors to change the size. InitializeComponent(); label1->Font = gcnew System::Drawing::Font( label1->Font->FontFamily, label1->Font->SizeInPoints + 4, FontStyle::Bold, GraphicsUnit::Point); This will keep the design view from getting confused... but you also won't be able to see it in design view.
208,268
208,286
Enumerating network shared directories in C++ / MFC
I need to get a list of directories shared by the current computer, and their shared names. How do I do this in C++ / MFC?
You can use NetShareEnum, supplying NULL as the server name. You need to include Lm.h and add Netapi32.lib to the list of libraries linked,
208,373
212,953
wxWidgets: How to initialize wxApp without using macros and without entering the main application loop?
We need to write unit tests for a wxWidgets application using Google Test Framework. The problem is that wxWidgets uses the macro IMPLEMENT_APP(MyApp) to initialize and enter the application main loop. This macro creates several functions including int main(). The google test framework also uses macro definitions for each test. One of the problems is that it is not possible to call the wxWidgets macro from within the test macro, because the first one creates functions.. So, we found that we could replace the macro with the following code: wxApp* pApp = new MyApp(); wxApp::SetInstance(pApp); wxEntry(argc, argv); That's a good replacement, but wxEntry() call enters the original application loop. If we don't call wxEntry() there are still some parts of the application not initialized. The question is how to initialize everything required for a wxApp to run, without actually running it, so we are able to unit test portions of it?
You want to use the function: bool wxEntryStart(int& argc, wxChar **argv) instead of wxEntry. It doesn't call your app's OnInit() or run the main loop. You can call wxTheApp->CallOnInit() to invoke OnInit() when needed in your tests. You'll need to use void wxEntryCleanup() when you're done.
208,433
208,446
How do I write a short literal in C++?
Very basic question: how do I write a short literal in C++? I know the following: 2 is an int 2U is an unsigned int 2L is a long 2LL is a long long 2.0f is a float 2.0 is a double '\2' is a char. But how would I write a short literal? I tried 2S but that gives a compiler warning.
((short)2) Yeah, it's not strictly a short literal, more of a casted-int, but the behaviour is the same and I think there isn't a direct way of doing it. That's what I've been doing because I couldn't find anything about it. I would guess that the compiler would be smart enough to compile this as if it's a short literal (i.e. it wouldn't actually allocate an int and then cast it every time). The following illustrates how much you should worry about this: a = 2L; b = 2.0; c = (short)2; d = '\2'; Compile -> disassemble -> movl $2, _a movl $2, _b movl $2, _c movl $2, _d
208,855
208,888
How to get pointer from another thread?
Let's have the following class definition: CThread::CThread () { this->hThread = NULL; this->hThreadId = 0; this->hMainThread = ::GetCurrentThread (); this->hMainThreadId = ::GetCurrentThreadId (); this->Timeout = 2000; //milliseconds } CThread::~CThread () { //waiting for the thread to terminate if (this->hThread) { if (::WaitForSingleObject (this->hThread, this->Timeout) == WAIT_TIMEOUT) ::TerminateThread (this->hThread, 1); ::CloseHandle (this->hThread); } } //********************************************************* //working method //********************************************************* unsigned long CThread::Process (void* parameter) { //a mechanism for terminating thread should be implemented //not allowing the method to be run from the main thread if (::GetCurrentThreadId () == this->hMainThreadId) return 0; else { m_pMyPointer = new MyClass(...); // my class successfully works here in another thread return 0; } } //********************************************************* //creates the thread //********************************************************* bool CThread::CreateThread () { if (!this->IsCreated ()) { param* this_param = new param; this_param->pThread = this; this->hThread = ::CreateThread (NULL, 0, (unsigned long (__stdcall *)(void *))this->runProcess, (void *)(this_param), 0, &this->hThreadId); return this->hThread ? true : false; } return false; } //********************************************************* //creates the thread //********************************************************* int CThread::runProcess (void* Param) { CThread* thread; thread = (CThread*)((param*)Param)->pThread; delete ((param*)Param); return thread->Process (0); } MyClass* CThread::getMyPointer() { return m_pMyPointer; } In the main program, we have the following: void main(void) { CThread thread; thread.CreateThread(); MyClass* myPointer = thread.getMyPointer(); myPointer->someMethod(); // CRASH, BOOM, BANG!!!! } At the moment the myPointer is used ( in the main thread ) it crashes. I don't know how to get the pointer, which points to memory, allocated in another thread. Is this actually possible?
The memory space for your application is accessible to all threads. By default any variable is visible to any thread regardless of context (the only exception would be variables declared __delcspec(thread) ) You are getting a crash due to a race condition. The thread you just created hasn't started running yet at the point where you call getMyPointer. You need to add some kind of synchronization between the newly created thread and the originating thread. In other words, the originating thread has to wait until the new thread signals it that it has created the object.
208,959
208,968
How to store variant data in C++
I'm in the process of creating a class that stores metadata about a particular data source. The metadata is structured in a tree, very similar to how XML is structured. The metadata values can be integer, decimal, or string values. I'm curious if there is a good way in C++ to store variant data for a situation like this. I'd like for the variant to use standard libraries, so I'm avoiding the COM, Ole, and SQL VARIANT types that are available. My current solution looks something like this: enum MetaValueType { MetaChar, MetaString, MetaShort, MetaInt, MetaFloat, MetaDouble }; union MetaUnion { char cValue; short sValue; int iValue; float fValue; double dValue; }; class MetaValue { ... private: MetaValueType ValueType; std::string StringValue; MetaUnion VariantValue; }; The MetaValue class has various Get functions for obtaining the currently stored variant value, but it ends up making every query for a value a big block of if/else if statements to figure out which value I'm looking for. I've also explored storing the value as only a string, and performing conversions to get different variant types out, but as far as I've seen this leads to a bunch of internal string parsing and error handling which isn't pretty, opens up a big old can of precision and data loss issues with floating point values, and still doesn't eliminate the query if/else if issue stated above. Has anybody implemented or seen something that's cleaner to use for a C++ variant data type using standard libraries?
As of C++17, there’s std::variant. If you can’t use that yet, you might want Boost.Variant. A similar, but distinct, type for modelling polymorphism is provided by std::any (and, pre-C++17, Boost.Any). Just as an additional pointer, you can look for “type erasure”.
209,110
209,552
MFC: Showing / Hiding Splitter Panes
In my application I have a number of panes from m_wndspliter classes. What I want to do is at run time show and hide one of these panes. Whilst with the following code I can show and hide the view associated with the pane, I can't temporarily remove the pane itself. CWnd * pCurView = m_wndSplitter2.GetPane(2, 0); if( !pCurView == NULL ) { if( fShow ) { pCurView->ShowWindow(SW_SHOW); RecalcLayout(); } else { pCurView->ShowWindow(SW_HIDE); RecalcLayout(); } } Any examples / ideas ?
Does this help? http://www.codeguru.com/cpp/w-d/splitter/article.php/c1543 I have used something very similar myself,
209,148
209,624
MFC: What on earth is a CSplitterWnd Caret?
What on earth is a caret in the context of a CSplitterWnd class? I can't find any documentation relating explicitly to CSplitterWnds... EDIT: Specifically, what do these functions actually do: CWnd * pCurView = m_wndSplitter2.GetPane(2, 0); pCurView->ShowCaret() pCurView->HideCaret() EDIT2: Please note, I know what a caret is, I am specifically asking about the functions within the context of the CSlitterWnd Class. I have seen the MSDN documentation and it offers no real explaination.
Any CWnd can have a caret, but only CWnd inheritors that CreateCaret first actually display one. @DannySmurf gives you one example - CEditView - of a CView that creates a caret that you can show and hide. Depending on the specific kind of CView you've got on your pane, ShowCaret is probably irrelevant. It has nothing to do with CSplitterWnd.
209,198
210,694
Borland x86 inlined assembler; get a label's address?
I am using Borland Turbo C++ with some inlined assembler code, so presumably Turbo Assembler (TASM) style assembly code. I wish to do the following: void foo::bar( void ) { __asm { mov eax, SomeLabel // ... } // ... SomeLabel: // ... } So the address of SomeLabel is placed into EAX. This doesn't work and the compiler complains of: Undefined symbol 'SomeLabel'. In Microsoft Assembler (MASM) the dollar symbol ($) serves as the current location counter, which would be useful for my purpose. But again this does not seem to work in Borlands Assember (expression syntax error). Update: To be a little more specific, I need the compiler to generate the address it moves into eax as a constant during compilation/linking and not at run time, so it will compile like "mov eax, 0x00401234". Can anybody suggest how to get this working? UPDATE: To respond to Pax's question (see comment), If the base address is changed at run time by the Windows loader the DLL/EXE PE image will still be relocated by the Windows loader and the labels address will be patched at run time by the loader to use the re-based address so using a compile/link time value for the label address is not an issue. Many thanks in advance.
Last time I tried to make some assembly code Borland-compatible I came across the limitation that you can't forward-reference labels. Not sure if that's what you're running into here.
209,334
499,549
How to start Linux Programming
I am working on C++ and COM/ATL in Windows from last few years. Now I want to shift to Linux Programming. I know basic architecture of Linux. I did some of the projects which are using ncurses, sockets and audio libraries(Terminal Applications). On which tool I should be familiar to start with projects. In windows I have started with Win32 Programming then moved to COM and ATL. Win32 Programming gave me the insights of Windows. Can you give me the steps to start with Linux Programming?
Start reading the book Advanced Linux Programming which is also available as a free PDF. Do not fear the advanced keyword. From the details of your post (ncurses, sockets) you are already "advanced". You can also look later at the glib library (Standard component of GTK+/GNOME but also used in command line applications.) If you absolutely have to program in C++, read the whole documenation of QT and you are good to go.
209,603
209,658
Steps to make a LED blink from a C/C++ program?
What are the easiest steps to make a small circuit with an LED flash from a C/C++ program? I would prefer the least number of dependencies and packages needed. What port would I connect something into? Which compiler would I use? How do I send data to that port? Do I need to have a micro-processor? If not I don't want to use one for this simple project. EDIT: Interested in any OS specific solutions.
Here's a tutorial on doing it with a parallel port. Though I would recommend an Arduino which can be purchased very cheaply and would only involve the following code: /* Blinking LED * ------------ * * turns on and off a light emitting diode(LED) connected to a digital * pin, in intervals of 2 seconds. Ideally we use pin 13 on the Arduino * board because it has a resistor attached to it, needing only an LED * * Created 1 June 2005 * copyleft 2005 DojoDave <http://www.0j0.org> * http://arduino.berlios.de * * based on an orginal by H. Barragan for the Wiring i/o board */ int ledPin = 13; // LED connected to digital pin 13 void setup() { pinMode(ledPin, OUTPUT); // sets the digital pin as output } void loop() { digitalWrite(ledPin, HIGH); // sets the LED on delay(1000); // waits for a second digitalWrite(ledPin, LOW); // sets the LED off delay(1000); // waits for a second } http://www.arduino.cc/en/Tutorial/BlinkingLED
209,793
223,541
Any way to cast with class operator only?
Kind of a random question... What I'm looking for is a way to express a cast operation which uses a defined operator of the class instance I'm casting from, and generates a compile-time error if there is not a defined cast operator for the type. So, for example, what I'm looking for is something like: template< typename RESULT_TYPE, typename INPUT_TYPE > RESULT_TYPE operator_cast( const INPUT_TYPE& tValue ) { return tValue.operator RESULT_TYPE(); } // Should work... CString sString; LPCTSTR pcszString = operator_cast< LPCTSTR >( sString ); // Should fail... int iValue = 42; DWORD dwValue = operator_cast< DWORD >( iValue ); Interesting side-note: The above code crashes the VS2005 C++ compiler, and doesn't compile correctly in the VS2008 C++ compiler due to what I'm guessing is a compiler bug, but hopefully demonstrates the idea. Anybody know of any way to achieve this effect? Edit: More rationale, to explain why you might use this. Say you have a wrapper class which is supposed to encapsulate or abstract a type, and you're casting it to the encapsulated type. You could use static_cast<>, but that might work when you wanted it to fail (ie: the compiler chooses an operator which is allowed to convert to the type you asked for, when you wanted a failure because that operator is not present). Admittedly it's an uncommon case, but it's annoying that I can't express exactly what I want the compiler to do in an encapsulated function... hence the question here.
The code you posted works with the Cameau compiler (which is usually a good indication that it's valid C++). As you know a valid cast consists of no more than one user defined cast, so a possible solution I was thinking of was adding another user defined cast by defining a new type in the cast template and having a static assert that no cast is available from the new type to the result type (using boost is_convertible), however this doesn't distinguish between cast operators and cast constructors (ctor with one argument) and alows additional casts to take place (e.g. void* to bool). I'm not sure if making a distinction between cast operators and cast constructors is the the correct thing to do but that's what the question states. After a couple of days mulling this over it hit me, you can simply take the address of the cast operator. This is slightly easier said than done due to C++'s hairy pointer to member syntax (it took me way longer than expected to get it right). I don't know if this works on VS2008, I only checked it on Cameau. template< typename Res, typename T> Res operator_cast( const T& t ) { typedef Res (T::*cast_op_t)() const; cast_op_t cast_op = &T::operator Res; return (t.*cast_op)(); } Edit: I got a chance to test it on VS2005 and VS2008. My findings differ from the original poster's. On VS2008 the original version seems to work fine (as does mine). On VS2005 the original version only crashes the compiler when casting from a built in type (e.g. casting int to int) after providing a compilation error which doesn't seem so bad too me and my version seems to works in all cases.
210,026
210,043
Doxygen won't index my C++ source - why not?
I have some C++ source code with templates maybe like this - doxygen runs without errors but none of the documentation is added to the output, what is going on? /// /// A class /// class A { /// /// A typedef /// typedef B<C<D>> SomeTypedefOfTemplates; };
Yeah, so what is going on is the template instantiation is bogus. The ">>" like that is ambiguous and is meant to be a compile time error. You couldn't see it because maybe your compiler (VC++) let it slip by but I guess doxygen was stricter on that. Add a space like shown. /// /// A class /// class A { /// /// A typedef /// typedef B<C<D> > SomeTypedefOfTemplates; };
210,247
210,316
Visual studio intellisense for headers without .h
I am using a library that has headers without the .h This defeats visual studio's intellisense (declaration/definition lookup) Anyone know how to tell VS2008 that a file is a header?
Go to Tools::Options::Text Editor::File Extension tab in Visual Studio. Check the "Map extensionless headers" checkbox, and select the language you want from the combobox.
210,616
210,638
What is the member variables list after the colon in a constructor good for?
I'm reading this C++ open source code and I came to a constructor but I don't get it ( basically because I don't know C++ :P ) I understand C and Java very well. TransparentObject::TransparentObject( int w, int x, int y, int z ) : _someMethod( 0 ), _someOtherMethod( 0 ), _someOtherOtherMethod( 0 ), _someMethodX( 0 ) { int bla; int bla; } As far I can "deduce" The first line only declares the construtor name, the "::" sounds like "belongs to" to me. And the code between {} is the constructor body it self. I "think" what's after the paremeters and the first "{" are like methods default parameters or something, but I don't find a reasonable explanation on the web. Most of the C++ constructors that I found in the examples are almost identical to those in Java. I'm I right in my assumptions? "::" is like belongs to, and the list after params and body are like "default args" or something? UPDATE: Thanks for the answers. May those be called methods? ( I guess no ) and what is the difference of call them within the constructor body
The most common case is this: class foo{ private: int x; int y; public: foo(int _x, int _y) : x(_x), y(_y) {} } This will set x and y to the values that are given in _x and _y in the constructor parameters. This is often the best way to construct any objects that are declared as data members. It is also possible that you were looking at constructor chaining: class foo : public bar{ foo(int x, int y) : bar(x, y) {} }; In this instance, the class's constructor will call the constructor of its base class and pass the values x and y. To dissect the function even further: TransparentObject::TransparentObject( int w, int x, int y, int z ) : _someMethod( 0 ), _someOtherMethod( 0 ), _someOtherOtherMethod( 0 ), _someMethodX( 0 ) { int bla; int bla; } The ::-operator is called the scope resolution operator. It basically just indicates that TransparentObject is a member of TransparentObject. Secondly, you are correct in assuming that the body of the constructor occurs in the curly braces. UPDATE: Thanks for the answers. May those be called methods? ( I guess no ) and what is the difference of call them within the constructor body There is much more information on this subject than I could possibly ever give you here. The most common area where you have to use initializer lists is when you're initializing a reference or a const as these variables must be given a value immediately upon creation.
210,639
210,706
How can I limit CreateWindowEx to alphanumeric input only?
I know that ES_NUMBER exists to limit CreateWindowEx to numeric input only, is there a similar mechanism for limiting it to only alphanumeric (a-z,0-9) input? Or another way to do something similar. I know I can check after the fact, but I would like to limit it as the user types.
Check the EN_UPDATE message (via WM_COMMAND). It is sent just before the screen is updated; you can check the contents of the control and modify them if they contain any characters you don't want.
210,646
211,980
Can't detect when Windows Font Size has changed C++ MFC
I'm trying to determine how I can detect when the user changes the Windows Font Size from Normal to Extra Large Fonts, the font size is selected by executing the following steps on a Windows XP machine: Right-click on the desktop and select Properties. Click on the Appearance Tab. Select the Font Size: Normal/Large Fonts/Extra Large Fonts My understanding is that the font size change results in a DPI change, so here is what I've tried so far. My Goal: I want to detect when the Windows Font Size has changed from Normal to Large or Extra Large Fonts and take some actions based on that font size change. I assume that when the Windows Font Size changes, the DPI will also change (especially when the size is Extra Large Fonts What I've tried so far: I receive several messages including: WM_SETTINGCHANGE, WM_NCCALCSIZE, WM_NCPAINT, etc... but none of these messages are unique to the situation when the font size changes, in other words, when I receive the WM_SETTINGSCHANGE message I want to know what changed. In theory when I define the OnSettingChange and Windows calls it, the lpszSection should tell me what the changing section is, and that works fine, but then I check the given section by calling SystemParametersInfo and I pass in the action SPI_GETNONCLIENTMETRICS, and I step through the debugger and I make sure that I watch the data in the returned NONCLIENTMETRICS for any font changes, but none occur. Even if that didn't work, I should still be able to check the DPI when the Settings change. I really wouldn't care about the other details, every time I get the WM_SETTINGCHANGE message, I would just check the DPI and perform the actions I'm interested in performing, but I'm not able to get the system DPI either. I have tried to get the DPI by invoking the method GetSystemMetrics, also for each DC: Dekstop DC->GetDeviceCaps LOGPIXELSX/LOGPIXELSY Window DC->GetDeviceCaps LOGPIXELSX/LOGPIXELSY Current DC->GetDeviceCaps LOGPIXELSX/LOGPIXELSY Even if I change the DPI in the Graphic Properties Window these values don't return anything different, they always show 96. Could anybody help me figure this out please? What should I be looking for? Where should I be looking at? afx_msg void CMainFrame::OnSettingChange(UINT uFlags, LPCTSTR lpszSection) { int windowDPI = 0; int deviceDPI = 0; int systemDPI = 0; int desktopDPI = 0; int dpi_00_X = 0; int dpi_01_X = 0; int dpi_02_X = 0; int dpi_03_X = 0; CDC* windowDC = CWnd::GetWindowDC(); // try with window DC HDC desktop = ::GetDC(NULL); // try with desktop DC CDC* device = CWnd::GetDC(); // try with current DC HDC hDC = *device; // try with HDC if( windowDC ) { windowDPI = windowDC->GetDeviceCaps(LOGPIXELSY); // always 96 regardless if I change the Font // Size to Extra Large Fonts or keep it at Normal dpi_00_X = windowDC->GetDeviceCaps(LOGPIXELSX); // 96 } if( desktop ) { desktopDPI = ::GetDeviceCaps(desktop, LOGPIXELSY); // 96 dpi_01_X = ::GetDeviceCaps(desktop, LOGPIXELSX); // 96 } if( device ) { deviceDPI = device->GetDeviceCaps(LOGPIXELSY); // 96 dpi_02_X = device->GetDeviceCaps(LOGPIXELSX); // 96 } systemDPI = ::GetDeviceCaps(hDC, LOGPIXELSY); // 96 dpi_03_X = ::GetDeviceCaps(hDC, LOGPIXELSX); // 96 CWnd::ReleaseDC(device); CWnd::ReleaseDC(windowDC); ::ReleaseDC(NULL, desktop); ::ReleaseDC(NULL, hDC); CWnd::OnWinSettingChange(uFlags, lpszSection); } The DPI always returns 96, but the settings changes DO take effect when I change the font size to Extra Large Fonts or if I change the DPI to 120 (from the graphics properties).
[EDIT after re-read] I'm almost positive that changing to "Large fonts" does not cause a DPI change, rather it's a theme setting. You should be able to verify by applying the "Large fonts" change and then opening the advanced display properties where the DPI setting lives, it should have remained at 96dpi. DPI change is supposed to require a reboot. Maybe the setting hasn't propagated to a place where GetDeviceCaps can retrieve it? Maybe try changing a non-reboot-requiring setting (resolution perhaps) and then see if you can detect the change. If you can, your answer is probably that you can't detect DPI change until after reboot.
210,836
210,864
stdcall over-ride by visual studio?
In xp 32bit this line compiles with not problem however in vista 64bit this line: m_FuncAddr = ::GetProcAddress (somthing); gives the following error error C2440: '=' : cannot convert from 'FARPROC' to 'int (__cdecl *)(void)' GetProcAddress is defined as WINBASEAPI FARPROC WINAPI GetProcAddress (somthing) And m_FuncAddr as int (WINAPI *m_FuncAddr)(); From what I understand both are stdcall's. To avoid the error I had to put m_FuncAddr = (int (__cdecl *)(void))::GetProcAddress(somthing); My Question: If both m_FuncAddr and GetProcAddress have the stdcall calling convention why do I have to 'recall' it with cdecl ? Is it possible that the VS project setting 'default calling convention (which is set to cdecl) over-rides the assignemet statment above ? Thanks in advance! [Edit] To clerfiy the question: On one side of the equation (say side 1) i have int __stdcall * m_FuncAddr On other side (side 2) INT_PTR far __stdcall GetProcAddress So how is it that i have to cast side 2 with cdecl if both are stdcalls ? Or am I not getting something ?
The return type should be INT_PTR (a 64-bit value in 64-bit builds). You shouldn't cast around this error -- the compiler is trying to tell you that something is wrong. From WinDef.h: #ifdef _WIN64 typedef INT_PTR (FAR WINAPI *FARPROC)(); So the declaration of m_FuncAddr should be: INT_PTR (WINAPI *m_FuncAddr)();
210,939
211,309
Better Way To Use C++ Named Parameter Idiom?
I've been developing a GUI library for Windows (as a personal side project, no aspirations of usefulness). For my main window class, I've set up a hierarchy of option classes (using the Named Parameter Idiom), because some options are shared and others are specific to particular types of windows (like dialogs). The way the Named Parameter Idiom works, the functions of the parameter class have to return the object they're called on. The problem is that, in the hierarchy, each one has to be a different class -- the createWindowOpts class for standard windows, the createDialogOpts class for dialogs, and the like. I've dealt with that by making all the option classes templates. Here's an example: template <class T> class _sharedWindowOpts: public detail::_baseCreateWindowOpts { public: /////////////////////////////////////////////////////////////// // No required parameters in this case. _sharedWindowOpts() { }; typedef T optType; // Commonly used options optType& at(int x, int y) { mX=x; mY=y; return static_cast<optType&>(*this); }; // Where to put the upper-left corner of the window; if not specified, the system sets it to a default position optType& at(int x, int y, int width, int height) { mX=x; mY=y; mWidth=width; mHeight=height; return static_cast<optType&>(*this); }; // Sets the position and size of the window in a single call optType& background(HBRUSH b) { mBackground=b; return static_cast<optType&>(*this); }; // Sets the default background to this brush optType& background(INT_PTR b) { mBackground=HBRUSH(b+1); return static_cast<optType&>(*this); }; // Sets the default background to one of the COLOR_* colors; defaults to COLOR_WINDOW optType& cursor(HCURSOR c) { mCursor=c; return static_cast<optType&>(*this); }; // Sets the default mouse cursor for this window; defaults to the standard arrow optType& hidden() { mStyle&=~WS_VISIBLE; return static_cast<optType&>(*this); }; // Windows are visible by default optType& icon(HICON iconLarge, HICON iconSmall=0) { mIcon=iconLarge; mSmallIcon=iconSmall; return static_cast<optType&>(*this); }; // Specifies the icon, and optionally a small icon // ...Many others removed... }; template <class T> class _createWindowOpts: public _sharedWindowOpts<T> { public: /////////////////////////////////////////////////////////////// _createWindowOpts() { }; // These can't be used with child windows, or aren't needed optType& menu(HMENU m) { mMenuOrId=m; return static_cast<optType&>(*this); }; // Gives the window a menu optType& owner(HWND hwnd) { mParentOrOwner=hwnd; return static_cast<optType&>(*this); }; // Sets the optional parent/owner }; class createWindowOpts: public _createWindowOpts<createWindowOpts> { public: /////////////////////////////////////////////////////////////// createWindowOpts() { }; }; It works, but as you can see, it requires a noticeable amount of extra work: a type-cast on the return type for each function, extra template classes, etcetera. My question is, is there an easier way to implement the Named Parameter Idiom in this case, one that doesn't require all the extra stuff?
Maybe not what you want to hear, but I for one think it's ok to have lots of ugly type-casts and template parameters in library-code that's (more or less) hidden from the client as long as it is safe and makes the life of the client a lot easier. The beauty in library code is not in the code itself, but in the code it enables the clients to write. Take STL for example. I've also developed a small GUI-library as a personal project with basically the same aspirations as you and some of the code gets pretty ugly in it, but in the end it allows me to write beautiful client code (at least in my (possibly perverted) eyes) and that's what counts IMHO.
211,237
211,307
Static variables initialisation order
C++ guarantees that variables in a compilation unit (.cpp file) are initialised in order of declaration. For number of compilation units this rule works for each one separately (I mean static variables outside of classes). But, the order of initialization of variables, is undefined across different compilation units. Where can I see some explanations about this order for gcc and MSVC (I know that relying on that is a very bad idea - it is just to understand the problems that we may have with legacy code when moving to new GCC major and different OS)?
As you say the order is undefined across different compilation units. Within the same compilation unit the order is well defined: The same order as definition. This is because this is not resolved at the language level but at the linker level. So you really need to check out the linker documentation. Though I really doubt this will help in any useful way. For gcc: Check out ld I have found that even changing the order of objects files being linked can change the initialization order. So it is not just your linker that you need to worry about, but how the linker is invoked by your build system. Even try to solve the problem is practically a non starter. This is generally only a problem when initializing globals that reference each other during their own initialization (so only affects objects with constructors). There are techniques to get around the problem. Lazy initialization. Schwarz Counter Put all complex global variables inside the same compilation unit. Note 1: globals: Used loosely to refer to static storage duration variables that are potentially initialized before main(). Note 2: Potentially In the general case we expect static storage duration variables to be initialized before main, but the compiler is allowed to defer initialization in some situations (the rules are complex see standard for details).
211,376
211,419
function overloading fail: why did these operators clash?
I've got a big big code base that includes two main namespaces: the engine and the application. The engine defines a vector3 class as a typedef of another vector3 class, with equality operators that sit in the engine namespace, not in the vector3 class. I added a class to the application that also had equality operators in the application namespace. When I tried to compile, unrelated but near-by vector3 comparisons failed because it couldn't find an appropriate equality operator. I suspected I was causing a conflict so moved my equality operators into the class I added, and the compile succeeded. // engine.h namespace Engine { class Vector3Impl { ... }; typedef Vector3Impl Vector3; bool operator==(Vector3 const &lhs, Vector3 const &rhs) { ... } } // myfile.cpp #include "engine.h" namespace application { class MyClass { ... }; bool operator==(MyClass const &lhs, MyClass const &rhs) { ... } void myFunc(...) { if ( myClassA == myClassB ) { ... } // builds } void anotherFunc(...) { Engine::Vector3 a, b; ... if ( a == b ) { ... } // fails } } However after thinking about it I can't see why the compile failed. There are no implicit conversions from vector3s to my class or vice-versa, and argument-dependent look-up should be pulling in the equality operator from the engine namespace and matching it. I've tried reproducing this bug in a sample C++ project but that refuses to break. There must be something in the big big code base that is causing this problem, but I'm not sure where to start looking. Something like the opposite of a rogue "using Engine"? Anyone got any ideas?
C++ Standard, 3.4.4.2 declares: For each argument type T in the function call, there is a set of zero or more associated namespaces and a set of zero or more associated classes to be considered. The sets of namespaces and classes is determined entirely by the types of the function arguments (and the namespace of any template template argument). Typedef names and using-declarations used to specify the types do not contribute to this set. ADL doesn't work with typedef's.
211,384
211,449
Open Source C++ Data Visualization Library
We want to include data visualization in our desktop GUI (mostly timelines and graphs; clickable, draggable). We want to restrict to open-source, non-copyleft C++ libraries that allow commercial use and are portable across many platforms. Which library can I use? Our GUI is based on WxWidgets.
there is VTK. And if data visualization is your thing, have a look at opendx too.
211,934
211,949
Dynamically Loading External Modules in a C Program?
I'm sure this problem has been solved before and I'm curious how its done. I have code in which, when run, I want to scan the contents of a directory and load in functionality. Specifically, I am working with a scripting engine that I want to be able to add function calls to. I want the core engine to provide very limited functionality. The user should be able to add additional functions through 3rd party libraries, which I want the engine to scan for and load. How is this done?
It depends on the platform. On win32, you call LoadLibrary to load a DLL, then get functions from it with GetProcAddress. On Unixy platforms, the equivalents are dlopen and dlsym.
212,006
212,022
multiple definition error including c++ header file with inline code from multiple sources
I have a c++ header file containing a class. I want to use this class in several projects, bu I don't want to create a separate library for it, so I'm putting both methods declarations and definitions in the header file: // example.h #ifndef EXAMPLE_H_ #define EXAMPLE_H_ namespace test_ns{ class TestClass{ public: void testMethod(); }; void TestClass::testMethod(){ // some code here... } } // end namespace test_ns #endif If inside the same project I include this header from more than one cpp file, I get an error saying "multiple definition of test_ns::TestClass::testMethod()", while if I put the method definition inside the class body this does not happen: // example.h #ifndef EXAMPLE_H_ #define EXAMPLE_H_ namespace test_ns{ class TestClass{ public: void testMethod(){ // some code here... } }; } // end namespace test_ns #endif Since the class is defined inside a namespace, shouldn't the two forms be equivalent? Why is the method considered to be defined twice in the first case?
These are not equivalent. The second example given has an implicit 'inline' modifier on the method and so the compiler will reconcile multiple definitions itself (most likely with internal linkage of the method if it isn't inlineable). The first example isn't inline and so if this header is included in multiple translation units then you will have multiple definitions and linker errors. Also, headers should really always be guarded to prevent multiple definition errors in the same translation unit. That should convert your header to: #ifndef EXAMPLE_H #define EXAMPLE_H //define your class here #endif
212,237
212,693
Constants and compiler optimization in C++
I've read all the advice on const-correctness in C++ and that it is important (in part) because it helps the compiler to optimize your code. What I've never seen is a good explanation on how the compiler uses this information to optimize the code, not even the good books go on explaining what happens behind the curtains. For example, how does the compiler optimize a method that is declared const vs one that isn't but should be. What happens when you introduce mutable variables? Do they affect these optimizations of const methods?
Let's disregard methods and look only at const objects; the compiler has much more opportunity for optimization here. If an object is declared const, then (ISO/IEC 14882:2003 7.1.5.1(4)): Except that any class member declared mutable (7.1.1) can be modified, any attempt to modify a const object during its lifetime (3.8) results in undefined behavior. Lets disregard objects that may have mutable members - the compiler is free to assume that the object will not be modified, therefore it can produce significant optimizations. These optimizations can include things like: incorporating the object's value directly into the machines instruction opcodes complete elimination of code that can never be reached because the const object is used in a conditional expression that is known at compile time loop unrolling if the const object is controlling the number of iterations of a loop Note that this stuff applies only if the actual object is const - it does not apply to objects that are accessed through const pointers or references because those access paths can lead to objects that are not const (it's even well-defined to change objects though const pointers/references as long as the actual object is non-const and you cast away the constness of the access path to the object). In practice, I don't think there are compilers out there that perform any significant optimizations for all kinds of const objects. but for objects that are primitive types (ints, chars, etc.) I think that compilers can be quite aggressive in optimizing the use of those items.
212,442
212,462
How to create a for loop like command in C++?
I want to do something very simple in C++ but i can't find how. I want to create a function like a for loop where i will ideally enter a variable for the times the iteration should happen and some functions inside brackets my function will execute. I hope i was clear enough. Thanks... Example superFor (1) { //commands to be executed here add(1+2); }
What you want isn't possible in C++ because the (current version of the) language lacks some features that are required here: namely, creating function blocks “on the fly”. The best you can do is pass a function pointer or function object to your function. The STL offers many examples of this. Consider: void out(int x) { cout << x << ' '; } vector<int> xs; xs.push_back(42); xs.push_back(23); for_each(xs.begin(), xs.end(), out); This passes a pointer to function out to the function for_each.
212,492
254,915
How do you add external libraries for compilation in VC++?
I've worked with a couple of Visual C++ compilers (VC97, VC2005, VC2008) and I haven't really found a clearcut way of adding external libraries to my builds. I come from a Java background, and in Java libraries are everything! I understand from compiling open-source projects on my Linux box that all the source code for the library seems to need to be included, with the exception of those .so files. Also I've heard of the .lib static libraries and .dll dynamic libraries, but I'm still not entirely sure how to add them to a build and make them work. How does one go about this?
In I think you might be asking the mechanics of how to add a lib to a project/solution in the IDEs... In 2003, 2005 and 2008 it is something similar to: from the solution explorer - right click on the project select properties (typically last one) I usually select all configurations at the top... Linker Input Additional dependencies go in there I wish I could do a screen capture for this. In VC6 it is different bear with me as this is all from memory project settings or properties and then go to the linker tab and find where the libs can be added. Please excuse the haphazard nature of this post. I think that is what you want though.
212,645
214,078
How does _ftime / Windows internal time work?
I have found an interesting issue in windows which allows me to cause the Windows clock (but not the hardware clocks) to run fast - as much as 8 seconds every minute. I am doing some background research to work out how Windows calculates and updates it's internal time (not how it syncs with an NTP servers). Any information anyone has or any documents you can point me to would be greatly appreciated! Also, if anyone knows how _ftime works please let me know.
This MSDN article gives a very brief description of how the system time is handled: "When the system first starts, it sets the system time to a value based on the real-time clock of the computer and then regularly updates the time." Another interesting function is GetSystemTimeAdjustment, which has this to say: A value of TRUE [for lpTimeAdjustmentDisabled] indicates that periodic time adjustment is disabled. At each clock interrupt, the system merely adds the interval between clock interrupts to the time-of-day clock. The system is free, however, to adjust its time-of-day clock using other techniques. Such other techniques may cause the time-of-day clock to noticeably jump when adjustments are made. Finally, in regard to _ftime, it appears to be implemented using GetSystemTimeAsFileTime. So it would wrap directly onto the same built-in time facilities as would be used everywhere else.
212,669
212,747
Do the concepts in Accelerated C++ Practical Programming by Example still hold up today?
I was recommeded a book called: Accelerated C++ Practical Programming by Example by Andrew Koenig and Barbara E. Moo Addison-Wesley, 2000 ISBN 0-201-70353-X The basis of this book is that Object Oriented Programming is highly wasteful memory-wise, and that most source-code should not be written this way, rather that you should use all inline function calls and procedural programming. I mean I know most programming books have about the same shelf life as milk, but if your coding a client/server application (database, server and all) (not a device driver or a video game) is it really worth the hassle of having un-maintainable code just for a speed boost? Or is it worth it just to make the application run on a client's really old machine? Or to be able to run more servers on a single box?
I haven't read the book, but I have trouble believe that they wrote a book whose "basis ...is that Object Oriented Programming is highly wasteful memory-wise" (Full disclosure: Andy & Barbara are friends of mine). Andy would never say the OOP is wasteful of memory. He WOULD say that a particular algorithm or technique is wasteful, and might recommend a less OO approach in some cases, but, he would be the first to argue that as a general rule OO designs are no more or less wasteful that any other style of programming. The argument that OO designs are wasteful largely came from the fact that the EXEs of C++ "hello world" programs tend to be larger that the EXEs of C "hello world" programs. This is mostly because iostreams is larger the printf (but then, iostreams does more).
212,900
212,930
Advantages of Antlr (versus say, lex/yacc/bison)
I've used lex and yacc (more usually bison) in the past for various projects, usually translators (such as a subset of EDIF streamed into an EDA app). Additionally, I've had to support code based on lex/yacc grammars dating back decades. So I know my way around the tools, though I'm no expert. I've seen positive comments about Antlr in various fora in the past, and I'm curious as to what I may be missing. So if you've used both, please tell me what's better or more advanced in Antlr. My current constraints are that I work in a C++ shop, and any product we ship will not include Java, so the resulting parsers would have to follow that rule.
Update/warning: This answer may be out of date! One major difference is that ANTLR generates an LL(*) parser, whereas YACC and Bison both generate parsers that are LALR. This is an important distinction for a number of applications, the most obvious being operators: expr ::= expr '+' expr | expr '-' expr | '(' expr ')' | NUM ; ANTLR is entirely incapable of handling this grammar as-is. To use ANTLR (or any other LL parser generator), you would need to convert this grammar to something that is not left-recursive. However, Bison has no problem with grammars of this form. You would need to declare '+' and '-' as left-associative operators, but that is not strictly required for left recursion. A better example might be dispatch: expr ::= expr '.' ID '(' actuals ')' ; actuals ::= actuals ',' expr | expr ; Notice that both the expr and the actuals rules are left-recursive. This produces a much more efficient AST when it comes time for code generation because it avoids the need for multiple registers and unnecessary spilling (a left-leaning tree can be collapsed whereas a right-leaning tree cannot). In terms of personal taste, I think that LALR grammars are a lot easier to construct and debug. The downside is you have to deal with somewhat cryptic errors like shift-reduce and (the dreaded) reduce-reduce. These are errors that Bison catches when generating the parser, so it doesn't affect the end-user experience, but it can make the development process a bit more interesting. ANTLR is generally considered to be easier to use than YACC/Bison for precisely this reason.
212,990
212,997
Simple C++ UML w/ reverse engineering
I need a way to build C++ code from UML diagrams and vice versa. Should be simple too hopefully. I don't mind paying too much.
You could try Sparx Enterprise Architect but the code quality would be average, not excellent. I am not aware of any great automatic code generators for C++ Prices start from $135
213,121
213,135
Use 'class' or 'typename' for template parameters?
Possible Duplicate: C++ difference of keywords ‘typename’ and ‘class’ in templates When defining a function template or class template in C++, one can write this: template <class T> ... or one can write this: template <typename T> ... Is there a good reason to prefer one over the other? I accepted the most popular (and interesting) answer, but the real answer seems to be "No, there is no good reason to prefer one over the other." They are equivalent (except as noted below). Some people have reasons to always use typename. Some people have reasons to always use class. Some people have reasons to use both. Some people don't care which one they use. Note, however, that before C++17 in the case of template template parameters, use of class instead of typename was required. See user1428839's answer below. (But this particular case is not a matter of preference, it was a requirement of the language.)
Stan Lippman talked about this here. I thought it was interesting. Summary: Stroustrup originally used class to specify types in templates to avoid introducing a new keyword. Some in the committee worried that this overloading of the keyword led to confusion. Later, the committee introduced a new keyword typename to resolve syntactic ambiguity, and decided to let it also be used to specify template types to reduce confusion, but for backward compatibility, class kept its overloaded meaning.
213,256
213,507
How to determine whether a Windows application is offscreen?
I am trying to debug a strange issue with users that have LogMeIn installed. After a few days, some of my dialogs that my app opens can end up offscreen. If I could reliable detect that, I could programmatically move the dialogs back where they are visible again. Note: this has to work for multiple monitors and use the win32 API. However, if you know how to do it from .NET I can probably extrapolate from there... Update: For the curious, the bug mentioned above has to do with wxWidgets. If you run a wxWidgets application, then walk away and let your screen saver go, then log in remotely with LogMeIn, then try to open a dialog from your app, you will have trouble if you use wxDisplay::GetFromPoint(pos) or wxWindowBase::Center() to position the dialog.
Simply use MonitorFromWindow with the MONITOR_DEFAULTTONULL flag. If the return value is null, your window is not visible. You can subsequently pass MONITOR_DEFAULTTONEAREST to be able to reposition your window on the nearest monitor.
213,761
213,811
What are some uses of template template parameters?
I've seen some examples of C++ using template template parameters (that is templates which take templates as parameters) to do policy-based class design. What other uses does this technique have?
I think you need to use template template syntax to pass a parameter whose type is a template dependent on another template like this: template <template<class> class H, class S> void f(const H<S> &value) { } Here, H is a template, but I wanted this function to deal with all specializations of H. NOTE: I've been programming c++ for many years and have only needed this once. I find that it is a rarely needed feature (of course handy when you need it!). I've been trying to think of good examples, and to be honest, most of the time this isn't necessary, but let's contrive an example. Let's pretend that std::vector doesn't have a typedef value_type. So how would you write a function which can create variables of the right type for the vectors elements? This would work. template <template<class, class> class V, class T, class A> void f(V<T, A> &v) { // This can be "typename V<T, A>::value_type", // but we are pretending we don't have it T temp = v.back(); v.pop_back(); // Do some work on temp std::cout << temp << std::endl; } NOTE: std::vector has two template parameters, type, and allocator, so we had to accept both of them. Fortunately, because of type deduction, we won't need to write out the exact type explicitly. which you can use like this: f<std::vector, int>(v); // v is of type std::vector<int> using any allocator or better yet, we can just use: f(v); // everything is deduced, f can deal with a vector of any type! UPDATE: Even this contrived example, while illustrative, is no longer an amazing example due to c++11 introducing auto. Now the same function can be written as: template <class Cont> void f(Cont &v) { auto temp = v.back(); v.pop_back(); // Do some work on temp std::cout << temp << std::endl; } which is how I'd prefer to write this type of code.
213,952
214,093
Do c++ static libraries without mfc that are linked to an MFC project throw bad_alloc or CMemoryException*?
I'm working on a large, aging code base for an MFC app. The code has been worked on by many developers over time, and as a result, we have three different ways throughout the code of dealing with the possibility of an allocation failure with new. The first way is to test for NULL on the result of new. We don't use nothrownew.obj so this is clearly an error that needs to be cleaned up. The second is to catch CMemoryException* (yes, C++ exceptions are enabled in the compiler). From what I understand, MFC overrides the standard operator new, and throws this thing instead. I am fairly certain that this second method is correct in the MFC application itself. MFC overrides new, with its strange CMemoryException throwing version. The last comes from our base of people who are good with C++, but aren't neccessarily MFC programmers. They are catching const std::bad_alloc&. What I really don't know is what to expect for static libraries linked into the application. This is were the vast majority of the code that uses bad_alloc lives. Assuming these libraries are not compiled with MFC or ATL, and are written in standard C++ only, can they expect to catch bad_alloc? Or will the presence of MFC in the application they link to infect them with the global new operator and render their attempts to fail cleanly on a bad allocation moot? If you have an answer, could you explain how this works, or point me to the right reference to sort this out?
It will depend on the compile options for the static libraries to be linked to the application. If the libraries are compiled with a configuration to use the static Standard C++ run-time then I would expect the operator new from the Standard C++ run-time to be called. If libraries are compiled with a configuration to use the Standard C++ run-time DLL then the resolution of these functions will be delayed until program load and should be resolved to the MFC replacements of operator new. I also included a link to this Herb Sutter article regarding handle allocation errors that you may find useful.
213,953
214,222
Boost phoenix or lambda library problem: removing elements from a std::vector
I recently ran into a problem that I thought boost::lambda or boost::phoenix could help be solve, but I was not able to get the syntax right and so I did it another way. What I wanted to do was remove all the elements in "strings" that were less than a certain length and not in another container. This is my first try: std::vector<std::string> strings = getstrings(); std::set<std::string> others = getothers(); strings.erase(std::remove_if(strings.begin(), strings.end(), (_1.length() < 24 && others.find(_1) == others.end())), strings.end()); How I ended up doing it was this: struct Discard { bool operator()(std::set<std::string> &cont, const std::string &s) { return cont.find(s) == cont.end() && s.length() < 24; } }; lines.erase(std::remove_if( lines.begin(), lines.end(), boost::bind<bool>(Discard(), old_samples, _1)), lines.end());
You need boost::labmda::bind to lambda-ify function calls, for example the length < 24 part becomes: bind(&string::length, _1) < 24 EDIT See "Head Geek"'s post for why set::find is tricky. He got it to resolve the correct set::find overload (so I copied that part), but he missed an essential boost::ref() -- which is why the comparison with end() always failed (the container was copied). int main() { vector<string> strings = getstrings(); set<string> others = getothers(); set<string>::const_iterator (set<string>::*findFn)(const std::string&) const = &set<string>::find; strings.erase( remove_if(strings.begin(), strings.end(), bind(&string::length, _1) < 24 && bind(findFn, boost::ref(others), _1) == others.end() ), strings.end()); copy(strings.begin(), strings.end(), ostream_iterator<string>(cout, ", ")); return 0; }
213,957
213,971
ClickOnce: getting MSVCRT C++ DLLs on user's machine
I've been trying desperately to get my application (15 C# dlls and 1 C++/CLI dll with C++ Runtime DLL dependencies) to deploy with ClickOnce. I got it to work by just copying the Release folder, but ClickOnce refuses to copy the files (msvcm80.dll, msvcp80.dll and msvcr80.dll) and deploy them in this folder. I did this nutty workaround (supply msvcm80.dll, msvcp80.dll and msvcr80.dll as Content/Copy If Newer and then at startup, create the Microsoft.VC80.CRT folder, copy those DLLs, and create Microsoft.VC80.CRT.manifest) that seems to work, but this all just feels wrong to me. Am I missing something?
I'm stupid: I just found this: On Publish tab of Properties page of my startup project: click Prerequisites... button > check Visual C++ Runtime Libraries, radio button setting: Download prerequisites from the component vendor's web site. It seems to work the way one might expect!
214,230
214,242
<iostream> vs. <iostream.h> vs. "iostream.h"
When including a header file in C++, what's the difference between... including the .h part versus not including .h part when wrapping it in <> signs? #include <iostream> vs. #include <iostream.h> wrapping the header name in double quotes versus wrapping it in < > signs? #include <iostream.h> vs. #include "iostream.h"
In short: iostream.h is deprecated—it is the original Stroustrup version. iostream is the version from the standards committee. Generally, compilers point them both to the same thing, but some older compilers won't have the older one. In some odd cases, they will both exist and be different (to support legacy code) and you then must be specific. "" versus <> simply means check the local directories for the header before going to the library (in most compilers).
214,411
214,422
Embedding Flash Player in a C++ or Java application?
I would like to embed Flash Player directly inside a C++ or Java application. I found an article that describes how to do this for C#: http://www.adobe.com/devnet/flash/articles/stock_history03.html Unfortunately, I have no experience with C#, COM or ActiveX. I need someone to translate this code to C++, allowing me to embed the Flash Player into a Win32 Window. Ultimately I'd like to use this information to embed Flash into a Java application. I am looking for three main functionalities: Ability to play a Flash movie Ability to receive events (such as mouse clicks) Ability to send events Edit: I prefer an open-source solution if possible.
I don't know how to embed flash in C++, but Christopher Deckers (of SWTSwing fame) has developed an interesting hack which allows it to be embedded in Java. You can find more information in the Javalobby announcement thread. Here is an updated link: https://github.com/Chrriis/DJ-Native-Swing
214,687
214,860
Saving an array of colour data as a PNG file on DS
I'm looking for a library to save an array of colour data to a PNG file. (That's all there is to it, right? I know very little about the internals of a PNG.) This is for use in Nintendo DS development, so something lightweight is preferable. I don't need any other fancy features like rotation, etc.
To encode any kind of PNG file, libpng is the way of the walk. However, on small devices like the DS you really want to store your image data in the format which the display hardware expects. It is technically possible to get libpng working on the platform, but it will add significant overhead, both in terms of loadtimes and footprint.
214,706
214,707
C or C++ BigInt library on Microsoft Windows
What arbitrary-precision integers (and or rationals) library are there for compilers running on Microsoft Windows, and which would you recommend? Please state license type / cost, supported compilers (i.e. GCC and or VC++) for the library.
GMP. LGPL. Standard download from official website is designed for GCC. VC++ port is available from here.
214,891
214,966
Checklist for writing copy constructor and assignment operator in C++
Please write a list of tasks that a copy constructor and assignment operator need to do in C++ to keep exception safety, avoid memory leaks etc.
First be sure you really need to support copy. Most of the time it is not the case, and thus disabling both is the way to go. Sometimes, you'll still need to provide duplication on a class from a polymorphic hierarchy, in that case: disable the assignment operator, write a (protected?) copy constructor, and provide a virtual clone() function. Otherwise, in the case you are writing a value class, you're back into the land of the Orthogonal Canonical Form of Coplien. If you have a member that can't be trivially copied, you'll need to provide a copy-constructor, a destructor, an assignment-operator and a default constructor. This rule can be refined, see for instance: The Law of The Big Two I'd also recommend to have a look at C++ FAQ regarding assignment operators, and at the copy-and-swap idiom and at GOTW.
214,927
214,933
Do you prefer explicit namespaces or 'using' in C++?
When using C++ namespaces, do you prefer to explicitly name them, like this: std::cout << "Hello, world!\n"; Or do you prefer using namespace: using namespace std; cout << "Hello, world!\n"; And if if you prefer the latter, do you declare your usings at file or function scope? Personally I prefer to explicitly name them - it's more typing but when using a mixture of namespaces (e.g. std and boost) I find it more readable.
I always use using namespace for std & boost. Everything else I tend to use an explicit namespace unless it is used so much that it would clutter up the code. In headers, I never use using namespace to avoid polluting the global namespace of the #including source.
215,110
215,117
Scatter Plots in C++
What is the best way to graph scatter plots in C++? Do you write data to a file and use another tool? Is there a library like matplotlib in Python?
I always write out data and then using gnuplot to create my graphs. It is by far the best way I have found of producing graphs in a variety of formats: eps, png, jpeg, xpm, you name it. gnuplot will do scatter plot very easily. Provided the x and y values are in 2 space-separated columnss, then plot "data.txt" using 1:2 Will give you a quick scatter plot. Then you can adjust it and what not using other gnuplot commands. If you are involved in sciences, then learning gnuplot will be very valuable to you. It kicks the crap out of doing excel plots for sure and it eases the task of making plots to include in papers.
215,430
215,432
What type for an integer of more than 4 bytes?
I have to use unsigned integers that could span to more than 4 bytes, what type should I use? PS Sorry for the "noobism" but that's it :D NB: I need integers because i have to do divisions and care only for the integer parts and this way int are useful
long long, 64 bit integer... here you can find some reference about the data types and ranges...
215,684
215,692
Requirement for key in std::multimap
I have a std::multimap where key is a custom class. Something like this: Class X { public: std::string s; int x; operator <(const X& other) const { return s < other.s; } }; std::multimap<X, int> mymap; Now, I'd like to use upper_bound and lower_bound to iterate over all elements with the same value of "s". Do I need to implement some other operator for X (for example: ==). Or it will work properly just like this? Also, what should I supply as argument for upper_bound and lower_bound? I assume I should create a dummy object with desired value of "s"?
Since class X is the key for the multimap, the parameter to upper_bound()/lower_bound() needs to be of that type. If class X has an implicit conversion from std::string (which is the type of X::s) then you can use that as the parameter to upper_bound()/lower_bound(). The default comparison for multimap is less<> which simply calls operator <() - so that's the only operator you a required to have in class X for the multimap to work.
215,752
215,874
Python embedded in CPP: how to get data back to CPP
While working on a C++ project, I was looking for a third party library for something that is not my core business. I found a really good library, doing exactly what's needed, but it is written in Python. I decided to experiment with embedding Python code in C++, using the Boost.Python library. The C++ code looks something like this: #include <string> #include <iostream> #include <boost/python.hpp> using namespace boost::python; int main(int, char **) { Py_Initialize(); try { object module((handle<>(borrowed(PyImport_AddModule("__main__"))))); object name_space = module.attr("__dict__"); object ignored = exec("from myModule import MyFunc\n" "MyFunc(\"some_arg\")\n", name_space); std::string res = extract<std::string>(name_space["result"]); } catch (error_already_set) { PyErr_Print(); } Py_Finalize(); return 0; } A (very) simplified version of the Python code looks like this: import thirdparty def MyFunc(some_arg): result = thirdparty.go() print result Now the problem is this: 'MyFunc' executes fine, i can see the print of 'result'. What i cannot do is read 'result' back from the C++ code. The extract command never finds 'result' in any namespace. I tried defining 'result' as a global, i even tried returning a tuple, but i cannot get it to work.
First of all, change your function to return the value. printing it will complicate things since you want to get the value back. Suppose your MyModule.py looks like this: import thirdparty def MyFunc(some_arg): result = thirdparty.go() return result Now, to do what you want, you have to go beyond basic embedding, as the documentation says. Here is the full code to run your function: #include <Python.h> int main(int argc, char *argv[]) { PyObject *pName, *pModule, *pFunc; PyObject *pArgs, *pArg, *pResult; int i; Py_Initialize(); pName = PyString_FromString("MyModule.py"); /* Error checking of pName left out as exercise */ pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule != NULL) { pFunc = PyObject_GetAttrString(pModule, "MyFunc"); /* pFunc is a new reference */ if (pFunc) { pArgs = PyTuple_New(0); pArg = PyString_FromString("some parameter") /* pArg reference stolen here: */ PyTuple_SetItem(pArgs, 0, pArg); pResult = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pResult != NULL) { printf("Result of call: %s\n", PyString_AsString(pResult)); Py_DECREF(pResult); } else { Py_DECREF(pFunc); Py_DECREF(pModule); PyErr_Print(); fprintf(stderr,"Call failed\n"); return 1; } } else { if (PyErr_Occurred()) PyErr_Print(); fprintf(stderr, "Cannot find function"); } Py_XDECREF(pFunc); Py_DECREF(pModule); } else { PyErr_Print(); fprintf(stderr, "Failed to load module"); return 1; } Py_Finalize(); return 0; }
215,961
216,813
Variable naming schemes for objects in C++?
I am implementing a BFS, and what it is going to do is go through an ordered tree to find the shortest solution to a puzzle. What i will be doing is creating a Snapshot object that holds the current position of each piece in a puzzle. I will add this Snapshot object into the queue and check if it is the solution. However, I am creating these snapshots on the fly. So is there some kind of way that will automatically generate the names of the Snapshot objects when they are put into the queue? or do i have to keep track of how many declarations i have made and just hard code it by saying... Snapshot snapshot2; Snapshot snapshot3; Snapshot snapshot4; etc..
There is a way - you use the Preprocessor's Token-Pasting Operator. This allows you to create a name based on a variable, so you'd specify: #define S(variable) snapshot#variable and you'd be able to create variables named snapshot1, snapshot2 etc: Snapshot S(1) Snapshot S(2) However, I'm not sure this is what you really want, I've maybe used this technique once in practise, and that was for a code generator.
216,068
216,072
Parsing integers from a line
I am parsing an input text file. If I grab the input one line at a time using getline(), is there a way that I can search through the string to get an integer? I was thinking something similar to getNextInt() in Java. I know there has to be 2 numbers in that input line; however, these values will be separated by one or more white space characters, so I can't just go to a specific position.
If the only thing in there is whitespace and integers, just try something like this: int i1, i2; stringstream ss(lineFromGetLine); ss >> i1 >> i2; or easier: int i1, i2; theFileStream >> i1 >> i2;
216,124
216,154
Question about shallow copy in C++
Say I have a struct "s" with an int pointer member variable "i". I allocate memory on the heap for i in the default constructor of s. Later in some other part of the code I pass an instance of s by value to some function. Am I doing a shallow copy here? Assume I didn't implement any copy constructors or assignment operators or anything for s... just the default constructor.
To follow up on what @[don.neufeld.myopenid.com] said, it is not only a shallow copy, but it is either (take your pick) a memory leak or a dangling pointer. // memory leak (note that the pointer is never deleted) class A { B *_b; public: A() : _b(new B) { } }; // dangling ptr (who deletes the instance?) class A { B *_b; public: A() ... (same as above) ~A() { delete _b; } }; To resolve this, there are several methods. Always implement a copy constructor and operator= in classes that use raw memory pointers. class A { B *_b; public: A() ... (same as above) ~A() ... A(const A &rhs) : _b(new B(rhs._b)) { } A &operator=(const A &rhs) { B *b=new B(rhs._b); delete _b; _b=b; return *this; }; Needless to say, this is a major pain and there are quite a few subtleties to get right. I'm not even totally sure I did it right here and I've done it a few times. Don't forget you have to copy all of the members - if you add some new ones later on, don't forget to add them in too! Make the copy constructor and operator= private in your class. This is the "lock the door" solution. It is simple and effective, but sometimes over-protective. class A : public boost::noncopyable { ... }; Never use raw pointers. This is simple and effective. There are lots of options here: Use string classes instead of raw char pointers Use std::auto_ptr, boost::shared_ptr, boost::scoped_ptr etc Example: // uses shared_ptr - note that you don't need a copy constructor or op= - // shared_ptr uses reference counting so the _b instance is shared and only // deleted when the last reference is gone - admire the simplicity! // it is almost exactly the same as the "memory leak" version, but there is no leak class A { boost::shared_ptr<B> _b; public: A() : _b(new B) { } };
216,259
216,266
Is there a max array length limit in C++?
Is there a max length for an array in C++? Is it a C++ limit or does it depend on my machine? Is it tweakable? Does it depend on the type the array is made of? Can I break that limit somehow or do I have to search for a better way of storing information? And what should be the simplest way? What I have to do is storing long long int on an array, I'm working in a Linux environment. My question is: what do I have to do if I need to store an array of N long long integers with N > 10 digits? I need this because I'm writing some cryptographic algorithm (as for example the p-Pollard) for school, and hit this wall of integers and length of arrays representation.
There are two limits, both not enforced by C++ but rather by the hardware. The first limit (should never be reached) is set by the restrictions of the size type used to describe an index in the array (and the size thereof). It is given by the maximum value the system's std::size_t can take. This data type is large enough to contain the size in bytes of any object The other limit is a physical memory limit. The larger your objects in the array are, the sooner this limit is reached because memory is full. For example, a vector<int> of a given size n typically takes multiple times as much memory as an array of type vector<char> (minus a small constant value), since int is usually bigger than char. Therefore, a vector<char> may contain more items than a vector<int> before memory is full. The same counts for raw C-style arrays like int[] and char[]. Additionally, this upper limit may be influenced by the type of allocator used to construct the vector because an allocator is free to manage memory any way it wants. A very odd but nontheless conceivable allocator could pool memory in such a way that identical instances of an object share resources. This way, you could insert a lot of identical objects into a container that would otherwise use up all the available memory. Apart from that, C++ doesn't enforce any limits.
216,450
216,464
GCC and ld can't find exported symbols...but they're there
I have a C++ library and a C++ application trying to use functions and classes exported from the library. The library builds fine and the application compiles but fails to link. The errors I get follow this form: app-source-file.cpp:(.text+0x2fdb): undefined reference to `lib-namespace::GetStatusStr(int)' Classes in the library seem to be resolved just fine by the linker, but free functions and exported data (like a cosine lookup table) invariably result in the above error. I am using Ubuntu 8.04 (Hardy), and it is up to date with the latest Ubuntu packages. The command to link the library is (with other libraries removed): g++ -fPIC -Wall -O3 -shared -Wl,-soname,lib-in-question.so -o ~/project/lib/release/lib-in-question.so The command to link the application is (with other libraries removed): g++ -fPIC -Wall -O3 -L~/project/lib/release -llib-in-question -o ~/project/release/app-in-question Finally, it appears (as best as I can tell) that the symbols in question are being exported properly: nm -D ~/project/lib/release/lib-in-question.so | grep GetStatusStr --> U _ZN3lib-namespace12GetStatusStrEi
the U before _ZN3lib-namespace12GetStatusStrEi in the nm output shows that the symbol is undefined in the library. Maybe it's defined in the wrong namespace: it looks like you're calling it in lib-namepace but you might be defining it in another.
216,748
216,760
Pros and cons of using nested C++ classes and enumerations?
What are the pros and cons of using nested public C++ classes and enumerations? For example, suppose you have a class called printer, and this class also stores information on output trays, you could have: class printer { public: std::string name_; enum TYPE { TYPE_LOCAL, TYPE_NETWORK, }; class output_tray { ... }; ... }; printer prn; printer::TYPE type; printer::output_tray tray; Alternatively: class printer { public: std::string name_; ... }; enum PRINTER_TYPE { PRINTER_TYPE_LOCAL, PRINTER_TYPE_NETWORK, }; class output_tray { ... }; printer prn; PRINTER_TYPE type; output_tray tray; I can see the benefits of nesting private enums/classes, but when it comes to public ones, the office is split - it seems to be more of a style choice. So, which do you prefer and why?
Nested classes There are several side effects to classes nested inside classes that I usually consider flaws (if not pure antipatterns). Let's imagine the following code : class A { public : class B { /* etc. */ } ; // etc. } ; Or even: class A { public : class B ; // etc. } ; class A::B { public : // etc. } ; So: Privilegied Access: A::B has privilegied access to all members of A (methods, variables, symbols, etc.), which weakens encapsulation A's scope is candidate for symbol lookup: code from inside B will see all symbols from A as possible candidates for a symbol lookup, which can confuse the code forward-declaration: There is no way to forward-declare A::B without giving a full declaration of A Extensibility: It is impossible to add another class A::C unless you are owner of A Code verbosity: putting classes into classes only makes headers larger. You can still separate this into multiple declarations, but there's no way to use namespace-like aliases, imports or usings. As a conclusion, unless exceptions (e.g. the nested class is an intimate part of the nesting class... And even then...), I see no point in nested classes in normal code, as the flaws outweights by magnitudes the perceived advantages. Furthermore, it smells as a clumsy attempt to simulate namespacing without using C++ namespaces. On the pro-side, you isolate this code, and if private, make it unusable but from the "outside" class... Nested enums Pros: Everything. Con: Nothing. The fact is enum items will pollute the global scope: // collision enum Value { empty = 7, undefined, defined } ; enum Glass { empty = 42, half, full } ; // empty is from Value or Glass? Ony by putting each enum in a different namespace/class will enable you to avoid this collision: namespace Value { enum type { empty = 7, undefined, defined } ; } namespace Glass { enum type { empty = 42, half, full } ; } // Value::type e = Value::empty ; // Glass::type f = Glass::empty ; Note that C++0x defined the class enum: enum class Value { empty, undefined, defined } ; enum class Glass { empty, half, full } ; // Value e = Value::empty ; // Glass f = Glass::empty ; exactly for this kind of problems.
217,073
217,171
Partial sort of std::list
I have a linked list that I want to sort part of, eg: std::sort(someIterator, otherIterator, predicate); std::sort requires random-access iterators so this approach doesn't work. There is a specialisation std::list::sort, but that can only sort the entire list. I don't think I have enough access to the list members to write something myself. Is there a way to do this without changing to, say, vector?
How about unhooking the part of the list that you want sorted, into a standalone list, then use the specialized list sort, then hook it back into the original list?
217,463
217,474
How do you configure the email settings in CrashRpt to send the crash dump?
After reading this discussion and this discussion about using CrashRpt to generate a crash dump and email it to the developers, I've been having a difficult time finding any instructions/tutorials for configuring the email settings used by the library to send the email. When you call the install() function to initialize CrashRpt, you specify the email address you want the crash dump sent to, but how does the CrashPrt library know how to send the email to that address? Wouldn't the library have to know the email client settings for each individual user? When a fatal crash occurs in my code, the CrashRpt dialog box pops up and when I enter my email address and click the send button, it takes me to a "Save File" dialog box where I can save the zipped package and the account specified in the Install() function never receives an email. Thanks in advance for any and all help! I'm clearly missing something.
What CrashRpt does for emailing: The email system simply uses MAPI to send your email. Which would try to use your default mail client if you have one, and if it supports MAPI. Take a look at MailMsg.cpp for details. Personal experience: In my company's usage of CrashRpt, we modified it a bit though to call a web service that we created which submits the crash report. So we gutted the emailing code completely from CrashRpt. And instead we have in our bug tracking system a section for crashes that were auto submitted when crashes happen. To find your problem: I would maybe try to debug the CrashRpt code to see why it's giving you a save dialog. It should instead just open your default mail client. Maybe you have an older version of the library, or maybe the dialog resources are a little messed. Debugging the code will tell you this though. Most likely MailReport is being called but is failing. Set a breakpoint in the original CrashRpt code's CrashHandler.cpp at just after the DoModal: mainDlg.m_pUDFiles = &m_files; if (IDOK == mainDlg.DoModal()) { //Put breakpoint here <--------- if (m_sTo.IsEmpty() || !MailReport(rpt, sTempFileName, mainDlg.m_sEmail, mainDlg.m_sDescription)) { SaveReport(rpt, sTempFileName); } } Check to see why MailReport is not getting called. It's either the dialog resource, or your m_sTo is not filled or you can step through MailMsg.cpp and see where MAPI is failing. Alternate solution: An easy fix, if you find above that MailReport is being called, but not succeeding, is to instead just do a ShellExecute and specify a mailto: You could even try to use the MAPI method, but if that fails to do a mailto:
217,532
217,649
What are the possible classes for the OpenThemeData function?
I'm trying to call the OpenThemeData (see msdn OpenThemeData) function but I couldn't determine what are the acceptable Class names to be passed in by the pszClassList parameter. HTHEME OpenThemeData( HWND hwnd, LPCWSTR pszClassList ); Could anybody tell me what are the acceptable class names that I can pass into that parameter? Thanks!
You can look in "AeroStyle.xml" as a previous poster noted, which gives an exact list for Vista/Aero. However, if you want to play safe (and you probably do) the class names should, in general, be Windows class names of Windows common controls. For example, push buttons and check boxes use the class name "Button", the edit control "Edit", etc. I generally pick the class name of the control that's closest to whatever custom element I'm working on is, and use the theme data for that. That way you'll get code that works with XP, Vista and (hopefully) Windows 7, regardless of what the user's selected theme actually is. However, unless you use raw Win32 a lot, you probably don't do much control creation directly using the class name. The class names are rather liberally sprinkled throughout MSDN. A good place to start is usually the "CommCtrl.h" file from the Platform SDK, which has a lot of them, and they're always described in the MSDN help on the individual common controls. You can also often learn them by looking at how dialogs are defined in .rc files by opening them in a text editor: these contain the class name for the controls.
217,892
217,904
What is a safe equivalent of non-void STL erase?
Suppose I have a hash_map and a code like // i is an iterator i = hash_map.erase(i) But GCC's STL doesn't return iterator in erase, but a void. Now is a code like hash_map.erase(i++) safe (i.e. does not invalidate the iterator or does any other unexpected or unpleasant things)? Please note this is a hash_map.
Yes, this is safe, because the value of i will have been set to the next value, before the current value is erased. According to the SGI documentation about hashed containers invalidation does not occur for non-erased elements, nor even for resizing (there is no word on whether insertions cause resizing, so to be careful I admit that as a possibility)---but in the latter case, the iteration order will be changed. But this doesn't apply here, unless you go out of your way to resize the container during traversal or something. :-)
217,901
217,922
c++ template function overloading
Below are lines from "the c++ programming language" template<class T > T sqrt(T ); template<class T > complex<T> sqrt(complex<T>); double sqrt(double); void f(complex<double> z ) { s q r t (2 ); // sqrt<int>(int) sqrt(2.0) ; // sqrt(double) sqrt(z) ; // sqrt<double>(complex<double>) } I dont understand why sqrt(z) ; calls sqrt<double>(complex<double>) can any body please explain. Author says, T sqrt<complex<T>> is more specialized than T sqrt <T> but there is a seperate declaration for template<class T > complex<T> sqrt(complex<T>); why not use that?
Well, the function used is the one you are talking about sqrt<double>(complex<double>) is an instance of the template template <class T> complex<T> sqrt(complex<T>). Your misunderstanding was in the signification of the template instance and not in the overloading process.
217,911
217,934
Why don't C++ compilers define operator== and operator!=?
I am a big fan of letting the compiler do as much work for you as possible. When writing a simple class the compiler can give you the following for 'free': A default (empty) constructor A copy constructor A destructor An assignment operator (operator=) But it cannot seem to give you any comparison operators - such as operator== or operator!=. For example: class foo { public: std::string str_; int n_; }; foo f1; // Works foo f2(f1); // Works foo f3; f3 = f2; // Works if (f3 == f2) // Fails { } if (f3 != f2) // Fails { } Is there a good reason for this? Why would performing a member-by-member comparison be a problem? Obviously if the class allocates memory then you'd want to be careful, but for a simple class surely the compiler could do this for you?
The compiler wouldn't know whether you wanted a pointer comparison or a deep (internal) comparison. It's safer to just not implement it and let the programmer do that themselves. Then they can make all the assumptions they like.
218,003
218,014
Searching CStrings in C++
I was wondering if there is a native C++ (or STL/Boost) function which will search a CString for a specified string? e.g. CString strIn = "Test number 1"; CString strQuery = "num"; bool fRet = SomeFn(strIn, StrQuery); if( fRet == true ) { // Ok strQuery was found in strIn ... I have found a small number of functions like CompareNoCase IndexOf etc... but so far they don't really do what I want them to do (or use CLR/.Net) Thanks!
CString::Find() is what you want, one of the overloads does sub-string searching. CString strIn = "test number 1"; int index = strIn.Find("num"); if (index != -1) // ok, found
218,226
218,250
Visual C++ 2008 'Release' build contains debug information
I've noticed that when generating a new C++ project using MS Visual Studio 2008, the Release build contains debugging symbols - specifically the following settings are enabled: The C++/General/Debug Information Format is set to Program Database. The Linker/Debugging/Generate Debug Info setting is set to Yes. I have never noticed this on earlier releases of Visual Studio. So, other than generating a larger EXE file, is there any downside to leaving these settings enabled?
We have turned on those settings in our commercial releases for years now with no apparent downside. The upsides are enormous,though. We have integrated a crash dump packager that packages the dump along with some other information and emails it (with the user's consent) to a company inbox. This has helped us find problems that would have taken us forever to reproduce and find otherwise. Although it's slightly off topic, here's a link to an excellent contribution someone made that gives you an easy way to include a crash reporter to a C++/Windows app: http://www.codeproject.com/KB/debug/crash_report.aspx Note: It would be wise, though, not to include the PDB file with your release. That said, you must keep the PDB file that matches your released version so that you can correctly debug the problem in the future. If a PDB file is used that wasn't built with the same code that built the exe, the stack you see when you try to debug the dmp will be wrong.
218,488
218,720
Finding "best matching key" for a given key in a sorted STL container
Problem I have timestamped data, which I need to search based on the timestamp in order to get the one existing timestamp which matches my input timestamp the closest. Preferably this should be solved with the STL. boost::* or stl::tr1::* (from VS9 with Featurepack) are also possible. Example of timestamped data: struct STimestampedData { time_t m_timestamp; // Sorting criterion CData m_data; // Payload } Approach with stl::vector, sort() and equal_range() Since a map or set only allows me to find exact matches, I don't get any further using one of these. So now I have a vector to which I append data as it is coming in. Before searching I use <algorithm>'s sort() and supply it with a custom comparison function. After that I use <algorithm>'s equal_range() to find the two neighbors of a specified value x. From these two values I check which one is closest to x and then I have my best match. While this is not too complex, I wonder if there are more elegant solutions to this. Maybe the STL already has an algorithm which does exactly that so I'm not re-inventing something here? Update: Linear vs. binary search I forgot to mention that I have quite a lot of data to handle so I don't want to have to search linearly. The reason I am sorting a vector with sort() is because it has random access iterators which is not the case with a map. Using a map would not allow equal_range() to do a search with twice logarithmic complexity. Am I correct?
I would use set::lower_bound to find the matching or greater value, then decrement the iterator to check the next lower value. You should use std::set rather than std::map since your key is embedded in the object - you'll need to provide a functor that compares the timestamp members. struct TimestampCompare { bool operator()(const STimestampedData & left, const STimestampedData & right) const { return left.m_timestamp < right.m_timestamp; } }; typedef std::set<STimestampedData,TimestampCompare> TimestampedDataSet; TimestampedDataSet::iterator FindClosest(TimestampedDataSet & data, STimestampedData & searchkey) { if (data.empty()) return data.end(); TimestampedDataSet::iterator upper = data.lower_bound(searchkey); if (upper == data.end()) return --upper; if (upper == data.begin() || upper->m_timestamp == searchkey.m_timestamp) return upper; TimestampedDataSet::iterator lower = upper; --lower; if ((searchkey.m_timestamp - lower->m_timestamp) < (upper->m_timestamp - searchkey.m_timestamp)) return lower; return upper; }
218,786
218,817
Concurrent programming c++?
I keep on hearing about concurrent programing every where. Can you guys throw some light on what it's and how c++ new standards facilitate doing the same?
Concurrency is about your code doing multiple things at the same time. This is typically done with explicit "threads", but there are other possibilities. For example, if you use OpenMP directives in your code then a compiler that supports OpenMP will automatically generate threads for you. Thread is short for "thread of execution". In a single-threaded C++ program, execution starts at main(), and then proceeds in a sequential fashion. In a multi-threaded program, the first thread starts at main, but additional threads may be started by the application which start at a user-specified function. These then run concurrently, or in parallel with the original thread. In C++0x threads are started using the std::thread class: void my_function() { // do stuff } std::thread my_thread(my_function); // run my_function in its own thread The new C++0x standard also supports: atomic values and operations with the std::atomic<> class template, mutexes for data protection (std::mutex, std::recursive_mutex, etc.) lock classes for ease of managing lock lifetime (std::lock_guard<>, std::unique_lock<>) std::lock and std::try_lock functions to manage acquiring multiple locks at the same time without risking deadlock condition variables to ease waiting for an event (std::condition_variable, std::condition_variable_any) futures, promises and packaged tasks to simplify passing data between threads, and waiting for a value to be ready. This addresses the classic "how do I return a value from a thread" question. thread-safe initialization of local static objects the thread_local keyword to declare thread-local data I gave a more detailed overview of the new C++0x thread library in my article on devx.com: Simpler Multithreading in C++0x I write about multithreading and concurrency in C++ on my blog. I'm also writing a book on the topic: C++ Concurrency in Action.
218,951
221,409
Simple Model Checker Tool
Is there a simple Model Checker tool. I am planning to implement a model checker tool which will analyze the code for some of the predefined properties.
One important tool is SPIN, with the Promela language. If you use LaTeX, there is also TLA+. These will not analyse your code, but will let you express a model for your assumtions and state transitons, and will then analyse for invalid states. In other words, they will detect problems in your model, not the implementation of your model. I have seen a demo of Goanna, but I don't know if it is available at all (commercial or otherwise); this has the advantage of actually analysing your source code. Just looking at your question, and the comments in your question again, it sounds like you really should read some of the literature first. Perhaps, The Spin Model Checker, or Specifying Systems (downloadable from Leslie Lamport's website). You need to reframe your problem so that you don't try to solve the halting problem.
219,139
220,220
Polymorphic functors in std::for_each
I'm trying to use stl algorithm for_each without proliferating templates throughout my code. std::for_each wants to instantiate MyFunctor class by value, but it can't since its abstract. I've created a functor adapter class which passes a pointer around and then derefernces it when appropriate. My Question: Does the STL or Boost already have such an adapter class? I don't want to have to reinvent the wheel! struct MyFunctor { virtual ~MyFunctor() {} virtual void operator()(int a) = 0; } namespace { template<typename FunctorType, typename OperandType> struct FunctorAdapter { FunctorAdapter(FunctorType* functor) : mFunctor(functor) {} void operator()(OperandType& subject) { (*mFunctor)(subject); } FunctorType* mFunctor; }; } void applyToAll(MyFunctor &f) { FunctorHelper<MyFunctor, int> tmp(&f); std::for_each(myvector.begin(), myvector.end(), tmp); } Cheers, Dave
tr1::ref may help you here --- it's meant to be a reference wrapper so that you can pass normal objects by reference to bind or function objects (even abstract ones) by reference to standard algorithms. // requires TR1 support from your compiler / standard library implementation #include <functional> void applyToAll(MyFunctor &f) { std::for_each( myvector.begin(), myvector.end(), std::tr1::ref(f) ); } However, NOTE that compilers without decltype support MAY reject passing a reference to an abstract type... so this code may not compile until you get C++0x support.
219,726
221,208
VCL alternative to IStorage
To preface I am using Borland C++ and the VCL. I need some sort of structured storage object which can be saved to disk as a single file and can contain multiple named blobs of binary data which I can programatically enumerate, access and manipulate. The IStorage interface seems to be close what I want but I would prefer a VCL style solution as converting TStream's (VCL) to IStream's among other things gets awkward and their must be a simpler solution using the VCL stuff allready available, like a TIniFile but for binary data. I don't want to use XML as the binary data blobs are very large and when correctly encoded for use in XML it's completely inneficient. Thanks in advance for all suggestions.
A zip file is de facto a standard container, and it seems you can get a TStream interface to them: http://www.tek-tips.com/faqs.cfm?fid=6734
219,770
219,791
Dealing with C++ "initialized but not referenced" warning for destruction of scope helpers?
In Visual Studio, I often use objects only for RAII purposes. For example: ScopeGuard close_guard = MakeGuard( &close_file, file ); The whole purpose of close_guard is to make sure that the file will be close on function exit, it is not used anywhere else. However, Visual Studio gives me a warning that a "local variable is initialized but not referenced". I want to turn this warning off for this specific case. How do you deal with this kind of situation? Visual Studio thinks that this object is useless, but this is wrong since it has a non-trivial destructor. I wouldn't want to use a #pragma warning directive for this since it would turn off this warning even for legitimate reasons.
Method 1: Use the #pragma warning directive. #pragma warning allows selective modification of the behavior of compiler warning messages. #pragma warning( push ) #pragma warning( disable : 4705 ) // replace 4705 with warning number ScopeGuard close_guard = MakeGuard( &close_file, file ); #pragma warning( pop ) This code saves the current warning state, then it disables the warning for a specific warning code and then restores the last saved warning state. Method 2: Use a workaround like the following. Visual Studio will be happy and so will you. This workaround is used in many Microsoft samples and also in other projects. ScopeGuard close_guard = MakeGuard( &close_file, file ); close_guard; Or you can create a #define to workaround the warning. #define UNUSED_VAR(VAR) VAR ... ScopeGuard close_guard = MakeGuard( &close_file, file ); UNUSED_VAR(close_guard); Some users stated that the code presented will not work because ScopeGuard is a typedef. This assumption is wrong. http://www.ddj.com/cpp/184403758 According to the C++ Standard, a reference initialized with a temporary value makes that temporary value live for the lifetime of the reference itself.
219,914
219,956
What use are const pointers (as opposed to pointers to const objects)?
I've often used pointers to const objects, like so... const int *p; That simply means that you can't change the integer that p is pointing at through p. But I've also seen reference to const pointers, declared like this... int* const p; As I understand it, that means that the pointer variable itself is constant -- you can change the integer it points at all day long, but you can't make it point at something else. What possible use would that have?
When you're designing C programs for embedded systems, or special purpose programs that need to refer to the same memory (multi-processor applications sharing memory) then you need constant pointers. For instance, I have a 32 bit MIPs processor that has a little LCD attached to it. I have to write my LCD data to a specific port in memory, which then gets sent to the LCD controller. I could #define that number, but then I also have to cast it as a pointer, and the C compiler doesn't have as many options when I do that. Further, I might need it to be volatile, which can also be cast, but it's easier and clearer to use the syntax provided - a const pointer to a volatile memory location. For PC programs, an example would be: If you design DOS VGA games (there are tutorials online which are fun to go through to learn basic low level graphics) then you need to write to the VGA memory, which might be referenced as an offset from a const pointer. -Adam
220,040
221,061
how to get as much as possible from dbx
I do TDD on a daily basis for my C++ development on Solaris10. It has greatly reduced the time I have to spend using my debugger but sometime this is the only option. DBX is pretty powerful but not that user friendly. Note that I'm talking about console DBX not the SunStudio GUI for DBX). What are the best productivity tips you can give for dbx C++ debugging? PS. Changing debugger is not an option.
I have bookmarked a few sites related to dbx. Here they are, in no particular order in case they might be useful to you: Why Can't dbx Find My Function? Online Help for the Dbx Debugger Sun Studio: debugging a multi-threaded application w/ dbx gdb vs. dbx: commands mapping and feature comparison Importing debug information into dbx command line dbx : See more source Sun Studio C++ - Your .dbxrc (NB: adapt the integer type used to cast pointers according to your pointer size) Sun Studio: Investigating memory leaks with dbx Sun Studio: Gathering memory allocations/leaks data, from a running process EDIT on 2012 july 19th: I've tried to fix several link since Chris Quenelle's blog has moved. Some articles can still be accessed thanks to the wayback machine.
220,323
220,908
Determine Process Info Programmatically in Darwin/OSX
I have a class with the following member functions: /// caller pid virtual pid_t Pid() const = 0; /// physical memory size in KB virtual uint64_t Size() const = 0; /// resident memory for this process virtual uint64_t Rss() const = 0; /// cpu used by this process virtual double PercentCpu() const = 0; /// memory used by this process virtual double PercentMemory() const = 0; /// number of threads in this process virtual int32_t Lwps() const = 0; This class' duty is to return process information about caller. Physical memory size can easily determined by a sysctl call, and pid is trivial, but the remaining calls have eluded me, aside from invoking a popen on ps or top and parsing the output - which isn't acceptable. Any help would be greatly appreciated. Requirements: Compiles on g++ 4.0 No obj-c OSX 10.5
Process info comes from pidinfo: cristi:~ diciu$ grep proc_pidinfo /usr/include/libproc.h int proc_pidinfo(int pid, int flavor, uint64_t arg, void *buffer, int buffersize); cpu load comes from host_statistics: cristi:~ diciu$ grep -r host_statistics /usr/include/ /usr/include/mach/host_info.h:/* host_statistics() */ /usr/include/mach/mach_host.defs:routine host_statistics( /usr/include/mach/mach_host.h:/* Routine host_statistics */ /usr/include/mach/mach_host.h:kern_return_t host_statistics For more details, check out sources for top and lsof, they are open source (you need to register as an Apple developer but that's free of charge): https://opensource.apple.com/source/top/top-111.20.1/libtop.c.auto.html Later edit: All these interfaces are version specific, so you need to take that into account when writing production code (libproc.h): /* * This header file contains private interfaces to obtain process information. * These interfaces are subject to change in future releases. */
220,423
220,434
How do you deal with NUL?
From time to time, I run into communications issue with other programmers, when we talk about NULL. Now NULL could be a NULL pointer the NUL character an empty data element in some sort of database. NUL seems to be the most confusing. It is the ASCII character 0x00. I tend to use '\0' in my code to represent it. Some developers in my group tend to prefer to simply use 0, and let the compiler implicitly cast it to a char. What do you prefer to use for NUL? and why?
I use '\0' for the nul-character and NULL for pointers because it is clearest in both cases. BTW, both 0 and '\0' are ints in C and either one will be converted to char when stored in a char variable.
220,718
220,722
Using set.insert( key ) as a conditional?
I am trying to use set.insert (key) as a conditional, where if the key is inserted correctly (meaning that the key does NOT already exist in the set ) then it should go on and perform some kind of code. For example, something like: if (set.insert( key )) { // some kind of code } Is this allowed? Because the compiler is throwing this error: conditional expression of type 'std::_Tree<_Traits>::iterator' is illegal
The version of insert that takes a single key value should return a std::pair<iterator,bool>, where the bool indicates whether an insertion was made. A value of true indicates that the value was inserted, and false indicates that the value was already present. So your conditional would look like this: if( set.insert( key ).second ) { // code }
220,752
221,038
What is the C++03 memory model for concurrency?
What is the memory model for concurrency in C++03? (And, does C++11 change the memory model to support concurrency better?)
The C++ memory model is the specification of when and why physical memory is read/written with respect to C++ code. Until the next C++ standard, the C++ memory model is the same as C. In the C++0x standard, a proper memory model for multithreading is expected to be included (see here), and it will be part possibly of the next revision of the C standard, C1X. The current one is rudimentary: it only specifies the behavior of memory operations observable by the current program. it doesn't say anything about concurrent memory accesses when multiple processes access the same memory (there is no notion of shared memory or processes). it doesn't say anything about concurrent memory accesses when multiple threads access the same memory (there is no notion of threads). it offers no way to specify an ordering for memory accesses (compiler optimizations include code motion and recent processors reorder accesses, both can break patterns such as double checked initialization). So, the current state is: C++ memory operations are only specified when you have 1 process, with its main thread and don't write code which depends on a specific ordering of variable read/writes and that's it. In essence, this means that aside from the traditional hello world program you're screwed. Of course, you'll be prompt to add that "it works today on my machine, you can't possibly be right". The correct sentence would be "it works today on my machine with this specific combination of hardware, operating system (thread library) and compiler who know enough of each other to implement something which is somewhat working but will probably break at some point". Ok ok, this is a bit harsh but hell, even Herb Sutter acknowledges that (just read the intro) and he is talking about all pre 2007 versions of one of the most ubiquitous C/C++ toolchain... The C++ standard committee attempts to come up with something which will address all those issues while still being less constraining (and thus better performing) than Java's memory model. Hans Boehm has collected here some pointers to papers on the issue, both academic, and from the C++ committee.
220,832
220,837
Easy way to shift specific characters in a string in C++?
If I have the string .....ZZ..ZZ..... or .Z.1.Z.23Z.4.Z55, Is there an easy way of shifting all Zcharacters in the string one space right of the current position? Some additional test strings are: .Z Z. ZZ. .ZZ Z ZZ ZZZ I think a few of the higher voted answers to this question (including the currently accepted one) do not work on these tests.
Just iterate through the text and swap characters: int main () { char text[] = "...Z.Z.Z...", temp; int text_len = strlen (text), i; for (i = text_len - 1; i >= 0; i--) { if (text[i] == 'Z') { temp = text[i+1]; text[i+1] = text[i]; text[i] = temp; } } printf ("%s\n", text); return 0; } Produces: [~]$ gcc zshift.c && ./a.out ....Z.Z.Z.. There's a lot of discussion in the comments about a possible off-by-1 error in the above code. However, simple testing / stepping through is enough to show that this is not the case. zshift "Z." -> ".Z" zshift ".Z" -> "." zshift "Z" -> "" I think the behavior of "dropping" trailing Zs when shifting off the end of the string is sensible. After all, if you shift the bits of an integer, bits that end up outside the bounds of the integer are dropped. If another behavior is desired -- for example, shifting only within the string -- the change to the algorithm is minimal: temp = text[i+1]; if (temp == 0) continue; text[i+1] = text[i]; text[i] = temp;
220,884
221,026
Should my C++ program support IA64 or only x64?
Should my program support IA64, or should it only support x64? I haven't been able to easily find IA64 computers myself. Is IA64 dead? MS seems to have a wide support for IA64, but it took me a long time to be able to find an IA64, and I had to end up getting it on eBay.
What kind of software do you develop? If it's not a data center type of application or a high-end number crunching app, I'd be surprised if there were any demand for an ia64 version. And even then, I'd think it would be a situation where if you have to ask if you should support it, you probably don't need to. A couple things off the top of my head that might hamper an ia64 port: any third party tools or libraries you're depending on need to support it unaligned accesses that go largely unnoticed on x86 and x64 will cause headaches on ia64 Of course, I don't work for Gartner or IDC or anyone who does market analysis, so you should take what I say here with whatever skepticism you have lying around. Have any customers or potential customers inquired?
220,891
220,962
In what syntax should a COM SDK reference document be written?
I have a COM SDK written in C++ and I'd like to create documentation for my product. I understand that most people will probably not use C++ for integration with this COM component, but many will. Which method is best to describe the API, without losing details that a C++ developer would need to know.
You can write the documentation directly in the IDL using the helpstring attributes - most consumers of your code will be able to read this directly using e.g., OLE View or in their object browser. Our company wrote an internal tool to extract the helpstring documentation and turn it into internal reference documentation in HTML. Also, you can use a tool like doxygen to document the interfaces - it will output HTML, PDF, LaTeX etc. format documentation.
221,185
221,257
How can I compile and run C/C++ code in a Unix console or Mac terminal?
How can I compile/run C or C++ code in a Unix console or a Mac terminal?
If it is a simple single-source program, make foo where the source file is foo.c, foo.cpp, etc., you don’t even need a makefile. Make has enough built-in rules to build your source file into an executable of the same name, minus the extension. Running the executable just built is the same as running any program - but you will most often need to specify the path to the executable as the shell will only search what is in $PATH to find executables, and most often that does not include the current directory (.). So to run the built executable foo: ./foo
221,281
221,325
Converting Simplifed Chinese GB 2312 text characters into UTF8
How do I convert text between multi-byte text strings, for example Simplified Chinese GB 2312, into UTF8 using c++ ?
On unix systems you'd best use the iconv library. See iconv_open, iconv, iconv_close You'd have to know the character encoding of course (EUC-CN, HZ). If not on a unix system, search for some support in the OS, doing character conversions by hand is very hard to get right.
221,346
221,351
What can I use instead of the arrow operator, `->`?
What is the arrow operator (->) a synonym for?
The following two expressions are equivalent: a->b (*a).b (subject to operator overloading, as Konrad mentions, but that's unusual).
221,482
221,548
Unit testing with C/C++: Lessons, what to remember?
Unit testing with C/C++: What do you teach people who either did not do unit testing before or come from Java/Junit? What is the single most important lesson / thing to remember/ practice from your point of view that saves a lot of time or stress (especially regarding C/C++)?
Unit tests have to run automatically on every checkin (or, unit tests that are written then forgotten are not unit tests). Before fixing a bug, write a unit test to expose it (it should fail). Then fix the bug and rejoice as the test turns green. It's OK to sacrifice a bit of "beauty" of a class for easier testing (like provide public methods that should not really be public, but help your testing/mocking).
221,894
221,934
C++: Get MAC address of network adapters on Vista?
We are currently using the NetBios method, and it works ok under XP. Preliminary tests under Vista show that it also works, but there are caveats - NetBIOS has to be present, for instance, and from what I've been reading, the order of the adapters is bound to change. Our alternative method - with SNMPExtensionQuery - seems to be broken under Vista. The question is: do you know of a reliable way to get a list of the local MAC addresses on a Vista machine? Backwards compatibility with XP is a plus (I'd rather have one single method than lots of ugly #ifdef's). Thanks!
Could you use the WMIService? I used it to get the mac-address of a machine in pre-Vista days though.
221,950
221,961
Operations on arbitrary value types
This article describes a way, in C#, to allow the addition of arbitrary value types which have a + operator defined for them. In essence it allows the following code: public T Add(T val1, T val2) { return val1 + val2; } This code does not compile as there is no guarantee that the T type has a definition for the '+' operator, but the effect is achieved with code like this: public T Add(T val1, T val2) { //Num<T> defines a '+' operation which returns a value of type T return (new Num<T>(val1) + new Num<T>(val2)); } Follow the link to see how the Num class achieves this. Anyways, on to the question. Is there any way to achieve the same effect in C or C++? For the curious, the problem I'm trying to solve is to allow a CUDA kernel to be more flexible/general by allowing it to operate on more types. Update: For .NET, Marc Gravell has made a utility library which solves the operator problem very elegantly.
Due to the way templates are compiled in C++, simply doing: template < class T > T add(T const & val1, T const & val2) { return val1 + val2; } will work, you'll get a compile error for every type where an operator+ is not defined. C++ templates generate code for every type instantiation, so for every type T code will be generated that does the right thing. This way C++ doesn't need Num<> trickery. In plain C, this is not possible as far as I know.
222,175
222,213
Why destructor is not called on exception?
I expected A::~A() to be called in this program, but it isn't: #include <iostream> struct A { ~A() { std::cout << "~A()" << std::endl; } }; void f() { A a; throw "spam"; } int main() { f(); } However, if I change last line to int main() try { f(); } catch (...) { throw; } then A::~A() is called. I am compiling with "Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86" from Visual Studio 2005. Command line is cl /EHa my.cpp. Is compiler right as usual? What does standard say on this matter?
The destructor is not being called because terminate() for the unhandled exception is called before the stack gets unwound. The specific details of what the C++ spec says is outside of my knowledge, but a debug trace with gdb and g++ seems to bear this out. According to the draft standard section 15.3 bullet 9: 9 If no matching handler is found in a program, the function terminate() (_except.terminate_) is called. Whether or not the stack is unwound before calling terminate() is implementation-defined.
222,189
222,234
Is it correct to export data members? (C++)
As the title suggests, is it correct or valid to import/export static data from within a C++ class? I found out my problem - the author of the class I was looking at was trying to export writable static data which isn't supported on this platform. Many thanks for the responses however.
Is it correct inasmuch as it'll work and do what you expect it to? Assuming that you are talking about using _declspec(dllexport/dllimport) on a class or class member, yes, you can do that and it should give you the expected result - the static data would be accessible outside your dll and other C++ code could access it provided that that C++ access specification (public/protected/private) wouldn't block outside access in the first place. Is it a good idea? Personally I don't think so as you would be exposing class internals not only within your library but to the outside world, which means that it will be pretty much impossible to change what is an implementation detail at the end of the day. Ask yourself if you are 100% certain if the interface of this class and large parts of its implementation will never, ever change...
222,195
222,288
Are there gotchas using varargs with reference parameters
I have this piece of code (summarized)... AnsiString working(AnsiString format,...) { va_list argptr; AnsiString buff; va_start(argptr, format); buff.vprintf(format.c_str(), argptr); va_end(argptr); return buff; } And, on the basis that pass by reference is preferred where possible, I changed it thusly. AnsiString broken(const AnsiString &format,...) { ... the rest, totally identical ... } My calling code is like this:- AnsiString s1, s2; s1 = working("Hello %s", "World"); s2 = broken("Hello %s", "World"); But, s1 contains "Hello World", while s2 has "Hello (null)". I think this is due to the way va_start works, but I'm not exactly sure what's going on.
If you look at what va_start expands out to, you'll see what's happening: va_start(argptr, format); becomes (roughly) argptr = (va_list) (&format+1); If format is a value-type, it gets placed on the stack right before all the variadic arguments. If format is a reference type, only the address gets placed on the stack. When you take the address of the reference variable, you get the address or the original variable (in this case of a temporary AnsiString created before calling Broken), not the address of the argument. If you don't want to pass around full classes, your options are to either pass by pointer, or put in a dummy argument: AnsiString working_ptr(const AnsiString *format,...) { ASSERT(format != NULL); va_list argptr; AnsiString buff; va_start(argptr, format); buff.vprintf(format->c_str(), argptr); va_end(argptr); return buff; } ... AnsiString format = "Hello %s"; s1 = working_ptr(&format, "World"); or AnsiString working_dummy(const AnsiString &format, int dummy, ...) { va_list argptr; AnsiString buff; va_start(argptr, dummy); buff.vprintf(format.c_str(), argptr); va_end(argptr); return buff; } ... s1 = working_dummy("Hello %s", 0, "World");
222,471
222,494
Setting up a Programming Environment in Linux
I recently started using Linux as my primary OS. What are the tools that I will need to set up a complete programming environment in Linux for C and C++?
Standard stuff: The compiler tools, gcc, gdb, etc. Some sort of editor/IDE (emacs, vim, eclipse) Profiling tools Source Control (SubVersion, git, etc) Language specific tools, like easy_install for python (you said C/C++, but the same goes for everything) A web server maybe? Apache, Lighttpd, nginx Any libraries you'll be using. Are you doing kernal hacking? Driver development? opengl?
222,557
222,578
What uses are there for "placement new"?
Has anyone here ever used C++'s "placement new"? If so, what for? It looks to me like it would only be useful on memory-mapped hardware.
Placement new allows you to construct an object in memory that's already allocated. You may want to do this for optimization when you need to construct multiple instances of an object, and it is faster not to re-allocate memory each time you need a new instance. Instead, it might be more efficient to perform a single allocation for a chunk of memory that can hold multiple objects, even though you don't want to use all of it at once. DevX gives a good example: Standard C++ also supports placement new operator, which constructs an object on a pre-allocated buffer. This is useful when building a memory pool, a garbage collector or simply when performance and exception safety are paramount (there's no danger of allocation failure since the memory has already been allocated, and constructing an object on a pre-allocated buffer takes less time): char *buf = new char[sizeof(string)]; // pre-allocated buffer string *p = new (buf) string("hi"); // placement new string *q = new string("hi"); // ordinary heap allocation You may also want to be sure there can be no allocation failure at a certain part of critical code (for instance, in code executed by a pacemaker). In that case you would want to allocate memory earlier, then use placement new within the critical section. Deallocation in placement new You should not deallocate every object that is using the memory buffer. Instead you should delete[] only the original buffer. You would have to then call the destructors of your classes manually. For a good suggestion on this, please see Stroustrup's FAQ on: Is there a "placement delete"?
222,667
222,687
XML-RPC library for C++
What libraries are available for writing xml-rpc clients in native C++ or C?
You might want to check out either xmlrpc-c or xmlrpc++.
222,916
222,926
In a multi-threaded C++ app, do I need a mutex to protect a simple boolean?
I have a multi-threaded C++ app which does 3D rendering with the OpenSceneGraph library. I'm planning to kick off OSG's render loop as a separate thread using boost::threads, passing a data structure containing shared state in to the thread. I'm trying to avoid anything too heavyweight (like mutexes) for synchronization, as the render loop needs to be pretty tight, and OSG itself tries to avoid having to ever lock. Most of the shared state is set before the thread is started, and never changed. I do have some data that does need to be changed, which I am planning to double-buffer. However, I have a simple boolean for signaling the thread to suspend rendering, and later resume rendering, and another to kill it. In both cases the app thread sets the bool, and the render thread only reads it. Do I need to synchronize access to these bools? As far as I can tell, the worse thing that could happen is the the render loop continues on for an extra frame before suspending or quitting.
In C++11 and later, which has standards-defined concurrency, use std::atomic<bool> for this purpose. From http://en.cppreference.com/w/cpp/atomic/atomic: If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined (see memory model for details on data races). The following old answer may have been true at some time in the past with some compilers and some operating environments, but it should not be relied upon today: You're right, in this case you won't need to synchronise the bools. You should declare them volatile though, to ensure that the compiler actually reads them from memory each time, instead of caching the previous read in a thread (that's a simplified explanation, but it should do for this purpose). The following question has more information about this: C++ Thread, shared data
223,021
223,047
What's the scope of the "using" declaration in C++?
I'm using the 'using' declaration in C++ to add std::string and std::vector to the local namespace (to save typing unnecessary 'std::'s). using std::string; using std::vector; class Foo { /*...*/ }; What is the scope on this declaration? If I do this in a header, will it inject these 'using' declarations into every cpp file that includes the header?
When you #include a header file in C++, it places the whole contents of the header file into the spot that you included it in the source file. So including a file that has a using declaration has the exact same effect of placing the using declaration at the top of each file that includes that header file.
223,215
223,230
C++ example of Coding Horror or Brilliant Idea?
At a previous employer, we were writing binary messages that had to go "over the wire" to other computers. Each message had a standard header something like: class Header { int type; int payloadLength; }; All of the data was contiguous (header, immediately followed by data). We wanted to get to the payload given that we had a pointer to a header. Traditionally, you might say something like: char* Header::GetPayload() { return ((char*) &payloadLength) + sizeof(payloadLength); } or even: char* Header::GetPayload() { return ((char*) this) + sizeof(Header); } That seemed kind of verbose, so I came up with: char* Header::GetPayload() { return (char*) &this[1]; } It seems rather disturbing at first, possibly too odd to use -- but very compact. There was a lot of debate on whether it was brilliant or an abomination. So which is it - Crime against coding, or nice solution? Have you ever had a similar trade-off? -Update: We did try the zero sized array, but at the time, compilers gave warnings. We eventually went to the inhertited technique: Message derives from Header. It works great in practice, but in priciple you are saying a message IsA Header - which seems a little awkward.
I'd go for crime against coding. Both methods will generate the exact same object code. The first makes it's intention clear. The second is very confusing, with the only advantage that it saves a couple keystrokes. (Just learn to freakin' type). Also, note that NEITHER method is guaranteed to work. The sizeof() an object includes padding for word alignment, so that if the header was: class Header { int type; int payloadLength; char status; }; Both methods you describe would have the payload starting at Header+12, when most likely it actually starts at Header+9.
223,314
224,393
How to create an empty DOMElement
I am using Xerces-c in my project, and would like to create a single DOMElement without having to create a whole new DOMDocument. Is such a thing possible?
I haven't seen a way. AFAIK the DOMDocument acts as the "memory pool" and all elements are created in this pool. In the Xerces docs we see: Objects created by DOMDocument::createXXXX Users can call the release() function to indicate the release of any orphaned nodes. When an orphaned Node is released, its associated children will also be released. Access to a released Node will lead to unexpected behaviour. These orphaned Nodes will eventually be released, if not already done so, when its owner document is released I've worked around this situation by keeping a scratch pad DOMDocument around and using it to create fragments or orphan nodes and adopting them into their destination documents when I'm ready. E.g. // Create a fragment holding two sibling elements. The first element also has a child. DOMDocumentFragment* frag = scratchDom->createDocumentFragment(); DOMNode* e1 = frag->appendChild( frag->getOwnerDocument()->createElement("e1") ); e1->appendChild( e1->getOwnerDocument()->createElement("e1-1") ); DOMNode* e2 = frag->appendChild( frag->getOwnerDocument()->createElement("e2") ); ... // Paste the contents of the fragment into a "parent" node from another document DOMNode* parentFromOtherDom = ...; parentFromOtherDom->appendChild( parentFromOtherDom->getOwnerDocument()->adopt(frag) ); scratchDom->removeChild(frag);
223,421
224,705
Adding unit tests to an existing project
My question is quite relevant to something asked before but I need some practical advice. I have "Working effectively with legacy code" in my hands and I 'm using advice from the book as I read it in the project I 'm working on. The project is a C++ application that consists of a few libraries but the major portion of the code is compiled to a single executable. I 'm using googletest for adding unit tests to existing code when I have to touch something. My problem is how can I setup my build process so I can build my unit tests since there are two different executables that need to share code while I am not able to extract the code from my "under test" application to a library. Right now I have made my build process for the application that holds the unit tests link against the object files generated from the build process of the main application but I really dislike it. Are there any suggestions?
If your test app is only linking the object files it needs to test then you are effectively already treating them as a library, it should be possible to group those object files into a separate library for the main and the test app. If you can't then I don't see that what you are doing is too bad an alternative. If you are having to link other object files not under test then that is a sign of dependencies that need to be broken, for which you have the perfect book. We have similar problems and use a system like the one suggested by Vlion
223,634
223,665
Linux programming environment configuration
The other day I set up an Ubuntu installation in a VM and went to gather the tools and libraries I figured I would need for programming mostly in C++. I had a problem though, where to put things such as 3rd party source libraries, etc. From what I can gather, a lot of source distributions assume that a lot of their dependencies are already installed in a certain location and assume that a lot of tools are also installed in particular locations. To give an example of what I currently do on Windows, is I have a directory where I keep all source code. C:\code. In this directory, I have a directory for all 3rd party libraries, c:\code\thirdparty\libs. This way I can easily set up relative paths for all of the dependencies of any projects I write or come across and wish to compile. The reason I am interested in setting up a linux programming environment is that it seems that both the tool and library dependency problems have been solved efficiently making it easy for example to build OpenSSH from source. So what I was looking for was a decent convention I can use when I am trying to organize my projects and libraries on linux that is easy to maintain and easy to use.
Short answer: don't do a "heaps of code in local dir" thing. Long answer: don't do a "heaps of code in local dir" thing, because it will be nightmare to keep up-to-date, and if you decide to distribute your code, it will be nightmare to package it for any decent distribution. Whenever possible, stick to the libraries shipped in the distribution (ubuntu has 20000+ packets, it ought to have most of what you'll need prepackaged). When there is not package, you caninstall by hand to /usr/local (but see above about upgrades and DONT do that). Better, use "stow" or "installwatch" (or both) to install to per-library dirs (/usr/local/stow/libA-ver123) and then symlink files from there to /usr/local or /usr/ (stow does the simlinking part). Or just package the lib for your distribution.
223,919
223,943
Having trouble linking a static library C++
I've figured out how to set VC++ to compile code into a .lib file instead of a .exe, but I'm having trouble getting a lib to link together with my other .obj files. Here is how I have the library and application folders set up. (I'm not sure if this is right) AppFolder App.sln App.ncb *.h *.cpp Debug *.obj App.exe and somewhere else on the hard drive... LibraryFolder lib Library.lib include LibrarySolutionFolder Library.sln Library.ncb *.h *.cpp Debug *.obj Library.lib I've been #including the library *.h files from my app's cpp files, and everything compiles fine. It's just when it links I get a list of all the .lib files that are being searched, and Library.lib isn't on there even though I have it listed in VC++ directories. How can I get this to link? (And am I structuring the library folders correctly?)
On the project properties: Configuration Properties -> Linker -> Input -> Additional Dependancies Add it in there. Or, in your .h file for the library, add: #pragma comment(lib, "Library") This will do it automatically for you.
224,043
224,063
Timer in a win32 service
Can someone please point me to the easiest way to have a timer in a Win32 service? I suppose I could create a dummy window for this purpose or have a second thread do tick counts, but what's best? Is there a more elegant way? Thanks in advance.
You can use Timer Queues (http://msdn.microsoft.com/en-us/library/ms686796.aspx). They don't require an HWND.
224,090
343,141
local variables in constructors are not followed. Is this a bug in gdb ?
I am currently running gdb version 6.7.1 on Ubuntu Linux, and working in a C++ project. Surprisingly I was trying to debug a constructor and I have found that local variables declared within the scope of the constructor are not followed or noticed by gdb. Is this a bug ? Thanks for any information ..
It is a bug in GCC, not in GDB. It was recently fixed.
224,163
224,177
Capturing R6025 pure virtual call
I currently capture MiniDumps of unhandled exceptions using SetUnhandledExceptionFilter however at times I am getting "R6025: pure virtual function". I understand how a pure virtual function call happens I am just wondering if it is possible to capture them so I can create a MiniDump at that point.
If you want to catch all crashes you have to do more than just: SetUnhandledExceptionFilter I would also set the abort handler, the purecall handler, unexpected, terminate, and invalid parameter handler. #include <signal.h> inline void signal_handler(int) { terminator(); } inline void terminator() { int*z = 0; *z=13; } inline void __cdecl invalid_parameter_handler(const wchar_t *, const wchar_t *, const wchar_t *, unsigned int, uintptr_t) { terminator(); } And in your main put this: signal(SIGABRT, signal_handler); _set_abort_behavior(0, _WRITE_ABORT_MSG|_CALL_REPORTFAULT); set_terminate( &terminator ); set_unexpected( &terminator ); _set_purecall_handler( &terminator ); _set_invalid_parameter_handler( &invalid_parameter_handler ); The above will send all crashes to your unhandled exception handler.