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
626,511
626,594
CComboBox automatically selects text after call to MoveWindow
I'm currently experiencing a very strange problem with a CComboBox used within a CFormView. After adding strings to the combobox (created with WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_VSCROLL | CBS_DROPDOWN | CBS_SORT | CBS_AUTOHSCROLL), I'm selecting an entry via CComboBox::SetCurSel and resize the combobox via MoveWindow in the OnSize() handler of the CFormView derived class. As soon as I include the call to MoveWindow, the whole text in the edit part of the combobox gets selected. If I remove the call to MoveWindow, the text doesn't get selected. This happens not only for one, but for all comboboxes used. I'm somehow lost at this point. Any hint is much appreciated!
Selecting all the text is standard Windows behavior when a combo box gets focus. I guess the MoveWindow is resetting the focus on the control. Try using CComboBox::SetEditSel to remove the selection after MoveWindow.
626,708
626,731
How to recover from lost source code?
I have a one-function DLL that exports GetHash(). However, the source code for this DLL is lost. I need to integrate this code into my MSVC++ project. I know that there are some shareware tools for doing this, but I think that I can do it manually. What do I need to do, to accomplish this manually?
In a project that you build, reference the dll and call the hash function. Run the code in the debugger and step in and disassemble the function and translate it back into a high level language. If this isn't good enough, disassemble code into a series of functions you can implement with ASM blocks.
626,744
626,890
Is there a way to automatically avoiding stepping into certain functions in Visual Studio?
I'm aware of the "Enable just my code" debug option, but that only works for managed code. I'm looking for a way to step into a function call without having to step through, for example, an STL string cast operator because there is an implicit conversion from a char* to a string in one of the function's parameters.
I found this blog entry which has a solution. Although I'd prefer to be able to say "don't step into anything that isn't part of this project", this looks workable. EDIT: After looking at a few blogs and newsgroups, the method is to add an entry for each function that you don't want to step into under this registry key (assuming VS 2005): 32 bit Windows \\HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\8.0\NativeDE\StepOver 64 bit Windows \\HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\VisualStudio\8.0\NativeDE\StepOver Version numbers for the path: Visual Studio 2005: 8.0 Visual Studio 2008: 9.0 Visual Studio 2010: 10.0 Visual Studio 2012: 11.0 Visual Studio 2013: 12.0 This key contains a set of rules which affect how stepping is performed. Each rule is specified as a separate entry whose name is a decimal number and whose value is a function name pattern that specifies which functions we want to affect. e.g. "10" = "boost\:\:scoped_ptr.*\:\:.*=NoStepInto" prevents stepping into boost::scoped_ptr functions. The rules are evaluated from high to low values until a matching pattern is found, or there are no rules left. In that case the function is stepped into. Function names are regular expressions. Colons need to be quoted with a backslash. You can specify StepInto as well as NoStepInto. This gives you a way to avoid stepping into all but a few functions in the same scope/namespace. Restart Visual Studio to pick up the changes to the registry.
626,849
626,884
Initialize COM object / Translate VB code to C++
Can anybody translate the following code to C++? Is this possible at all or are there vital information missing? Dim Laser As Object Sub EnableLaser ‘ Create a laser object if it hasn’t been done yet If Laser Is Nothing Then Set Laser = CreateObject("NWLaserXControl.NWLaserX") End If If Laser.Initialize Then Laser.RepRate = 10 ‘ set the rep rate to 10Hz Laser.LaserEnabled = True ‘ turn on laser power supply, get it ready End If End Sub
// if (CoInitialize(0) == S_OK) { CComPtr<INWLaserX> pMyPtr = NULL; CLSID clsid = IID_NULL; CLSIDFromProgID("NWLaserXControl.NWLaserX"); if (pMyPtr.CoCreateInstance(clsid) == S_OK) { pMyPtr->put_RepRate(10); pMyPtr->put_LaserEnabled(TRUE); } // CoUnInitialize(); }
626,865
626,973
How to keep implementation/maintenance costs low in Pro*C?
Having experienced the horror that is Oracle Pro*C, when dealing with dynamically specified columns, and the need for bulk operations (ANSI METHOD 4), I simply must ask: What Ideas/Techniques can you share which makes it easier to develop/test/debug/maintain C and C++ CRUD applications which use ProC or ProC++? I am specifically interested in the Pro*C aspects.
Pull as much of the Oracle stuff out of the C code as you can and stick it in database PL/SQL packages/procedures/functions. Isolate (to the extent possible) the Oracle functionality in your C code. The less scattered your oracle calls are around your C code the better. Even better, have a library/DLL that contains the Oracle-specific stuff. Oh, and don't forget to sacrifice a goat on the altar at midnight...
627,131
627,889
GetDiskFreeSpaceEx reports wrong number of free bytes
__int64 i64FreeBytes unsigned __int64 lpFreeBytesAvailableToCaller, lpTotalNumberOfBytes, lpTotalNumberOfFreeBytes; // variables used to obtain // the free space on the drive GetDiskFreeSpaceEx (Manager.capDir, (PULARGE_INTEGER)&lpFreeBytesAvailableToCaller, (PULARGE_INTEGER)&lpTotalNumberOfBytes, (PULARGE_INTEGER)&lpTotalNumberOfFreeBytes); i64FreeBytes = lpTotalNumberOfFreeBytes; _tprintf(_T ("Number of bytes free on the drive:%I64u \n"), lpTotalNumberOfFreeBytes); I am working on a data management routine which is a Windows CE command line application. The above code shows how I get the number of free bytes on a particular drive which contains the folder Manager.capdir (it is the variable containing the full path name of the directory). My question is, the number of free bytes reported by the above code (the _tprintf statement) doesn't match with the number of free bytes of the drive (which i check by doing a right click on the drive). I wish to know if the reason for this difference?
I have a single-user machine with no disk quota in operation. I posted your code into a dialog based MFC application and ran it, with the single proviso that I used "C:\" as the lpDirectoryName parameter so I could compare against the drive free space as reported by the system. That seemed logical as free space is only meaningful for a drive, not a folder. At first I thought that I was seeing a similar problem, but then I re-ran the check (I tied it to a button), and got the same result as the properties dialog at that moment. It seems the free space on a drive is a fairly dynamic quantity - this is not terribly suprising if it is the system drive - and even absent the criteria that other posters have quite correctly reported, you may not see precisely the same number as the properties dialog reports at the moment it was run.
627,143
629,972
How to handle notify messages in child & parent classes?
I have a custom CTabCtrl which I am trying to customize (to automatically change pages). If I handle ON_NOTIFY_REFLECT(TCN_SELCHANGE, ...) in my tab control, ON_NOTIFY(TCN_SELCHANGE, ...) is not received by the parent class. How can I receive both notify messages in the child and parent classes? Currently I am using a "workaround" of manually sending the WM_NOTIFY message to the parent class: void CMyTabControl::OnSelChange(NMHDR *pHeader, LRESULT *pResult) { const int index = this->GetCurSel(); this->ShowTab(index); const CWnd *const pParent = this->GetParent(); if (pParent != NULL) { *pResult = pParent->SendMessage(WM_NOTIFY, TCN_SELCHANGE, reinterpret_cast<LPARAM>(pHeader)); } } Edit: I've tried both *pResult = 0 and *pResult = 1 but it still doesn't send the message onto the parent. Also, I've noticed that when I send the message on to the parent I end up in an almost infinite loop (for some reason it does break out after several iterations).
I've found the answer: http://msdn.microsoft.com/en-us/library/eeah46xd.aspx Basically you have to use ON_NOTIFY_REFLECT_EX and then return FALSE from your function to enable the parent notify message to be fired.
627,218
630,070
Is there a plugin that integrates to CPPUnit with VS2008 or Eclipse CDT?
We have some projects that have CPPUnit tests that are build and run using an ant script to build them all (right now we're using Borland C++, but we're moving to VS2008). The problem is that the interface to run and see the result of tests is unpleasant (command prompt). It would be awesome to have them run inside eclipse or VS2008. It would be a lot better if a plugin that I could select the tests I want to run and get some visual feedback (green bar/red bar), pointing me to the tests that failed and the messages. This exists with JUnit in Eclipse (for java), but is there something similar for C++ using Eclipse CDT or VS2008? A UI test runner would be usefull too, so I could launch the UI as a Post build action. EDIT (possible answer): I found this project: ECUT, however I didn't test it yet. Looks promising thou. I'll update this question as soon as I get more experience with the project.
Their doesn't seem to be a test runner for within Visual Studio, just the MfcTestRunner and the QtTestRunner. For Visual Studio, Resharper and TestDriven.Net are the usual suspects to first look for test runners, but both don't have support for CPPUnit.
627,273
627,293
Will auto_ptr protect against this?
I am not quite clear if auto_ptr will help me in this case: class A { A(const B& member) : _member(B) {}; ... const B& _member; }; A generateA() { auto_ptr<B> smart(new B()); A myA(*smart); return myA; } Will the myA._member reference be valid when smart leaves its enclosing scope? If auto_ptr isn't the answer here, what is? EDIT: I see where I confused everyone; I have to return myA outside the scope, which is why I care about _member being valid after smart exits the scope.
It won't help you. _member will become a dangling handle. This is because auto_ptr guarantees destruction at end of scope: no more, and no less. There are 2 possible answers. You can make _member's type boost::shared_ptr<const B>. Alternatively, if class B is small, copyable, monomorphic, and object identity doesn't need to be preserved, you can make _member a value, and store a copy of the argument there. This is by far the simplest option but obviously it is quite limiting. In response to your edit: That is indeed the case that I was talking about. By returning myA by value, a copy is created, and the copy's _member refers to the already destructed local. As described, both shared_ptr and value semantics solve this.
627,319
627,334
how do I get a process to reload itself in linux?
I have a service, say foo, written in C++, that runs as root. There is the usual scrip, /etc/init.d/foo start|stop|restart. At certain times, foo needs to reload itself. Normally after an upgrade has finished. But doing things like: system("/etc/init.d/foo restart") doesn't work since as soon as restart kills foo, the system() call obviously gets killed as well, and the restart script never executes to completion. Is there another call I can use instead of system() that runs asynchronously as a sibling to the calling process, instead of creating a synchronous child? Thanks!
Have you considered the exec[*] family yet? Here's one -- execve.
627,512
627,546
Help with declaring C++ structure, with a float array as one of its members
I was wondering if anyone could spot what is wrong with my structure declaration and use. At the moment I have a structure and wish to store float array as one of it's members. My code: struct Player{ float x[12]; float y[12]; float red,green,blue; float r_leg, l_leg; int poly[3]; bool up,down; }; I then tried filling the struct: float xcords[12] = {1,1,1,1,1,1,1,1,1,1,1,1 }; float ycords[12] = {1,1,1,1,1,1,1,1,1,1,1,1 }; Player player = {xcords,ycords,1,1,1,2,2,true,true}; Error: 1>.\template_with_console.cpp(35) : error C2440: 'initializing' : cannot convert from 'float [12]' to 'float' 1> There is no context in which this conversion is possible 1>.\template_with_console.cpp(35) : error C2440: 'initializing' : cannot convert from 'float [12]' to 'float' 1> There is no context in which this conversion is possible
Arrays decay to pointer-to-first-element of the array in most contexts as is the case with xcords and ycords. You cannot initialize the struct like this. So, you have to initialize the members explicitly: Player player = { {1,1,1,1,1,1,1,1,1,1,1,1 }, // xcords {1,1,1,1,1,1,1,1,1,1,1,1 }, // ycords 1,1,1, // red, green, blue 2,2, // right, left {0,1,2}, // poly[3] -- missing? true,true}; // up, down You are also missing initializers for poly[3] if I understand correctly. Put in the appropriate values. Otherwise there will be default initialization -- is that what you want?
628,410
628,421
error: X may be used uninitialized in this function in C
I am getting this error error: Access.Core may be used uninitialized in this function And this is my code: static int FirstTime = 1; MyStruct Access; if (FirstTime) { FirstTime = 0; Access = Implementation(); DoSomething(Access); } if(Other_Variable) { Access = Implementation2(); DoSomething(Access); } //The Other_Variable will be set to 1 and to 0 by other part of the code My code is like that because I want to call to the function Implementation only the first time. In every call the Access variable is going to be updated so it does not make many sense make it static. If I make Access static works, but I do not like make it static because in every other call Access is going to be updated. Any way to avoid the problem without making it static?. Also any better options to execute only once a function instead of using a static variable are welcome.
Make Access like this (and remove FirstTime and the if): static MyStruct Access = Implementation(this_b); The reason you get this warning is because static variables survive one function call. Their value is retained across all function calls (without regard to which thread calls that function). So, FirstTime will control whether you initialize Access. The first time you call the function that code is in will correctly initialize the Access variable. But with every further function call, FirstTime is zero, and you will not initialize Access anymore, and thus will use an uninitialized variable down the code. Edit: Now, with your updated information, you say that you have two Implementation functions. The first time you want to use one, and all the other times you want to use another function. How about this then: // static will be false/zero by default static bool AlreadyCalled; MyStruct Access; if (!AlreadyCalled) { Access = Implementation(); AlreadyCalled = true; } else { Access = Implementation2(); } Depending on your actual use case, there may be better ways to handle this, though. For example, why not update the state of Access, like this: // let the default constructor initialize it // to a plausible state static MyStruct Access; // use RAII to update the state of Access when this // function returns. MyUpdater updater(Access); // now, do whatever the function does. Something like this for MyUpdater: struct MyUpdater { MyStruct &s; MyUpdater(MyStruct &s):s(s) { } ~MyUpdater() { s.ChangeState(); } }; That pattern is called RAII: You associate some useful action with the constructor and destructor of a locally allocated object.
628,526
628,554
Is short-circuiting logical operators mandated? And evaluation order?
Does the ANSI standard mandate the logical operators to be short-circuited, in either C or C++? I'm confused for I recall the K&R book saying your code shouldn't depend on these operations being short circuited, for they may not. Could someone please point out where in the standard it's said logic ops are always short-circuited? I'm mostly interested on C++, an answer also for C would be great. I also remember reading (can't remember where) that evaluation order isn't strictly defined, so your code shouldn't depend or assume functions within an expression would be executed in a specific order: by the end of a statement all referenced functions will have been called, but the compiler has freedom in selecting the most efficient order. Does the standard indicate the evaluation order of this expression? if( functionA() && functionB() && functionC() ) cout<<"Hello world";
Yes, short-circuiting and evaluation order are required for operators || and && in both C and C++ standards. C++ standard says (there should be an equivalent clause in the C standard): 1.9.18 In the evaluation of the following expressions a && b a || b a ? b : c a , b using the built-in meaning of the operators in these expressions, there is a sequence point after the evaluation of the first expression (12). In C++ there is an extra trap: short-circuiting does NOT apply to types that overload operators || and &&. Footnote 12: The operators indicated in this paragraph are the built-in operators, as described in clause 5. When one of these operators is overloaded (clause 13) in a valid context, thus designating a user-defined operator function, the expression designates a function invocation, and the operands form an argument list, without an implied sequence point between them. It is usually not recommended to overload these operators in C++ unless you have a very specific requirement. You can do it, but it may break expected behaviour in other people's code, especially if these operators are used indirectly via instantiating templates with the type overloading these operators.
628,588
628,609
Renaming executable causes error when run
I have created a small daemon (basically a console application that hides the console and runs). I need to send it to a user and have tried renaming the executable with a different extension, emailing it to the user, and having them rename it to the correct name. This seems to work when I email it to myself to test it. However, when the user tries to run the executable it produces the following error message: This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix the problem. What am I doing wrong?
You are missing some dlls. You can figure out exactly which ones using dependency walker. You could also install the Visual Studio Re-distributable package (x86) or Visual Studio Re-distributable package (x64) and that will probably fix your problem too.
628,790
628,867
Have a good hash function for a C++ hash table?
I am in need of a performance-oriented hash function implementation in C++ for a hash table that I will be coding. I looked around already and only found questions asking what's a good hash function "in general". I've considered CRC32 (but where to find good implementation?) and a few cryptography algorithms. My table, though, has very specific requirements. Here's what the table will be like: 100,000 items max 200,000 capacity (so the load is 0.5) hashing a 6-character string which is a part of English sentence examples: "become" "and he" ", not " The number one priority of my hash table is quick search (retrieval). Quick insertion is not important, but it will come along with quick search. Deletion is not important, and re-hashing is not something I'll be looking into. To handle collisions, I'll be probably using separate chaining as described here. I have already looked at this article, but would like an opinion of those who have handled such task before.
Now assumming you want a hash, and want something blazing fast that would work in your case, because your strings are just 6 chars long you could use this magic: size_t precision = 2; //change the precision with this size_t hash(const char* str) { return (*(size_t*)str)>> precision; } CRC is for slowpokes ;) Explanation: This works by casting the contents of the string pointer to "look like" a size_t (int32 or int64 based on the optimal match for your hardware). So the contents of the string are interpreted as a raw number, no worries about characters anymore, and you then bit-shift this the precision needed (you tweak this number to the best performance, I've found 2 works well for hashing strings in set of a few thousands). Also the really neat part is any decent compiler on modern hardware will hash a string like this in 1 assembly instruction, hard to beat that ;)
628,933
684,144
CStatusBarCtrl GetItemRect XP Manifest
When using a CStatusBarCtrl in MFC I use GetItemRect to get the bounds of each item within the CStatusBar. However I am seeing a problem now I use an XP manifest in the exe. That it will not return a correct rectangle so I no longer identify correctly when the mouse is in the far right of the control. The problem can be tested with a method like this: GetStatusBarCtrl().SetTipText(n - 1, _T("Test")); When a CStatusBarCtrl is created and a pane is created with SetPaneInfo and the text set as above the tip text will not be visible when you mouse over the far right hand side pane. This problem has been reported elsewhere. But has not got a satisfactory answer. I need a solution or work around would be great.
My first guess would be differences between 'THEMES' in Vista and XP. Remember, if you are using a CFrameWnd there is a gripper control in what would be your last pane in the far right of the status bar. So, it looks as though changes in the ComCtl32.dll may account for this, thus, giving you a smaller rect. I assume you are just seeing a smaller rect.Width() than you did before? You are not talking about smaller X and Y at the same time are you? If you have to, you may want to look for the correct version and deploy it with your app, or make your manifest reflect which version to use... Sorry I don't have a clear cut answer, but Themes are the only thing that come to mind, since if I recall correctly, in VC6, the gripper was added on top of the status bar, OR the status bar was shrunk just enough to display it... One suggestion you could use would be to detect your running version of Windows, and made the assumption of the gripper for the OS. The gripper will be the same size as the VScroll bar, so you can naturally remove that many DLU's (or Pixels) from the last cell at runtime, and render text based on that. I'll have to go home and fire up VC6, and see how it acts based on what you are saying here... I don't have a Vista VM handy to see what version of ComCtl32.dll it has installed by default, but it's my guess they put some code in it to deal with the gripper. If you have complete sample code, that would really make things easier on me too... Otherwise, I have to start digging for all my old VC6 generated code and go from there... An interesting test would be to call GetSystemMetrics on the pieces that we think could have an effect on this, and see how they differ from system to system. If you put Vista into "Windows Classic" mode, do you still see the same results? Also, which machine is your dev box? Vista or XP?
629,017
629,063
how does array[100] = {0} set the entire array to 0?
How does the compiler fill values in char array[100] = {0};? What's the magic behind it? I wanted to know how internally compiler initializes.
It's not magic. The behavior of this code in C is described in section 6.7.8.21 of the C specification (online draft of C spec): for the elements that don't have a specified value, the compiler initializes pointers to NULL and arithmetic types to zero (and recursively applies this to aggregates). The behavior of this code in C++ is described in section 8.5.1.7 of the C++ specification (online draft of C++ spec): the compiler aggregate-initializes the elements that don't have a specified value. Also, note that in C++ (but not C), you can use an empty initializer list, causing the compiler to aggregate-initialize all of the elements of the array: char array[100] = {}; As for what sort of code the compiler might generate when you do this, take a look at this question: Strange assembly from array 0-initialization
629,018
629,336
Advantage of porting vc6 to vc2005/vc2008?
I was asking my team to port our vc6 application to vc2005, they are ready to allot sometime to do the same.Now they need to know what is the advantage of porting. I don't thing they really understand what does it mean to adhere to standard compliance. Help me list out the advantage to do the porting. Problem I am facing are 1)No debugging support for standard containers 2)Not able to use boost libraries 3)We use lot of query generation but use CString format function that is not type safe 4)Much time is spent on trouble shooting vc6 problems like having >> vector<vector<int>> with out space between >>
Advantages: More standards compliant compiler. This is a good thing because it will make it easier to port to another platform (if you ever want to do that). It also means you can look things up in the standard rather than in microsoft's documentation. In the end you will have to upgrade your compiler at some point in the feature. The sooner you do it, the less work it will be. Not supported by MS. The new SDK doesn't work. 64-bit doesn't work. And I don't think they're still fixing bugs either. Nicer IDE. Personally, I really prefer tabs to MDI. I also think that it's much easier to configure Visual Studio (create custom shortcuts, menu bars, etc.). Of course that's subjective. Check out an express edition and see if you agree. Better plugin support. Some plugins aren't available for VC6. Disadvantages: Time it takes to port. This very much depends on what kind of code you have. If your code heavily uses non-standards compliant VC6 features, it might take some time. As Andrew said, if you're maintaining an old legacy project, it might not be worth it. Worse Performance. If you're developing on really old computers, Visual Studio may be too slow. Cost I just had a quick look and Visual Studio licenses seem to be a bit more expensive than VC6's.
629,085
629,303
unresolved external symbol _CLSID_ScenicIntentUIFramework with GUID
I'm trying to build a ribbon app in visual studio and I got that linker error. After looking through the headers, I noticed that CLSID_ScenicIntentFramework is defined as extern const CLSID. The think is, I can't seem to figure out which library I need to link to (or other header i need to import?). I'd really appreciated some help too. Afternote: I noticed that in addtion to scenicintent.h, there is a scenicintent.idl, but if I include this into my project I get a slew of errors. Is there a proper way to include idl files, and would that fix my issue?
Often times, you need to link to an import library (.lib file) that contains the definitions of the class ids and interface ids for the library you are using. Alternatively, you can use the __uuidof keyword that can get the associated GUID for an attributed object (a class or interface). __uuidof(ScenicIntentFramework) // this should be the same thing
629,141
629,149
why bit-fields for same data types have less in size compared to bit-fields for mix-data types
I am curious to know why bit fields with same data type takes less size than with mixed data types. struct xyz { int x : 1; int y : 1; int z : 1; }; struct abc { char x : 1; int y : 1; bool z : 1; }; sizeof(xyz) = 4 sizeof(abc) = 12. I am using VS 2005, 64bit x86 machine. A bit machine/compiler level answer would be great.
Alignment. Your compiler is going to align variables in a way that makes sense for your architecture. In your case, char, int, and bool are different sizes, so it will go by that information rather than your bit field hints. There was some discussion in this question on the matter. The solution is to give #pragma directives or __attributes__ to your compiler to instruct it to ignore alignment optimizations.
629,205
647,087
Need help to display Japanese Text using GDI+ without installing East Asian Language pack in Windows XP
I am writing a Japanese language quiz program and I don't want to require people to install the East Asian language pack for Windows XP. I am using GDI+ for drawing text. I tried downloading a free Unicode font and using that to draw text. I tested it on my computer (with East asian pack installed) and it displayed the Japanese characters correctly using the downloaded font, but on another computer without the language pack it didn't work. I am looking for suggestions on how to make this work. The program is pretty simple and is written in C++ using only Win32 API, GDI+, and STL. If possible I would like to stick to just these libraries. I do have UNICODE #defined. The code that I am basically using for drawing text is pasted below: #include <gdiplus.h> using namespace Gdiplus ; Graphics * gi ; PrivateFontCollection _fonts ; _fonts.AddFontFile(fontFilename) ; Font * currentFont = new Font(fontName, fontSize, FontStyleRegular, UnitPoint, &_fonts) ; std::wstring text = L"Some text" ; gi->DrawString(text.c_str(), (INT)text.size(), currentFont, rectangle, &format, &brush) ;
I was wrong. If you have a font that includes Japanese Characters it will display correctly in Windows XP even if East Asian language Pack is not installed. If you have the East Asian Language Pack installed and if your font doesn't support Japanese characters, Windows will pick from between one of two fonts that it thinks matches your font the closest. This caused me to think that the fonts I was using included Japanese characters since it would change the way the characters were drawn when I switched between my font and the system font. Microsoft has a free to install Japanese font called Meiryo Collection Version 5.00. Also here is a page listing more Japanese fonts , The only problem with the fonts listed is the licensing is not clear.
629,433
629,448
How to initialize nested structures in C++?
I have created a couple of different structures in a program. I now have a structure with nested structures however I cannot work out how to initialize them correctly. The structures are listed below. /***POINT STRUCTURE***/ struct Point{ float x; //x coord of point float y; //y coord of point }; /***Bounding Box STRUCTURE***/ struct BoundingBox{ Point ymax, ymin, xmax, xmin; }; /***PLAYER STRUCTURE***/ struct Player{ vector<float> x; //players xcoords vector<float> y; //players ycoords BoundingBox box; float red,green,blue; //red, green, blue colour values float r_leg, l_leg; //velocity of players right and left legs int poly[3]; //number of points per polygon (3 polygons) bool up,down; }; I then attempt to intialse a newly created Player struct called player. //Creates player, usings vectors copy and iterator constructors Player player = { vector<float>(xcords,xcords + (sizeof(xcords) / sizeof(float)) ), //xcords of player vector<float>(ycords,ycords + (sizeof(ycords) / sizeof(float)) ), //ycoords of playe box.ymax = 5; //create bounding box box.ymin = 1; box.xmax = 5; box.xmin = 1; 1,1,1, //red, green, blue 0.0f,0.0f, //r_leg,l_leg {4,4,4}, //number points per polygon true,false}; //up, down This causes several different errors, concerning box. Stating the box has no clear identifier and missing struct or syntax before '.'. I then tried just to create a Player struct and initialise it's members as follows: Player bob; bob.r_leg = 1; But this causes more errors, as the compiler thinks bob has no identifier or is missing some syntax. I googled the problem but I did not find any articles showing me how to initalise many different members of nested structures within the (parent) structure. Any help on this subject would be greatly appreciated :-) !!!
You initialize it normally with { ... }: Player player = { vector<float>(xcords,xcords + (sizeof(xcords) / sizeof(float)) ), vector<float>(ycords,ycords + (sizeof(ycords) / sizeof(float)) ), 5, 1, 5, 1, 5, 1, 5, 1, 1.0f,1.0f,1.0f, //red, green, blue 0.0f,0.0f, //r_leg,l_leg {4,4,4}, //number points per polygon true,false }; Now, that is using "brace elision". Some compilers warn for that, even though it is completely standard, because it could confuse readers. Better you add braces, so it becomes clear what is initialized where: Player player = { vector<float>(xcords,xcords + (sizeof(xcords) / sizeof(float)) ), vector<float>(ycords,ycords + (sizeof(ycords) / sizeof(float)) ), { { 5, 1 }, { 5, 1 }, { 5, 1 }, { 5, 1 } }, 1.0f, 1.0f, 1.0f, //red, green, blue 0.0f, 0.0f, //r_leg,l_leg { 4, 4, 4 }, //number points per polygon true, false }; If you only want to initialize the x member of the points, you can do so by omitting the other initializer. Remaining elements in aggregates (arrays, structs) will be value initialized to the "right" values - so, a NULL for pointers, a false for bool, zero for ints and so on, and using the constructor for user defined types, roughly. The row initializing the points looks like this then { { 5 }, { 5 }, { 5 }, { 5 } }, Now you could see the danger of using brace elision. If you add some member to your struct, all the initializers are "shifted apart" their actual elements they should initialize, and they could hit other elements accidentally. So you better always use braces where appropriate. Consider using constructors though. I've just completed your code showing how you would do it using brace enclosed initializers.
629,559
629,743
A weird memory leak problem
I use an ActiveX control which is just a HTTP handler. It sends out an HTTP request, gets the response and fires an event to the user. When the user is not requesting the ActiveX control is pretty much dormant. It just waits for a user request to send another HTTP request. As long as the window in which the OCX resides does not change (losing focus, getting focus, etc) the memory stays calm. For each of the above said operations I lose approx 400 bytes. Where should I look for a possible leak?
Assuming that the HTTP string is passed down via BSTRs, you might be running into BSTR caching. To verify, you'll want to set the environment variable OANOCACHE to 1 or call OaSetNoCache() directly. The environment variable should be easier to test with.
629,741
630,104
How to initialize a IMimeMessage object from IStream
Given an empty MimeMessage created with e.g. MimeOleCreateMessage function, how can I initialize it from an IStream / data buffer, which contains the complete message text?
If I'm not wrong IMimeMessage returned by MimeOleCreateMessage supports IPersistStream stream then you have Load & Save methods.
629,894
629,978
Function-Level Linking (/Gy switch in VC++) - What is it good for?
What is there to gain from the use of this switch in a large VS solution (200 VC projects)? From what I understand this mainly affects the size of the resulting binaries; but aside from smaller binaries, could FLL also help in reducing dependencies between projects? How does FLL usually affect build times? I'd also appreciate an educated explanation on FLL in VC. MSDN's explanation is pretty brief.
Since you linked MSDN's explanation, you know that /Gy ensures that all functions are packaged in their own COMDAT. The main advantage of this is that if you have identical functions the linker can collapse them all down into one actual piece of code ("COMDAT folding"). This can have very large impacts when you have many identical functions, which is often the case when you write modern C++ that is heavy on templates. Aside from the smaller size of the resulting executable due to COMDAT folding and elimination of unreferenced COMDATs, there's no other effect of /Gy. To be specific, it doesn't help in reducing interproject dependencies. The cost is a slight increase in compilation time (similar to other optimizer flags). Usually not something you'll notice.
629,961
850,464
How can I set ccshared=-fPIC while executing ./configure?
I am trying to build Python 2.6 for QGIS on RHEL 5. During the making of QGIS I get the following error: Linking CXX shared library libqgispython.so /usr/bin/ld: /usr/local/lib/python2.6/config/libpython2.6.a(abstract.o): relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC /usr/local/lib/python2.6/config/libpython2.6.a: could not read symbols: Bad value collect2: ld returned 1 exit status make[2]: *** [src/python/libqgispython.so.1.0] Error 1 make[1]: *** [src/python/CMakeFiles/qgispython.dir/all] Error 2 make: *** [all] Error 2 What I figure out from this error is that I need to build Python 2.6 with some flag, -fPIC. OK, so I found it in the configure.in file but it checks several conditions and on the basis of those conditions it assigns -fPIC to the CCSHARED flag. What I did was that after all conditions were checked I added the following line to deliberately use CCSHARED as -fPIC. CCSHARED="-fPIC"; But it did not work.. How to specify while configuring that I want to set CCSHARED as -fPIC?
Run configure with --enable-shared. Then -fPIC will be included as part of the shared flags.
630,432
630,454
Where can I find a ZwCreateFile example for C++?
I am looking for an example to read an already opened COM port, the only thing that I have found is an application called PORTMON that refers to a method called ZwCreateFile.
codeproject.com - is a nice site for looking examples. http://www.codeproject.com/KB/system/chaiyasit_t.aspx edit: msdn have information too http://msdn.microsoft.com/en-us/library/aa363424.aspx
630,920
630,994
Store pointers to member function in the map
I'd like to map string to an instance member functions, and store each mapping in the map. What is the clean way of doing something like that? class MyClass { //........ virtual double GetX(); virtual double GetSomethingElse(); virtual double GetT(); virtual double GetRR(); //........ }; class Processor { private: typedef double (MyClass::*MemFuncGetter)(); static map<std::string, MemFuncGetter> descrToFuncMap; public: static void Initialize(); void Process(Myclass m, string); }; void Processor::Initialize() { descrToFuncMap["X"]=&MyClass::GetX; descrToFuncMap["SomethingElse"]=&MyClass::GetSomethingElse; descrToFuncMap["RR"]=&MyClass::GetRR; descrToFuncMap["T"]=&MyClass::GetT; }; void Processor::Process(MyClass ms, const std::string& key) { map<std::string, Getter>::iterator found=descrToFuncMap.find(key); if(found!=descrToFuncMap.end()) { MemFuncGetter memFunc=found->second; double dResult=(ms).*memFunc(); std::cout<<"Command="<<key<<", and result="<<result<<std::end; } } let me know if you see a problem with this approach and what are common idioms for that? Perhaps, I should use if-else-if statement chain, given that I have a limited number of member functions, instead of a confusing map of func pointers BTW, I found some of the useful info here in the c++-faq-lite
Looks fine to me, but for the fact that descrToFuncMap needs to be declared static if you intend to initialise it from inside the static function Initialize(). If you want to make sure that Initialize() gets called, and gets called just once, you can use the Singleton pattern. Basically, if you aren't doing multithreading, that just means wrapping descrToFuncMap inside its own class (called say FuncMap) with a private constructor that calls Initialize(). Then you add a static local variable of type FuncMap to Processor::Process() -- because the variable is static, it persists and is only initialised once. Example code (I now realise that friend isn't really necessary here): class Processor { private: typedef double (MyClass::*MemFuncGetter)(); class FuncMap { public: FuncMap() { descrToFuncMap["X"]=&MyClass::GetX; descrToFuncMap["SomethingElse"]=&MyClass::GetSomethingElse; descrToFuncMap["RR"]=&MyClass::GetRR; descrToFuncMap["T"]=&MyClass::GetT; } // Of course you could encapsulate this, but its hardly worth // the bother since the whole class is private anyway. map<std::string, MemFuncGetter> descrToFuncMap; }; public: void Process(Myclass m, string); }; void Processor::Process(MyClass ms, const std::string& key) { static FuncMap fm; // Only gets initialised on first call map<std::string, Getter>::iterator found=fm.descrToFuncMap.find(key); if(found!=fm.descrToFuncMap.end()) { MemFuncGetter memFunc=found->second; double dResult=(ms).*memFunc(); std::cout<<"Command="<<key<<", and result="<<result<<std::end; } } This is not the "true" Singleton pattern as different functions could create their own, separate instances of FuncMap, but it's enough for what you need. For "true" Singleton, you would declare FuncMap's constructor private and add a static method, say getInstance(), which defined the one-and-only instance as a static variable and returned a reference to that. Processor::Process() would then use this with FuncMap& fm = FuncMap::getInstance();
630,950
630,960
Pure virtual destructor in C++
Is it wrong to write: class A { public: virtual ~A() = 0; }; for an abstract base class? At least that compiles in MSVC... Will it crash at run time?
Yes. You also need to implement the destructor: class A { public: virtual ~A() = 0; }; inline A::~A() { } should suffice. If you derive anything from A and then try to delete or destroy it, A's destructor will eventually be called. Since it is pure and doesn't have an implementation, undefined behavior will ensue. On one popular platform, that will invoke the purecall handler and crash. Edit: fixing the declaration to be more conformant, compiled with http://www.comeaucomputing.com/tryitout/
631,145
631,177
Why param needs two arguments in following case:
I am sort of confused by this: istream_iterator<string> ii(is); istream_iterator<string> eos; vector<string> param (ii, eos);
One for start and one for end RANDOM DATA BEGIN ITERATOR USEFUL DATA END ITERATOR RANDOM DATA Without "eos", how would the vector know when it has reached the end?
631,201
631,287
Why is a second cin.ignore() necessary?
I've noticed that whenever I write a program that uses std::cin that if I want the user to press Enter to end the program, I have to write std::cin.ignore() twice to obtain the desired behavior. For example: #include <iostream> int main(void) { int val = 0; std::cout << "Enter an integer: "; std::cin >> val; std::cout << "Please press Enter to continue..." << std::endl; std::cin.ignore(); std::cin.ignore(); // Why is this one needed? } I've also noticed that when I'm not using cin for actual input but rather just for the ignore() call at the end, I only need one.
Discl: I'm simplifying what really happens. The first serves to purge what the extraction operator (>>) hasn't consumed. The second waits for another \n. It is exactly the same when we do a std::getline after an extraction: a the_stream::ignore(std::numeric_limits<streamsize>::max(), '\n'); is required before the call to std::getline()
631,282
631,393
const pointer as a constructor argument
This is an odd one. Note this is cut down example code, and misses out destructors deliberately). template <class f, class g> class Ptr; class RealBase { }; template <class a, class b, class c = Ptr<a,b> > class Base : public RealBase { public: Base(){}; }; template <class d, class e> class Derived : public Base <d,e> { public: Derived(){}; void DerivedMethod(){}; }; typedef Derived<double,double> D_Derived; template <class f, class g> class Ptr { public: Ptr(){}; Ptr(Base<f,g,Ptr<f,g> >* a){in = a;}; Base<f,g,Ptr<f,g> >* operator->() { return in; }; Base<f,g,Ptr<f,g> >& operator*() { return *in; }; private: Base<f,g,Ptr<f,g> >* in; }; I'm using the Ptr class from this example in a vector, as a pointer to a Derived class. As we can see, the Ptr takes a Base<>* as it's constructor argument. Unfortunately I need a constructor that takes a const Base<>*, and I cannot simply do this: Ptr(const Base<>* a) { in = const_cast<Base<>*>(a)}; Any ideas how I can make this class accept a const Base<>* as it's constructor? Edit: Ok, turns out I can fix this by making changes to unrelated code, so it's a bit of a non-problem now =] Took me about a day to fix it though =[
I think you need to define a separate class to wrap pointers to const, since not only the arguments of the constructor, but also the return types of the operators should be changed to const versions. If you make the ConstPtr a friend of Ptr, this should work out quite nicely: template<...> class ConstPtr { const Base<...> *in; ConstPtr(Base<...>* a) { in = a; } ConstPtr(const Base<...>* a) { in = a; } ConstPtr(const Ptr<...> &a) { in = a.in; } ... }; To construct wrappers from raw pointers you could add an overloaded function, more or less like this: template<..., class P> P make_ptr(Base<...> *t); template<...> Ptr<...> make_ptr< ..., Ptr<...> >(Base<...> *t) { return Ptr(t); } template<...> ConstPtr<...> make_ptr< ..., ConstPtr<...> >(const Base<...> *t) { return ConstPtr(t) }
631,380
647,113
Is it wise to provide access to weak_ptr in a library interface?
I have written a library that exposes references to several related object types. All of these objects have their lifetimes managed by the library internally via boost::shared_ptr A user of the library would also be able to know, by nature of the library, the lifetimes of any of the exposed objects. So they could store pointers or keep references to these objects. It would be reasonable for them to do this and know when those objects are no longer valid. But I feel guilty forcing my users to be reasonable. Is it acceptable to have a library expose weak_ptr's to its objects? Have other libraries done this? I have profiled this library's usage in apps and have found it to be too mission-critical to expose weak_ptr exclusively. Would it be wiser to have matching API functions expose either a reference or a weak_ptr or to make any object capable of exposing a weak_ptr to itself?
If the smart_ptrs are already directly accessible to the library's users, then they've already got access to the weak_ptrs, simply via the corresponding weak_ptr's constructor. But if the smart_ptrs are all internal to the library, that's a different story. In that case, I'd recommend letting each object pass out weak_ptrs to itself, in addition to any other access your library offers. That gives the users the most flexibility: if they need a weak_ptr, they've got immediate access to it; if they need a shared_ptr, they can easily get it; and if they just need access to the object itself, they can ignore the smart pointers entirely. Of course, I don't know what your library does or how it's used or designed. That might change my recommendation.
631,506
631,532
Does Pre and post increment/decrement operators in C++ have same performance in a loop?
Consider following two examples. class ClassOne { //class definition is here }; std::vector< ClassOne > myListOfObjects; std::vector< ClassOne >::const_iterator iter = myListOfObjects.begin(); Example 1: for( ; iter < myListOfObjects.end(); **++iter**) { //some operations } OR Example 2: for( ; iter < myListOfObjects.end(); **iter++**) { //some operations } Which one is faster ? ++iter or iter++ in the context of loop. Reason Fro Closure: Copied from Brian's Post (to make the question more succinct). You could also try one of these similar questions: here or here or here or here.
As noted in this answer, pre is faster. They are only the same when you are dealing with primitives (int, char, etc.). In this case, they are calling overloaded operators.
631,633
631,767
returning a 'pointer' which is required to be held by a smart pointer
I have a project which I would like to make more use of smart pointers. Overall, I have been successful in this goal. However, I've come across one things which I'm not sure what the "best practice" is. Basically I would like to return a "pointer" from a function, but require that the user hold it in a smart pointer. Not only that, I don't want to mandate a particular smart pointer (shared vs. scoped). The problem is mostly that there doesn't seem be to a proper way to upgrade a scoped_ptr to a shared_ptr (that would be the ideal solution i think). I understand why they didn't do this, as it would allow transferring of ownership which can lead to some issues like those std::auto_ptr has. However, transferring of ownership seems like a good idea for this case. So my idea is like this: // contrived example of factory pattern std::auto_ptr<A> func() { return std::auto_ptr<A>(new A); } This works "ok" since both scoped_ptr and shared_ptr have constructors which take ownership from a std::auto_ptr. So my question is, is this good practice? Is there a better solution? The only real alternative I've been able to come up with is using a template template as the return value like this: // similar to above example template <template <typename> class P> P<A> func() { return P<A>(new A); } which actually could work well except that I think it would need some work to get it to work with a scoped_ptr too. Thoughts?
Using std::auto_ptr is the good practice, in fact such example was suggested by Bjarne Stroustrup. The move semantics of auto_ptr gives you right tools to deal with it. For example: auto_ptr<Foo> make_foo() { return auto_ptr<Foo>(new Foo); } Foo *raw_pointer=make_foo().release(); shared_ptr<Foo> shared_pointer=make_foo(); auto_ptr<Foo> auto_pointer=make_foo(); If you return shared_ptr you can't fallback to normal pointer, with auto_ptr you can. You can allways upgrade auto_ptr to shared but not other direction. Another important point, shared_ptr uses atomic reference-counting, that is much slower that simple and yet fully efficient job that auto_ptr does. P.S.: scoped_ptr is just version of auto_ptr for poors --- it is non-copyable and does not have default constuctor. It is more like "less confusing" version of auto_ptr, in comparison to shared_ptr it is not in tr1. Generally there no much advantages of using scoped_ptr over auto_ptr
631,661
631,699
snprintf Format String security vulnerability issue
We have a Coverity bug for this line of code: snprintf( tempStr, size, testStrings[testID], A2DtoV(testResults[testID].value), A2DtoV(testResults[testID].min),A2DtoV(testResults[testID].max)); The error says: non_const_printf_format_string: "format string is not a string literal, potential security vulnerability if user controlled" I changed testStrings to a const, but that didn't do anything: static const char *testStrings[] = {"1", ... etc}; Any ideas as to what this error is really saying?
Your code is fine. The issue is that if you pass a string that is user controlled as a printf format string, security bugs can arise. For instance, printf(userName); Where userName is supplied by the user, a user can pass "%s", and get your function to start accessing data at a random address on the stack, which could result in a crash. printf will try to pop additional parameters off the stack, resulting in a stack corruption. Denial of service attack like this is probably the best case, information can be disclosed by getting printf to dump out values on the stack and there are even ways to get printf style functions to modify the return address on the stack. Since your strings are not user controlled, it is safe to ignore this message. The typical fix is to replace the printf example I gave with printf("%s", userName);, which would not appear to help in your case because the const strings appear to contain format strings. Wikipedia has more on format string vulnerabilities here: http://en.wikipedia.org/wiki/Format_string_vulnerabilities
631,664
631,728
Accessing Environment Variables In C++
I'd like to have access to the $HOME environment variable in a C++ program that I'm writing. If I were writing code in C, I'd just use the getenv() function, but I was wondering if there was a better way to do it. Here's the code that I have so far: std::string get_env_var( std::string const & key ) { char * val; val = getenv( key.c_str() ); std::string retval = ""; if (val != NULL) { retval = val; } return retval; } Should I use getenv() to access environment variables in C++? Are there any problems that I'm likely to run into that I can avoid with a little bit of knowledge?
There is nothing wrong with using getenv() in C++. It is defined by stdlib.h, or if you prefer the standard library implementation, you can include cstdlib and access the function via the std:: namespace (i.e., std::getenv()). Absolutely nothing wrong with this. In fact, if you are concerned about portability, either of these two versions is preferred. If you are not concerned about portability and you are using managed C++, you can use the .NET equivalent - System::Environment::GetEnvironmentVariable(). If you want the non-.NET equivalent for Windows, you can simply use the GetEnvironmentVariable() Win32 function.
631,770
631,824
C++ select first not null element
[question update according to updated requirements] I've implemented following function which should return either first not null element or throw an exception. Also could you invent more classic and shorter name like 'max', 'min', 'pair'? template <typename T> T select_first_not_empty( const T& a, const T&b ) { static T null = T(); if ( a == null && b == null ) throw std::runtime_error( "null" ); return a != null ? a : b; } int main() { const int a1 = 2; const int b1 = 0; const int* a2 = 0; const int* b2 = new int(5); const std::string a3 = ""; const std::string b3 = ""; std::cout << select_first_not_empty( a1, b1 ) << std::endl; std::cout << select_first_not_empty( a2, b2 ) << std::endl; std::cout << select_first_not_empty( a3, b3 ) << std::endl; return 0; }
you can try do next template < typename T > T get_valuable( const T& firstValue, const T& alternateValue, const T& zerroValue = T() ) { return firstValue != zerroValue ? firstValue : alternateValue; } // usage char *str = "Something"; // sometimes can be NULL std::string str2 ( get_valuable( str, "" ) ); // your function template <typename T> T select_first_not_empty( const T& a, const T& b, const T& zerroValue = T() ) { const T result = get_valuable( a, b, zerroValue ); if ( result == zerroValue ) { throw std::runtime_error( "null" ); } return result; }
631,783
631,791
What is the use of having destructor as private?
What is the use of having destructor as private?
Basically, any time you want some other class to be responsible for the life cycle of your class' objects, or you have reason to prevent the destruction of an object, you can make the destructor private. For instance, if you're doing some sort of reference counting thing, you can have the object (or manager that has been "friend"ed) responsible for counting the number of references to itself and delete it when the number hits zero. A private dtor would prevent anybody else from deleting it when there were still references to it. For another instance, what if you have an object that has a manager (or itself) that may destroy it or may decline to destroy it depending on other conditions in the program, such as a database connection being open or a file being written. You could have a "request_delete" method in the class or the manager that will check that condition and it will either delete or decline, and return a status telling you what it did. That's far more flexible that just calling "delete".
631,808
631,861
rules for inclusion in header files when using type in typedef
if I create typedef double (MyClass::*MemFuncGetter)(); in a header file, do I need to include "MyClass.h" or would forward declaring suffice? Header file: #ifndef _TEST_ #define _TEST_ #include "MyClass.h" //do I need this? //or I can just say class MyClass; typedef double (MyClass::*MemFuncGetter)(); #endif What are the linkage rules here?
You are fine with just the forward declaration of the class: #ifndef _TEST_ #define _TEST_ class MyClass; typedef double (MyClass::*MemFuncGetter)(); #endif But note that by not including the whole class, the compiler has to do extra work to handle the cases when MyClass is a multiple-virtual inheritance mess, since it doesn't know. In some cases this can mean that each function pointer actually takes up to 20 bytes of memory. Whereas if you had defined the whole, each function pointer would only take 4. (Of course the sizes are all compiler-dependant).
631,952
631,966
Forward declare pointers-to-structs in C++
I am using a 3rd party library that has a declaration like this: typedef struct {} __INTERNAL_DATA, *HandleType; And I'd like to create a class that takes a HandleType in the constructor: class Foo { Foo(HandleType h); } without including the header that defines HandleType. Normally, I'd just forward-declare such a type, but I can't figure out the syntax for this. I really want to say something like: struct *HandleType; But that says "Expected identifier before *" in GCC. The only solution I can see is to write my class like this: struct __INTERNAL_DATA; class Foo { Foo(__INTERNAL_DATA *h); } But this relies on internal details of the library. That is to say, it uses the name __INTERNAL_DATA, which is an implementation detail. It seems like it should be possible to forward-declare HandleType (part of the public API) without using __INTERNAL_DATA (part of the implementation of the library.) Anyone know how? EDIT: Added more detail about what I'm looking for.
Update: I am using it in the implementation .cpp of Foo, but I want to avoid including it in my header .h for Foo. Maybe I'm just being too pedantic? :) Yes you are :) Go ahead with forward declaration. If HandleType is part of the interface there must be a header declaring that. Use that header. Your problem is still a vague one. You are trying to protect against something you cannot. You can add the following line to your client library: typedef struct INTERNAL_DATA *HandleType; but, if the name/structure changes you may be in for some casting nastiness. Try templates: template <class T> class Foo { Foo(T h); }; Forward declaration is fine. If you are going to use pointers or references you only need a class (__INTERNAL_DATA) declaration in scope. However, if you are going to use a member function or an object you will need to include the header.
631,969
631,975
Creating C++ DLLs with Visual Studio
I am creating a simple C++ DLL project using Visual Studio 2008 Express Edition. I have a few classes inside a namespace, and a few non-static functions and constructors inside it are declared with __declspec(dllexport). All those functions are implemented. I also have an extern "C" BOOL APIENTRY DllMain function which simply returns TRUE. As I hit Debug(or Release), it successfully builds with no errors nor warnings. The output folder(either "Debug/" or "Release/") gets files such as "BuildLog.htm", one ".obj" file per source file, "vc90.pdb", "vc90.idb", "[DLLNAME].dll.embed.manifest", "[DLLNAME].dll.embed.manifest.res", "[DLLNAME].dll.intermediate.manifest" but... not the DLL itself. This is the first time I try to compile this project(so I never sucessfully compiled before) and I have little experience with C++/DLLs, although I do know standalone C++ and created Linux C shared objects before. What am I doing wrong? Is there any particular required file that I'm missing?
I'd look up a little higher in the directory structure (the one that the solution is in) and see if your Debug/Release folders (with the DLL) are there. I think the default is to put the actual DLLs in folders in the solution directory, not the project directory (I think the assumption is that you want all the DLLs that you build for a solution to go to the same place)
632,805
633,225
What's the cleanest way to walk and unwalk a std::vector using iterators?
I have a situation where I'm marching through a vector, doing things: std::vector<T>::iterator iter = my_list.begin(); for ( ; iter != my_list.end(); ++iter ) { if ( iter->doStuff() ) // returns true if successful, false o/w { // Keep going... } else { for ( ; iter != m_list.begin(); --iter ) // ...This won't work... { iter->undoStuff(); } } } Under normal conditions - assuming everything goes well - I march all the way to my_list.end() and end the loop successfully. However, if something goes wrong while I'm doing stuff, I want to be able to undo everything - basically retrace my steps back to the very beginning of the vector, undoing everything one at a time in reverse order. My problem is that when I get to my_list.begin() - as shown in the nested for loop - I'm really not done yet because I still need to call undoStuff() on my first element in the list. Now, I could just make the final call outside of the loop, but this seems a little unclean. The way I see it, I'm only done when I get to my_list.rend(). However, I can't compare a std::vector::iterator to a std::vector::reverse_iterator. Given what I'm trying to do, what's the best choice of iterator-type / loop combination?
While using reverse iterators via rbegin() and rend() works nicely, unfortunately I find that converting between reverse and non-reverse iterarotrs tends to be quite confusing. I can never remember without having to go through a logic-puzzle exercise whether I need to increment or decrement before or after the conversion. As a result I generally avoid the conversion. Here's the way I'd probably code your error handling loop. Note that I'd think that you wouldn't have to call undoStuff() for the iterator that failed - after all, doStuff() said it didn't succeed. // handle the situation where `doStuff() failed... // presumably you don't need to `undoStuff()` for the iterator that failed // if you do, I'd just add it right here before the loop: // // iter->undoStuff(); while (iter != m_list.begin()) { --iter; iter->undoStuff(); }
632,896
632,930
What is the best way for distributed processes to communicate asynchronously?
I'm developing an application in which distributed components talk to one another over a network, in an asynchronous, pub/sub kind of way. For this, I like the idea of sending XML over sockets - it's asynchronous, I don't need a server of any kind, and it can work locally or over a network. I would have to roll my own pub/sub mechanism, which probably won't be too onerous - I could use the IP address as the id of the subscriber. The implementation language will be C++. I've used this method before with good results. But, I wonder if there is a better way? Any advice welcome. Edit: I haven't made a decision yet, but I'm interested in cparcode's comment on protobuf: "I never understood the popularity of using XML for network comms. Any way, I realize that the protocol is only part of your problem but on that subject, there's Google's protobuf too: http://code.google.com/p/protobuf/ – caparcode (Mar 11 at 1:01)"
Instead of using XML it might be best to use an existing message passing framework. Have a look at libt2n or d-bus But it you have used your own socket implementation in the past with good results i don't see a reason why you should change. If it ain't broke don't fix it :)
632,919
633,150
How to make an icon button in C++
I know how to draw a button in C++ but how would i make an icon on it can someone post source or give reference please? by SendMessage() or if not that way just please paste Please need easier anwsers without so many files im new a bit
If you use MFC then I would recommend you to use the following CButton method SetIcon: CButton myButton; // Create an icon button. myButton.Create(_T("My button"), WS_CHILD|WS_VISIBLE|BS_ICON, CRect(10,10,60,50), pParentWnd, 1); // Set the icon of the button to be the system question mark icon. myButton.SetIcon( ::LoadIcon(NULL, IDI_QUESTION) ); This works very well.
633,549
633,563
How to copy the contents of std::vector to c-style static array,safely?
I need to manipulate data in fixed array involving mid insertion. Rather than using memcpy,etc. I want to use vector. I have problem when I want to copy the vector elements back to the c-style array. Here's the code: void tryvector() { using namespace std; const int MAX_SIZE=16; BYTE myarr[MAX_SIZE]={0xb0,0x45,0x47,0xba,0x11,0x12, 0x4e}; vector<BYTE> myvec (myarr, myarr+MAX_SIZE); vector<BYTE>::iterator it; printf("myarr pre :"); for(int i=0;i<MAX_SIZE;++i){ printf("%02x ", myarr[i]) ; } printf("\nmyvec pre :") for(it=myvec.begin(); it<myvec.end();++it){ cout<<hex<<static_cast<int>(*it)<<" "; } it = myvec.begin()+ 3; myvec.insert(it,0x5f); printf("\nmyvec post:"); for(it=myvec.begin(); it<myvec.end();++it){ cout<<hex<<static_cast<int>(*it)<<" "; } copy(myvec.begin(), myvec.end(), myarr); //??? printf("\nmyarr post:"); for(int i=0;i<MAX_SIZE;++i){ printf("%02x ", myarr[i]) ; } } I'm using vs 2005. Here's the warning: warning C4996: 'std::_Copy_opt' was declared deprecated 1> c:\program files\microsoft visual studio 8\vc\include\xutility(2270) : see declaration of 'std::_Copy_opt' 1> Message: 'You have used a std:: construct that is not safe. See documentation on how to use the Safe Standard C++ Library' 1> c:\documents and settings\mhd\my documents\tesvector.cpp(50) : see reference to function template instantiation '_OutIt std::copy<std::_Vector_iterator<_Ty,_Alloc>,BYTE*>(_InIt,_InIt,_OutIt)' being compiled 1> with 1> [ 1> _OutIt=BYTE *, 1> _Ty=BYTE, 1> _Alloc=std::allocator<BYTE>, 1> _InIt=std::_Vector_iterator<BYTE,std::allocator<BYTE>> 1> ] When I run it , I got the following run-time error: Run-Time Check Failure #2 - Stack around the variable 'myarr' was corrupted. Please note that I use vector instead list or deque because the 'middle insertion' like the code above is juat a particular problem. It will happen less than 'inserting at the end' and 'random access of element'. Any solution ? Any answer that resembles:"You use c++, drop the c style array implementation. Use only vector for all array implementation" is not really helpful. Thanks.
The problem is that you're adding things to the vector so it ends up with more elements than were in the myarr array that you initialized it with. If you want to copy the vector back into the array, you'll need to size it down: myvec.resize( MAX_SIZE); Or you could limit the number of elements you copy back: copy( myvec.begin(), myvec.begin()+MAX_SIZE, myarr); If you want the myarr array to contain all the elements, then it needs to be larger than MAX_SIZE, and you've found out why people suggest to use vector rather than raw arrays (vectors know how to grow, arrays do not). Note that while you don't want 'Any answer that resembles:"You use c++, drop the c style array implementation. Use only vector for all array implementation"', you can often get away with using a vector and passing &myvec[0] to routines that expect a raw array. vector is required to store its elements contiguously just like a raw array for just this reason. Since you're getting the 'unsafe operation' warning, you're using Microsoft's compiler. To fix the problem safely, you're supposed to use the checked_copy algorithm instead of copy. As Evgeny Lazin indicates, you can create a checked iterator for your array to pass to the checked_copy algorithm. Other options to make the copy safe that do not require Microsoft extensions would be to wrap the array in a class (possibly templated) that keeps track of the array size and provides methods to copy data into the array in a safe manner. Something like STLSoft's array_proxy template or Boost's boost::array might help.
633,634
633,643
Declaring class objects in a header file
I seem to be snagging on a fundamental but I can't find the solution anywhere. Anywho, will go ahead and explain. I have a program consisting of three files; main.ccp, add.h, add.cpp. I declare the class 'SA' in add.h and have all my functions defined in add.cpp. additional.h class SA { ... public int x; } Obj1, Obj2; main.ccp #include "additional.h" int main() { Obj1.x = 5; ... } This gives me a link error on compiling: error LNK2005: "class SA Obj1" (?Obj1@@3VSA@@A) already defined in main.obj The only deffinition of the object occurs in add.h, and nowhere else. The program compiles just fine if I declare the objects in the main and not the header: main.ccp #include "additional.h" int main() { SA Obj1; Obj1.x = 5; ... } The issue is that I want to use the objects primarily within add.cpp, but still need to initialise several public values through main.cpp. Any words of wisdom?
Define Obj1 and Obj2 in your .cpp instead of at .h add.h class SA { ... public int x; }; main.cpp #include "additional.h" SA Obj1, Obj2; int main() { Obj1.x = 5; ... } If you want to declare Obj1 and Obj2 in your .h file, add extern in the .h file like so: extern SA Obj1, Obj2; but you should declare the objects in a .cpp file in your project: main.cpp SA Obj1, Obj2; The reason for this is that everytime you include the .h file, you are declaring Obj1 and Obj2. So if you include the .h file two times, you will create two instance of Obj1 and Obj2. By adding the keyword extern, you are telling the compiler that you have already decalred the two variables somewhere in your project (preferably, in a .cpp file).
633,851
633,870
Shouldn't Gdiplus::Image::GetWidth() and a bunch of other getters be "const"?
Why aren't they const? I believe that's flawed API design. Or am I missing something? UINT GetWidth(); UINT GetHeight(); ... vs. UINT GetWidth() const; UINT GetHeight() const; ...
Hard to say. I'd agree, but perhaps there is something in the implementation that prevents them from being const, and that they didn't want to add overhead to hide. Nowdays we have the mutable keyword, but I think that is younger than this API. Or maybe the designers of the API belong to the (sometimes shockingly large, imo) bunch of C++ developers who are hostile towards the const keyword, feeling that only makes things harder to use. I'm no Windows historian, so I can't tell you. :)
633,881
633,905
Algorithm for Counting Sorted Strings (Homebrew "uniq -c")
I have the following sorted data: AAA AAA TCG TTT TTT TTT I want to count the occurrences of each String: AAA 2 TCG 1 TTT 3 I know I can do that using uniq -c, but here I need to do extra processing on the overall C++ code that I have. I am stuck with this construct (modified according to 'pgras' suggestion): #include <iostream> #include <vector> #include <fstream> #include <sstream> using namespace std; int main ( int arg_count, char *arg_vec[] ) { if (arg_count !=2 ) { cerr << "expected one argument" << endl; return EXIT_FAILURE; } string line; ifstream myfile (arg_vec[1]); if (myfile.is_open()) { int count; string lastTag = ""; while (getline(myfile,line) ) { stringstream ss(line); string Tag; ss >> Tag; // read first column //cout << Tag << endl; if (Tag != lastTag) { lastTag = Tag; count = 0; } else { count++; } cout << lastTag << " " << count << endl; } cout << lastTag << " " << count << endl; myfile.close(); } else {cout << "Unable to open file";} return 0; } It prints this wrong result: AAA 0 AAA 1 TCT 0 TTT 0 TTT 1 TTT 2 TTT 2
You have to reset counter when tag is different from lastTag, and increment if it's the same... When the tag is different you can handle the previous tag with it's associated count value (before you reset count)...
634,087
646,510
std::copy to std::cout for std::pair
I have next code: #include <iostream> #include <algorithm> #include <map> #include <iterator> //namespace std //{ std::ostream& operator << ( std::ostream& out, const std::pair< size_t, size_t >& rhs ) { out << rhs.first << ", " << rhs.second; return out; } //} int main() { std::map < size_t, size_t > some_map; // fill some_map with random values for ( size_t i = 0; i < 10; ++i ) { some_map[ rand() % 10 ] = rand() % 100; } // now I want to output this map std::copy( some_map.begin(), some_map.end(), std::ostream_iterator< std::pair< size_t, size_t > >( std::cout, "\n" ) ); return 0; } In this code I just want copy map to output stream. For do this I need define operator <<(..) - OK. But according names finding rules compiler can't find my operator<<(). Because std::cout, std::pair and std::copy which called my operator<< - all from namespace std. Quick solution - add my oerator<< to std namespace - but it is ugly, imho. What solutions or workaround for this problem do you know?
I've founded one new elegant way to solve this problem. I've got many interest ideas when read answers: wrap iterator, for transform std::pair to std::string; wrap std::pair, for have a chance to overload operator<<(...); use usual std::for_each with printing functor; use std::for_each with boost::labda - looks nice, except accessing to std::pair< >::first and std::pair< >::second members; I think I will use all of this ideas in future for solve different other problems. But for this case I've understaded that I can formulate my bproblem as "transform map's data to strings and write them to output stream" instead "copy map's data to ouput stream". My solution looks like: namespace { std::string toString( const std::pair< size_t, size_t >& data) { std::ostringstream str; str << data.first << ", " << data.second; return str.str(); } } // namespace anonymous std::transform( some_map.begin(), some_map.end(), std::ostream_iterator< std::string >( std::cout, "\n" ), toString ); I think this method is most short and expressive than others.
634,404
634,480
Complete solution for writing Mac OS X application in C++
I am looking for alternatives for my current box and Mac OS X seems very appealing. My main area of interest is C++ programming. Currently I'm using Eclipse + CDT and g++ for creating my software; sometimes it is KDevelop. I know that primary IDE for Mac is Xcode and primary language is Objective-C. I would like to avoid learning Objective-C if at all possible. I've also heard/read that there are some issues in accessing Mac OS X APIs from C++. Hence my question: what is the complete solution for developing/debugging/testing C++ applications that access all aspects of hardware (UI, sound, video/accelerated video, etc.) for Mac OS X? Edit: how does Xcode compare to the Eclipse+CDT combo? If this comparison is at all possible...
If you want to use C++ instead of Objective-C, and still want to avoid an intermediate layer of libraries (such as QT), you can use Carbon. I would use XCode instead of Eclipse simply because Eclipse is way slower when dealing with hardcore C/C++ programming (compiling, debugging, testing). When I first started to program in Mac OS X, I was in the same page you are now. I thought it was better to stick to the language I knew (C++) and use an older library (Carbon). For some reason I don't remember now, I forced myself into Cocoa (Objective-C). Looking back, I think it was a good thing because: Objective-C is not fundamentally different to C++ Cocoa is better, faster and simpler than Carbon iPhone Dev is exclusively Cocoa (Carbon is not supported)
634,502
634,685
How can I extract frames from videos (using DirectShow)?
I have to extract the frames from any video file that can be played using the standard windows media player into separate images. Can you provide me some info on how to proceed, what documentation/books to read, etc? The language is C/C++. Also, don't recommend any solution which involves GPL code, the software I have to work on is proprietary.
I can recommend you the following excellent example on CodeProject. It shows you how to process frames from a camera source or an avi file.
634,662
634,705
Non-static const member, can't use default assignment operator
A program I'm expanding uses std::pair<> a lot. There is a point in my code at which the compiler throws a rather large: Non-static const member, 'const Ptr std::pair, const double*>::first' can't use default assignment operator I'm not really sure what this is referring to? Which methods are missing from the Ptr class? The original call that causes this problem is as follows: vector_of_connections.pushback(pair(Ptr<double,double>,WeightValue*)); Where it's putting an std::Pair<Ptr<double,double>, WeightValue*> onto a vector, where WeightValue* is a const variable from about 3 functions back, and the Ptr<double,double> is taken from an iterator that works over another vector. For future reference, Ptr<double,double> is a pointer to a Node object.
You have a case like this: struct sample { int const a; // const! sample(int a):a(a) { } }; Now, you use that in some context that requires sample to be assignable - possible in a container (like a map, vector or something else). This will fail, because the implicitly defined copy assignment operator does something along this line: // pseudo code, for illustration a = other.a; But a is const!. You have to make it non-const. It doesn't hurt because as long as you don't change it, it's still logically const :) You could fix the problem by introducing a suitable operator= too, making the compiler not define one implicitly. But that's bad because you will not be able to change your const member. Thus, having an operator=, but still not assignable! (because the copy and the assigned value are not identical!): struct sample { int const a; // const! sample(int a):a(a) { } // bad! sample & operator=(sample const&) { } }; However in your case, the apparent problem apparently lies within std::pair<A, B>. Remember that a std::map is sorted on the keys it contains. Because of that, you cannot change its keys, because that could easily render the state of a map invalid. Because of that, the following holds: typedef std::map<A, B> map; map::value_type <=> std::pair<A const, B> That is, it forbids changing its keys that it contains! So if you do *mymap.begin() = make_pair(anotherKey, anotherValue); The map throws an error at you, because in the pair of some value stored in the map, the ::first member has a const qualified type!
634,680
636,024
Converting indexed polygons to unindexed ones. Several problems have cropped up
Yet again I have some questions regarding polygon algorithms. I'll try to explain my problem: I am using a subset of a third party library called Geometric Tools(GT) to perform boolean operations on my polygons. To accomplish this I have to convert my internal polygon format to the format GT uses. Our internal polygon format consists of a vertex array, while the GT polygon consists of an indexed vertex array where each edge is represented by a pair of indices. Example of a square for clarification: Internal format: vertices[0] = Vertex2D(1,0) -> start vertices[1] = Vertex2D(1,1) vertices[2] = Vertex2D(0,1) vertices[3] = Vertex2D(0,0) vertices[4] = Vertex2D(1,0) -> end External format: vertices[0] = Vertex2D(1,0) vertices[1] = Vertex2D(1,1) vertices[2] = Vertex2D(0,1) vertices[3] = Vertex2D(0,0) edges[0] = std::pair<int,int>(0,1) edges[1] = std::pair<int,int>(1,2) edges[2] = std::pair<int,int>(2,3) edges[3] = std::pair<int,int>(3,0) //There is also a BSP tree of the polygon which I don't care to depict here. Now, I wrote an algorithm that works in most cases, but crashes and burns when two edges share the same starting vertex. Let me start by explaining how my current algorithm works. Make a std::map where the key is an integer representing the vertex index. The value represents where in the edge array there is an edge with the key-index as starting index. Mockup example: std::vector< std::pair< int, int > > edge_array; edge_array.push_back( std::pair< int, int >( 0, 1 ) ); edge_array.push_back( std::pair< int, int >( 2, 3 ) ); edge_array.push_back( std::pair< int, int >( 1, 2 ) ); edge_array.push_back( std::pair< int, int >( 3, 0 ) ); std::map< int, int > edge_starts; for ( int i = 0 ; i < edge_array.size(); ++i ) { edge_starts[ edge_array[i].first ] = i; } To jump from correct edge to correct edge i can now just do the following inside a while loop: while ( current_placed_index = first_index_in_polygon ) { int index_to_next_edge_to_be_traversed = edge_starts[ current_edge.second ]; } Inside this loop there is done some optimization, and vertex indices are added to an array. Each time a polygon is closed i find the first untraversed edge and start making another polygon. I keep on doing this until there are no more untraversed edges in the GTPolygon. So each GTPolygon can result in several Polygon(internal) objects. The flaw in this algorithm is evident when there are two edges sharing the same vertex as a starting vertex. Example: <1,2> <1,3> <1,5> When traversing my edges, how will i know which of these edges belongs to the polygon I am currently traversing? I could try traversing the edges BACKWARDS when such a duplicate situation occurs. The problem then would be the possibility of the traversation going back and forth infinitely if another duplicate is found while reversing. My question is, how can I solve this? Is it solvable at all? Can I use the BSP tree to solve this in some way? The amount of corner cases is a bit daunting. Any help is greatly appreciated as 5 months of work depends on this working. Edit: To clarify: I want to convert from the indexed representation of a polygon that Geometry Tools works with to our internal polygon format, which is just a series of connected vertices in a list.
You are effectively trying to find all cycles in an undirected graph where each cycle represents the edges of a unique polygon. This paper proposes a depth-first search (DFS) solution.
634,816
634,876
C++ Header files - put them in one directory or merged in a tree structure?
I have a substantial body of source code (OOFILE) which I'm finally putting up on Sourceforge. I need to decide if I should go with a monolithic include directory or keep the header files with the source tree. I want to make this decision before pushing to the svn repo on SourceForge. I expect a lot of people who use it after that move will keep a working copy checked out directly from SF so won't want to change their structure. The full source tree has about 262 files in 25 folders. There are a lot more classes than that suggests as due to conforming to 8.3 character names (yes it dates back to Win3.1) many classes are in one file. As I used to develop with ObjectMaster, that never bothered me but I will be splitting it up to conform to more recent trends to minimise the number of classes per file. From a quick skim of the class list, there are about 600 classes. OOFILE is a cross-platform product expected to be built on Mac, Windows and assorted Unix platforms. As it started life on Mac, with compilers that point to include trees rather than flat include dirs, headers were kept with the source. Later, mainly to keep some Visual Studio users happy, a build was reorganised with a single include directory. I'm trying to choose between those models. The entire OOFILE product covers quite a few domains: database front-end range of database backends simple 2D graphing engine for Mac and Windows simple character-mode report-writer for trivial html and text listing very rich banding report-writer with Mac and Windows Preview and Printing and cross-platform generation of text, RTF, HTML and XML reports forms integration engine for easy CRUD forms binding to the database, with implementations on PowerPlant and MFC cross-platform utility classes file and directory manipulation strings arrays XML and tag generation Many people only want to use it on a single platform and some of those code areas are pure legacy (eg: PowerPlant UI framework on classic Mac). It therefore seems people would appreciate not having headers from those unwanted areas dumped in their monolithic include directory. I started thinking about having an include directory split up into a few of the domains above and then realised that was sounding more like the original structure. In summary, the choices seem to be: Keep original model, all headers adjacent to source - max flexibility at cost of some complex includes in projects. one include directory with everything inside split includes by domain, so there may be about 6 directories for someone using the lot but a pure database user would probably have a single directory. From a Unix build aspect, the recommended structure has been 2. My situation is complicated by needing to keep Visual Studio and XCode users happy (sniff, CodeWarrior, how I doth miss thee!). Edit - the chosen solution: I went with four subdirectories in include. I started trying to divide them up further by platform but it just got very noisy very quickly.
Personally I would go with 2, or 3 if really pushed. But whichever you choose, please make it crystal clear in the build instructions how to set up the include paths. Nothing dooms an open source project more than it being really difficult to build - developers want a quick out-of-the-box experience and if it involves faffing around with many undocumented environment variables (or whatever) most will simply go away.
634,951
634,957
C++ OpenSource project for beginner programmer?
I`m a beginner C++ programmer. And I want to pursue my career in system- and driver-programming. Can you suggest me an opensource projects to I improve my skills in low-level development? I am looking for a project with the following characteristic: - on C\C++ language based - a small project with a small amount of code, yet - UNIX-based systems designed Do you know that something like this?
Check the google summer of code projects page! These are all open source, and many of them are based on C/C++. Each project lists ideas that are aimed at outsiders / beginners. Here is last year's page: http://code.google.com/soc/2008/ Google has not yet decided on which projects are participating this year, but this information will become available within the next couple of weeks (before the end of march 2009) along with a fresh list of ideas. If you're a student in a College/University you can get lucky and even get mentoring through the GSOC project. But even if not, they will really value any contribution you can make.
634,963
635,098
A good bank of recursion solutions in C/C++/Java/C#
I saw this question, but the answers there are not very relevant. A friend needs a bank of solved recursion problems to help him study for a test tomorrow. He learned the issue theoretically, but is having problems grasping how to actually solve recursion problems. Do you know a good source of solved recursion problems (preferably in C, but can be in a C-style language as well) available on the net? Note - examples in functional languages will not help much here. My friend is in a study race to pass his test tomorrow, and I'm sure switching languages will just confuse him at this point (it might be educational on other, less stressed times).
This article explains recursion and has some simple C examples for traversing linked list and binary tree
635,225
635,236
How do I call a member function pointer using a pointer to a constant object?
Here is an example of what I want to accomplish and how: class MyClass { public: void Dummy() const{} }; typedef void (MyClass::*MemFunc)(); void (const MyClass * instance) { MemFunc func=&MyClass::Dummy; // (instance->*func)(); //gives an error (const_cast<MyClass *>instance->*func)(); // works } Why do compilers (gcc 3 & 4) insist that instance should be non-const? Would that const_cast cause issues? FYI: instance` is not necessarily const, I just don't want a callee to mess with it. What is happening here?
The error is in the line before. Change the typedef to typedef void (MyClass::*MemFunc)() const; To make it a pointer to a const member function type. The difference might be more clear when considering this code and how it works: typedef void FunctionType() const; typedef FunctionType MyClass::*MemFunc; A member-function pointer in particular is actually just a special case of a member-pointer in general. For a const member function, the function type of the member function is different than for a non-const member function. That is why the types have to match.
635,276
635,295
Simple Thread Synchronization
I need a simple "one at a time" lock on a section of code. Consider the function func which can be run from multiple threads: void func() { // locking/mutex statement goes here operation1(); operation2(); // corresponding unlock goes here operation3(); } I need to make sure that operation1 and operation2 always run "together". With C# I would use a simple lock block around these two calls. What is the C++/Win32/MFC equivalent? Presumably some sort of Mutex?
Critical sections will work (they're lighter-weight that mutexes.) InitializeCriticalSection, EnterCriticalSection, LeaveCriticalSection, and DeleteCriticalSection are the functions to look for on MSDN. void func() { // cs previously initialized via InitializeCriticalSection EnterCriticalSection(&cs); operation1(); operation2(); LeaveCriticalSection(&cs); operation3();} } EDIT: Critical sections are faster than mutexes since critical sections are primarily user mode primitives - in the case of an uncontended acquire (usually the common case) there is no system call into the kernel, and acquiring takes on the order of dozens of cycles. A kernel switch is more more expensive (on the order of hundreds of cycles). The only time critical sections call into the kernel is in order to block, which involves waiting on a kernel primitive, (either mutex or event). Acquiring a mutex always involves a call into the kernel, and is thus orders of magnitude slower. However, critical sections can only be used to synchronize resources in one process. In order to synchronize across multiple processes, a mutex is needed.
635,658
635,796
What is the best way to declare a global variable?
In C++, say you want to declare a global variable to be used by many. How do you do it? I commonly use declare and define in cpp file, and then use extern in other cpp file (and not headers). I don't like this approach, and I am considering something along these lines: In a header file: some_file.h Class MYGlobalClass { }; MyGlobalClass& MyGlobalClassInstance() { static MYGlobalClass instance; return instance; } Edit Consider in the following contexts: can be used in multi-threaded applications namespace pollution may NOT necessery be a singleton, as many instances of this might be created What are your thoughts, suggestions, new ideas?
Declare it in one header file (using extern), and define it in one .cpp (or whatever other extension) file. You may use a function and return a reference to a static variable like you showed to circumvent problems with construction order relative to other such namespace scope variables in other .cpp files. But remember that won't protect you from destruction order problems - which is in the exact reverse order from construction (these things are called "static initialization order fiasco". If you use a function like yours and put it into headers, make it inline to make the redefinition of the function valid when it is included into multiple .cpp files (logically, the function is still only apparent once, because the static in it will only exist once, not separately for each file it is included into). Alternatively just declare it in a header but define it in one .cpp file (but then, remove the inline from it!). inline A& getA() { static A a; return a; } The potential problems with destruction order can be circumvented by using new: inline A& getA() { static A *a = new A; return *a; } The destructor of it, however, will never be called then. If you need thread safety, you should add a mutex that protects against multiple accesses. boost.thread probably has something for that.
635,705
635,764
Why does my Boost.Regex search report only one match iteration?
I am trying to find out how many regex matches are in a string. I'm using an iterator to iterate the matches, and and integer to record how many there were. long int before = GetTickCount(); string text; boost::regex re("^(\\d{5})\\s(\\d{8})\\s(.*)\\s(.*)\\s(.*)\\s(\\d{8})\\s(.{1})$"); char * buffer; long length; long count; ifstream f; f.open("c:\\temp\\test.txt", ios::in | ios::ate); length = f.tellg(); f.seekg(0, ios::beg); buffer = new char[length]; f.read(buffer, length); f.close(); text = buffer; boost::sregex_token_iterator itr(text.begin(), text.end(), re, 0); boost::sregex_token_iterator end; count = 0; for(; itr != end; ++itr) { count++; } long int after = GetTickCount(); cout << "Found " << count << " matches in " << (after-before) << " ms." << endl; In my example, count always returns 1, even if I put code in the for loop to show the matches (and there are plenty). Why is that? What am I doing wrong? Edit TEST INPUT: 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N OUTPUT (without matches): Found 1 matches in 16 ms. If I change the for loop to this: count = 0; for(; itr != end; ++itr) { string match(itr->first, itr->second); cout << match << endl; count++; } I get this as output: 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N 12345 12345678 SOME NAME SOMETHING 88888888 N Found 1 matches in 47 ms.
Heh. Your problem is your regex. Change your (.\*)s to (.\*?)s (assuming that's supported). You think you're seeing each line being matched, but in fact you're seeing the entire text being matched because your pattern is greedy. To see the issue illustrated, change the debug output in your loop to: cout << "[" << match << "]" << endl;
635,807
635,819
Can a string literal and a character literal be concatenated?
Why does name misbehave in the following C++ code? string name = "ab"+'c'; How would the equivalent code behave in Java/C#?
Try std::string name = "ab" "c"; or std::string name = std::string("ab") + c; In C++, "ab" is not a std::string, but rather a pointer to a string of chars. When you add an integral value to a pointer, you get a new pointer that points farther down the string: char *foo = "012345678910121416182022242628303234"; std::string name = foo + ' '; name gets set to "3234", since the integer value of ' ' is 32 and 32 characters past the begining of foo is four characters before the end of the string. If the string was shorter, you'd be trying to access something in undefined memory territory. The solution to this is to make a std:string out of the character array. std:strings let you append characters to them as expected: std::string foo = "012345678910121416182022242628303234"; std::string name = foo + ' '; name gets set to "012345678910121416182022242628303234 "
635,812
636,633
How to keep together few inseparable text blocks in QTextEdit at the end of current page (throw all on the next page)?
i have a QTextEdit document which size is different by every print. In the middle of the document i have few blocks of text which are inseparable in the eyes of the user and i have to protect my blocks from splitting on two pages in case the document gets equivalent size. Have you got any solution?
I am a great fan of Qt but I have not had an opportunity yet to use a QTextEdit. I would like to help though so I took a look through the documentation. If you are using a sufficiently recent version of Qt you should find that a QTextEdit has an associated QTextDocument and it would seem that the functionality you seek may be there. A QTextDocument is a hierarchy of frames and blocks. A block is equivalent to a paragraph as you mention above. The documentation seems to indicate that you could specify that your blocks be wrapped in a frame. Then, you should be able to set a format for the frame using QTextFrame::setFrameFormat. This format will allow you to specify a page break policy using some flags. The flags that are specified are PageBreak_Auto, PageBreak_AlwaysBefore and PageBreak_AlwaysAfter. It would seem to me that if you set both the PageBreak_AlwaysBefore and PageBreak_AlwaysAfter flags for the frame, then your blocks should stay together. I realize this is a fairly complex series. I hope that it helps and would really like to hear if it works.
636,110
636,206
does adding new member function into d pointer class break binary compatibility?
Will adding new member function into d pointer class definition break binary compatibility? For example, will the new definition below break binary compatibility compared to the original? (side question, is there a tool that will tell me if a new .so breaks binary compatibility compared to the old .so? If not, how do I check manually?) Original: #ifndef __TESTBC_H__ #define __TESTBC_H__ class APrivate; class A { public: int get() { d->update(); return _d->get(); } private: APrivate *_d; }; class APrivate { public: int get() { return _val; } void update() { _val = 1; } private: int _val; }; #endif New: #ifndef __TESTBC_H__ #define __TESTBC_H__ class APrivate; class A { public: int get() { _d->update(); return _d->get(); } private: APrivate *_d; }; class APrivate { public: int get() { return _val; } void update() { _val = 1; multiply(); } void multiply() { _val = _val * 10; } private: int _val; }; #endif FYI: I understand d pointer class should be specified in the cc file instead of header. above example is contrived to focus on binary compatibility issue.
No it does not. You should understand how C++ builds its objects. In your case it is just almost "POD" class with non-virtual member functions. These functions do not affet the representation of object in memory. Thus new version is binary compatible with old. More then that, if you do not expose your "APrivate" class to user. (Not giving a header just forward declaration), you would not brake an API even if you do much bigger changes. Meaning: #ifndef YOUR_PUBLIC_API #define YOUR_PUBLIC_API class bar; class foo { public: // member functions using bar private: bar *bar_; }; #endif You do not even expose bar so you may change it in any way you wish. it is the best way to make C++ libraries ABI compatible.
636,755
636,760
How can I return a const ref a to local variable in C++?
I have a function for which I cannot change the function parameters. I need to return a const reference to a std::string created in this function. I tried to use boost shared_ptr, but this doesn't work. Why? How do I make this work? const std::string& getVal(const std::string &key) { boost::shared_ptr<std::string> retVal(new std::string()); ... //build retVal string with += operator based on key return *retVal; }
You can't return a reference to a local variable from a function with c++. Although in c++0x this is possible. Allocate the string on the heap and manually cleanup later: If you cannot change the function's interface, then you will need to create it on the heap and then manually delete it after. //Remember to free the address that getVal returns const std::string& getVal(const std::string &key) { std::string *retVal = new std::string(); ... //build retVal string with += operator based on key return *retVal; } Same solution but not manually: Since the above will eventually lead to a memory leak if you forget to free it manually. I would recommend to wrap this call into a class and use RAII. I.e. in the constructor, call getVal and set a member of this class to point to it. In the destructor of your class you would delete it. Why the code you gave with shared_ptr does not work: shared_ptr works via reference counting. Since you are destroying the only shared_ptr object (by scope), there are no references left and the memory will be freed. To get this to work you'd have to return a shared_ptr, but you said you cannot do this.
636,810
637,640
Mac OSX - Xcode Installation Directory
After Xcode has finished building is there a way to make it copy the executable to specific directory ~/Sites/cgi-bin/ I have the target Installation Directory set to the correct folder, with skip installation unchecked, but no luck. Is there something i'm missing?
Check the "Deployment Postprocessing" build setting in your target's Release configuration. Installation is normally done only with a command-line xcodebuild install, but setting Deployment Postprocessing makes it install on every build. Ensure your user account has write privileges in the directory you want to install in, because the IDE normally doesn't run with root privileges.
636,829
636,834
Difference between void main and int main in C/C++?
Does it matter which way I declare the main function in a C++ (or C) program?
The difference is one is the correct way to define main, and the other is not. And yes, it does matter. Either int main(int argc, char** argv) or int main() are the proper definition of your main per the C++ spec. void main(int argc, char** argv) is not and was, IIRC, a perversity that came with older Microsoft's C++ compilers. https://isocpp.org/wiki/faq/newbie#main-returns-int
636,975
728,723
ATL simple object wizard - "Object Xxx already exists" error
I am attempting to create a new COM object in my DLL using the ATL Simple Object Wizard in Visual Studio 2005. I enter the short name for the object, and all of the other fields are derived. However, when I click Next in the wizard, the following error message comes up: Object 'IXxxInterfaceName' already exists I have searched my entire solution for all references to IXxxInterfaceName and can't see it defined anywhere. How is the wizard determining that it exists already?
I never found out why the wizard determined that the object name existed already - I'm guessing something was cached somewhere that I couldn't track down. In the end, I appended a 2 to the end of the interface name when creating it which allowed it to be added. Then I replaced all the occurrences of IXxxInterfaceName2 with IXxxInterfaceName. Everything worked after this. If I ever track down the root cause of this problem, I'll update the answer.
636,999
637,031
DECLSPEC_NOVTABLE on pure virtual classes?
This is probably habitual programming redundancy. I have noticed DECLSPEC_NOVTABLE ( __declspec(novtable) ) on a bunch of interfaces defined in headers: struct DECLSPEC_NOVTABLE IStuff : public IObject { virtual method1 () = 0; virtual method2 () = 0; }; The MSDN article on this __declspec extended attribute says that adding this guy will remove the construct and desctructor vtable entries and thus result in "significant code size reduction" (because the vtable will be removed entirely). This just doesn't make much sense to me. These guys are pure virtual, why wouldn't the compiler just do this by default? The article also says that if you do this, and then try and instantiate one of these things, you will get a run time access violation. But when I tried this with a few compilers (with or without the __declspec extension), they don't compile (as I would have expected). So I guess to summarize: Does the compiler strip out the vtable regardless for pure virtual interfaces, or have I missed something fundamental here? What is the MSDN article talking about ?
The compiler strips out the only reference to the vtable, which would have been during construction of the class. Therefore, the linker can optimize it away since there is no longer a reference in the code to it. Also by the way, I have made a habit of declaring an empty constructor as protected, and also using Microsoft's extension abstract keyword, to avoid that access violation at runtime. This way, the compiler catches the problem at compile time instead (since only a base class can instantiate the interface through the protected constructor). The derived class will of course fill in the vtable during its construction.
637,081
637,217
How can I link a dynamic library in Xcode?
I am currently developing a program in Qt and it uses the library libqextserialport.1.dylib. I build it and run in x-code and it spits back: dyld: Library not loaded: libqextserialport.1.dylib Referenced from: /Users/samuelreh/Desktop/QtOpenCV/build/Debug/QtOpenCV.app/Contents/MacOS/QtOpenCV Reason: image not found The library is located in /Users/samuelreh/Desktop/QtOpenCV/qextserialport/build/. I can run my program by changing to the executable folder /Users/samuelreh/Desktop/QtOpenCV/build/Debug/QtOpenCV.app/Contents/MacOS/ and entering: install_name_tool -change libqextserialport.1.dylib /Users/samuelreh/Desktop/QtOpenCV/qextserialport/build/libqextserialport.1.dylib QtOpenCV I know there is probably many solutions besides this. Anybody know the best / most-elegant / easiest to do from x-code?
If I understand your problem correctly, your app is building fine, no errors when linking, but when you try to launch it the library cannot be found. That's not surprising, since the dylib file is in some arbitrary directory not on the system path. You either need to copy it into /usr/lib (probably not a good idea) or include it in the application bundle. The latter is probably the better approach. I've never tried it, but apparently you need to use a Copy Files Build Phase to put the dylib inside your bundle and then configure Xcode so that your executable will know where to find it.
637,118
637,155
std::stringstream strange behaviour
Some background information, for a homework assignment I had to write a polish notation calculator using binary trees, for this to work I had to parse command line input so that it would properly build the binary tree and then go over it to give a valid answer to the mathematical expression that was entered. For the parsing I used a std::stringstream so that I would easily be able to convert the std::string I was handed into a valid float (or integer, double). The issue I ran across was the following code, which has the error showcased and how I solved the issue. I was hoping that somebody where would be able to tell me if I was doing something wrong and .clear() is not correct, or if this is a bug in the standard library in the way it handles this particular input (only happens for + and -). #include <iostream> #include <sstream> #include <string> int main() { std::string mystring("+"); int num; char op; std::stringstream iss(mystring); iss >> num; // Seems it is not a number if (iss.fail()) { // This part does not work as you would expect it to // We clear the error state of the stringstream iss.clear(); std::cout << "iss fail bit: " << iss.fail() << std::endl; iss.get(op); std::cout << "op is: " << op << " iss is: " << iss.str() << std::endl; std::cout << "iss fail bit: " << iss.fail() << std::endl; // This however works as you would expect it to std::stringstream oss(iss.str()); std::cout << "oss fail bit: " << oss.fail() << std::endl; oss.get(op); std::cout << "op is: " << op << " oss is: " << oss.str() << std::endl; std::cout << "oss fail bit: " << oss.fail() << std::endl; } else { // We got a number } } Sample output from the program: iss fail bit: 0 op is: iss is: + iss fail bit: 1 oss fail bit: 0 op is: + oss is: + oss fail bit: 0 Maybe you guys will see something I missed, or if this is indeed a bug higher up beyond my program, in which case pointers as to where to report this would be greatly appreciated.
When you say: iss.clear(); std::cout << "iss fail bit: " << iss.fail() << std::endl; iss.get(op); you are trying to read something that has already been read. You need to reset the streams read pointer: iss.clear(); iss.seekg(0); // start again std::cout << "iss fail bit: " << iss.fail() << std::endl; iss.get(op);
637,175
637,214
Possible bug in _controlfp_s may not restore control word correctly
I've stumbled across either a problem with _controlfp_s (Visual Studio 2008), or my understanding of it. I thought the first out parameter returned the control flags before changes of the other parameters are applied. Seems it returns the flags after the change. So, I thought the correct way to use it was like this: // Chop rounding unsigned int old; _controlfp_s(&old, _RC_CHOP, _MCW_RC); // Do chopped math // Restore unsigned int unused; _controlfp_s(&unused, old, _MCW_RC); Unfortunately I need to do this: // Save unsigned int old1; _controlfp_s(&old1, 0, 0); // Chop rounding unsigned int old2; _controlfp_s(&old2, _RC_CHOP, _MCW_RC); // Do chopped math // Restore unsigned int unused; _controlfp_s(&unused, old1, _MCW_RC); Have I missed something? Seems pretty stupid to have to do this. btw: I've reported this to MS who said they couldn't understand it and suggested I provide a video showing the problem. Yeah right. Brad
According to MSDN: If the value for mask is equal to 0, _controlfp_s gets the floating-point control word. If mask is nonzero, a new value for the control word is set: For any bit that is on (equal to 1) in mask, the corresponding bit in new is used to update the control word. In other words, fpcntrl = ((fpcntrl & ~mask) | (new & mask)) where fpcntrl is the floating-point control word. (emphasis mine) So the way to reliably store the current control word is the second method you've written (the one you already found worked). If you're modifying the control word, then you won't be passing 0 for the mask, and per the function documentation it will not retrieve the current control word.
637,196
637,198
How to Pass Decimal Value as Argument Correctly
I have this: double myDecimal = static_cast<double>(atoi(arg_vec[1])); cout << myDecimal << endl; But why when I pass the argument like this: ./MyCode 0.003 It prints 0 instead of 0.003.
atoi() converts to integer. You want atof(). Or you could use strtod().
637,441
637,548
std::for_each, calling member function with reference parameter
I have a container of pointers which I want to iterate over, calling a member function which has a parameter that is a reference. How do I do this with STL? My current solution is to use boost::bind, and boost::ref for the parameter. // Given: // void Renderable::render(Graphics& g) // // There is a reference, g, in scope with the call to std::for_each // std::for_each( sprites.begin(), sprites.end(), boost::bind(&Renderable::render, boost::ref(g), _1) ); A related question (from which I derived my current solution from) is boost::bind with functions that have parameters that are references. This specifically asks how to do this with boost. I am asking how it would be done without boost. Edit: There is a way to do this same thing without using any boost. By using std::bind and friends the same code can be written and compiled in a C++11-compatible compiler like this: std::for_each( sprites.begin(), sprites.end(), std::bind(&Renderable::render, std::placeholders::_1, std::ref(g)) );
This is a problem with the design of <functional>. You either have to use boost::bind or tr1::bind.
637,489
637,498
What would be the correct design for keeping configuration settings in c++?
Say I have ini/json to store configuration setting of my desktop application,Will it be ok to have a static object with all property loaded at startup/when ever it is required or is there any other better alternative? Since this is the very first time I am doing this ,so just wanted to know whether static object is fine or singleton pattern or something else would be better
Either way is fine. If it was me, I would have it on construction of the config object. cConfig Config("config.ini"); This Config class would load the settings found in the file. Any code can access the settings by doing Config.Get("NumberOfFoobars") For testability purposes, if there is no file in the construction, the class' settings is set to default or a log file is created with a line advising the user of the missing settings. And then for functions that needs the config, I would pass the Config instance as part of the parameters: DoStuff(Config, [...]); and have DoStuff get the variables from the Config class. This makes the class testable (you can mock Config class), readeable (at a glance, you can tell which function requires Configs) and you don't have to rely on static instances (singletons are dangerous if you don't know how to use them). You might be interested to learn more about this
637,695
637,737
How efficient is std::string compared to null-terminated strings?
I've discovered that std::strings are very slow compared to old-fashioned null-terminated strings, so much slow that they significantly slow down my overall program by a factor of 2. I expected STL to be slower, I didn't realise it was going to be this much slower. I'm using Visual Studio 2008, release mode. It shows assignment of a string to be 100-1000 times slower than char* assignment (it's very difficult to test the run-time of a char* assignment). I know it's not a fair comparison, a pointer assignment versus string copy, but my program has lots of string assignments and I'm not sure I could use the "const reference" trick in all places. With a reference counting implementation my program would have been fine, but these implementations don't seem to exist anymore. My real question is: why don't people use reference counting implementations anymore, and does this mean we all need to be much more careful about avoiding common performance pitfalls of std::string? My full code is below. #include <string> #include <iostream> #include <time.h> using std::cout; void stop() { } int main(int argc, char* argv[]) { #define LIMIT 100000000 clock_t start; std::string foo1 = "Hello there buddy"; std::string foo2 = "Hello there buddy, yeah you too"; std::string f; start = clock(); for (int i=0; i < LIMIT; i++) { stop(); f = foo1; foo1 = foo2; foo2 = f; } double stl = double(clock() - start) / CLOCKS\_PER\_SEC; start = clock(); for (int i=0; i < LIMIT; i++) { stop(); } double emptyLoop = double(clock() - start) / CLOCKS_PER_SEC; char* goo1 = "Hello there buddy"; char* goo2 = "Hello there buddy, yeah you too"; char *g; start = clock(); for (int i=0; i < LIMIT; i++) { stop(); g = goo1; goo1 = goo2; goo2 = g; } double charLoop = double(clock() - start) / CLOCKS_PER_SEC; cout << "Empty loop = " << emptyLoop << "\n"; cout << "char* loop = " << charLoop << "\n"; cout << "std::string = " << stl << "\n"; cout << "slowdown = " << (stl - emptyLoop) / (charLoop - emptyLoop) << "\n"; std::string wait; std::cin >> wait; return 0; }
Well there are definitely known problems regarding the performance of strings and other containers. Most of them have to do with temporaries and unnecessary copies. It's not too hard to use it right, but it's also quite easy to Do It Wrong. For example, if you see your code accepting strings by value where you don't need a modifiable parameter, you Do It Wrong: // you do it wrong void setMember(string a) { this->a = a; // better: swap(this->a, a); } You better had taken that by const reference or done a swap operation inside, instead of yet another copy. Performance penalty increases for a vector or list in that case. However, you are right definitely that there are known problems. For example in this: // let's add a Foo into the vector v.push_back(Foo(a, b)); We are creating one temporary Foo just to add a new Foo into our vector. In a manual solution, that might create the Foo directly into the vector. And if the vector reaches its capacity limit, it has to reallocate a larger memory buffer for its elements. What does it do? It copies each element separately to their new place using their copy constructor. A manual solution might behave more intelligent if it knows the type of the elements before-hand. Another common problem is introduced temporaries. Have a look at this string a = b + c + e; There are loads of temporaries created, which you might avoid in a custom solution that you actually optimize onto performance. Back then, the interface of std::string was designed to be copy-on-write friendly. However, with threads becoming more popular, transparent copy on write strings have problems keeping their state consistent. Recent implementations tend to avoid copy on write strings and instead apply other tricks where appropriate. Most of those problems are solved however for the next version of the Standard. For example instead of push_back, you can use emplace_back to directly create a Foo into your vector v.emplace_back(a, b); And instead of creating copies in a concatenation above, std::string will recognize when it concatenates temporaries and optimize for those cases. Reallocation will also avoid making copies, but will move elements where appropriate to their new places. For an excellent read, consider Move Constructors by Andrei Alexandrescu. Sometimes, however, comparisons also tend to be unfair. Standard containers have to support the features they have to support. For example if your container does not keep map element references valid while adding/removing elements from your map, then comparing your "faster" map to the standard map can become unfair, because the standard map has to ensure that elements keep being valid. That was just an example, of course, and there are many such cases that you have to keep in mind when stating "my container is faster than standard ones!!!".
637,729
639,102
Making C++ library Avaiable to .Net
I need to make a large c++ library avaiable for use in .Net languages such as C#. The library contains a large number of classes which can be broken into two groups. Refrence counted classes, which implement the IRefCounted abstract class and use a factory method to create them, and just plain classes using new/delete. In adittion there are many plain functions. Origenannly I was just going to write wrapper classes for everything in c++/clr. However it is desired that the resulting wrapper libraries will work on Mono. Recompiling the library and the wrapper to target each platform is fine, however the problem is that it seems that c++/clr can only target windows as there is no compiler for it to target other platforms and thus the wrapper code wont work on other patforms... Is there somthing I missed here (like a howto run c++/clr on x platform guide) or is there an alterative way to make all the c++ functions, structs and classes avaible to C#? EDIT: By avaible I mean avaible to use eg say in my c++ lib I had //namespace maths{ class Vector2 { public: float x,y; Vector2(); Vector2(const Vector&); Vector2(float x, float y); float Dot(); //operators ... }; Then in C# id like to be able to use it like a normal class eg maths::Vector2 a = new maths::Vector2(5, 5); maths::Vector2 b = new maths::Vector2(1, 10); b *= 3 maths::Vector2 c = a + b; //c.x == 8, c.y == 35 Also however I do it I cant edit the c++ library, anything must be done as a wrapper around the existing classes and functions.
C++/CLI wrappers are definitely the best option if you are only targetting Windows. They perform very well, are very easy to write and maintain, etc. But, as you said, this will not work on Mono. The issue is that the assembly that gets created is not a clr:pure assembly, but one that has mixed native and IL code, so it will not work outside of Windows. In addition, you need to create separate assemblies in C++/CLI for x86 and x64 targets, if you're going to be targetting 64bit systems. SWIG is definitely an option. It can handle all of the complexities of wrapping a C++ class, but when you get to more complex issues, you typically have to do some tweaking. I'd recommend checking out the SWIG main site, and especially their C# section. For good examples of using SWIG to wrap a very complex library, check out OGRE Dot Net (nearly dead, but still a good example) or GDAL. From what I remember, both have special handling for C# specific features, and handle reference counted classes, enums, etc. The other nice thing about SWIG - if you make SWIG wrappers, it's very easy to extend it to other languages if you ever need to. Once you have the wrappers, making Java, python, ruby, etc wrappers is easy.
637,892
637,901
"String.h" VS <string.h>
Friends On HP-UX box when Iam passing a string object to function Im getting the following below error Error 422: "../header/Handler.h", line 24 # 'string' is used as a type, but has not been defined as a type. Perhaps you meant 'String' as in class String ["/opt/aCC/include/SC/String.h", line 66]. int populateBindingHandle(rpc_if_handle_t p_if_spec, string p_cell_name); why would I get an error to use String.h not how does a declaration String newstr; different from string newstr; ?? Many Thanks
Looks like there is a String class in the header mentioned by the compiler. The compiler thinks you made a typo. If you want to use STL strings use the following: #include <string> int populateBindingHandle(rpc_if_handle_t p_if_spec, std::string ...) or have a using declaration somewhere: using std::string; int populateBindingHandle(rpc_if_handle_t p_if_spec, std::string ...) Note, the old-style headers have been deprecated, i.e. you should no longer use #include <string.h>
637,953
637,961
g++ not working on Windows command prompt. Cygwin installed
I have installed Eclipse and CDT (to use C/C++ in eclipse CDT is needed), as well as installing Cygwin so that I can compile my files. In environment variables I've set Path to include the following: "C:\cygwin\bin;" g++, make and GDC are all installed via Cygwin. I made sure of this by searching for them in the bin folder - they're all there. If I enter "make" into the windows command prompt, this appears: make: *** No targets specified and no makefile found. Stop. If I enter "g++" or "gdc" into the windows command prompt, this appears (or similar): 'g++' is not recognized as an internal or external command, operable program or batch file. So, in other words make is working but the rest isn't..but they're in the same bin folder! Has got me completely confused. If I attempt to open Cygwin Bash Shell, g++, make and GDC all work there. However, I need it to work in the command prompt so that Eclipse is able to compile the programs I write in the IDE. If you know why this is happening, please let me know.
I haven't used cygwin much, but my understanding is you have to use it from the cygwin bash shell. if you need g++, make, etc, use mingw, with it, g++ works from the normal windows command line.
638,053
638,100
How to Increment Visual Studio build number using C++?
I have a Visual Studio 2008 project that produces a file called: "Game-Release.exe". This was configured under Project Properties -> C/C++ -> Linker -> General: $(OutDir)\$(ProjectName)-Release.exe I would like to take this a bit further by have an incrementing build number so I would have something which says: Game-Release-Build-1002.exe The number on the end should be an incrementing integer. I will be storing the build exe's on subversion so I think i would find this useful (although not necessary). Perhaps there is a built in macro in Visual Studio that could handle this. Quite possibly I was thinking I could have a text file with the build number in it and have the compiler read, use and increment the number in the file each time the project is built. My goal is however to make the process as automated as possible. What is the best way to accomplish this? If you offer an opinion, please also provide the code we can all share. Thnx.
The Versioning Controlled Build add-in seems like it would do the job. Update: Your question specifically mentions using Visual Studio to increment the version, but there is nothing automated about that. Have you considered using Nant and a CI server? That way, it is easy to inject the SVN revision number into AssemblyInfo.cs equivalent for C++. Automatically, on the build server.
638,090
638,139
Profiling C++ multi-threaded applications
Have you used any profiling tool like Intel Vtune analyzer? What are your recommendations for a C++ multi threaded application on Linux and windows? I am primarily interested in cache misses, memory usage, memory leaks and CPU usage. I use valgrind (only on UNIX), but mainly for finding memory errors and leaks.
Following are the good tools for multithreaded applications. You can try evaluation copy. Runtime sanity check tool Thread Checker -- Intel Thread checker / VTune, here Memory consistency-check tools (memory usage, memory leaks) - Memory Validator, here Performance Analysis. (CPU usage) - AQTime , here EDIT: Intel thread checker can be used to diagnose Data races, Deadlocks, Stalled threads, abandoned locks etc. Please have lots of patience in analyzing the results as it is easy to get confused. Few tips: Disable the features that are not required.(In case of identifying deadlocks, data race can be disabled and vice versa.) Use Instrumentation level based on your need. Levels like "All Function" and "Full Image" are used for data races, where as "API Imports" can be used for deadlock detection) use context sensitive menu "Diagnostic Help" often.
638,101
638,122
C/C++ Programming in Vista
I'm from a Java school, but I'd like to get my hands dirty in C/C++ development as well. Can you suggest: a Lightweight beginner IDE [Eg: JCreator for Java] (Simple and small download) a full-blown advanced IDE [Eg: Eclipse for Java] (Every feature and huge download) should I use GCC or other compilers? Thanks a lot guys!
1) a Lightweight beginner IDE [Eg: JCreator for Java] (Simple and small download) Eclipse with CDT (~40 MB download) or Visual Studio 2008 Express edition (2.6 MB download for installer and then tons of stuff that it'll pull from the net) -- it's free. Also, get the SP1. But, I still suggest that you take a look at Visual Studio. 2) a full-blown advanced IDE [Eg: Eclipse for Java] (Every feature and huge download) Eclipse with CDT (~40 MB download) or Visual Studio 2008 Professional (if you are going to pay). 3) should I use GCC or other compilers? Yes and no. Depends on your needs. GNU g++ is great to get started with. However, hooking up with CDT may prove to be difficult. If you intend to do professional Windows programming in near future, it is best to buy the Visual Studio 2008 Pro (and install SP1) and get used to it.
638,251
638,693
How to emit cross-thread signal in Qt?
Qt documentation states that signals and slots can be direct, queued and auto. It also stated that if object that owns slot 'lives' in a thread different from object that owns signal, emitting such signal will be like posting message - signal emit will return instantly and slot method will be called in target thread's event loop. Unfortunately, documentation do not specify that 'lives' stands for and no examples is available. I have tried the following code: main.h: class CThread1 : public QThread { Q_OBJECT public: void run( void ) { msleep( 200 ); std::cout << "thread 1 started" << std::endl; MySignal(); exec(); } signals: void MySignal( void ); }; class CThread2 : public QThread { Q_OBJECT public: void run( void ) { std::cout << "thread 2 started" << std::endl; exec(); } public slots: void MySlot( void ) { std::cout << "slot called" << std::endl; } }; main.cpp: int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); CThread1 oThread1; CThread2 oThread2; QObject::connect( & oThread1, SIGNAL( MySignal() ), & oThread2, SLOT( MySlot() ) ); oThread1.start(); oThread2.start(); oThread1.wait(); oThread2.wait(); return a.exec(); } Output is: thread 2 started thread 1 started MySlot() is never called :(. What I'm doing wrong?
There are quite a few problems with your code : like said by Evan the emit keyword is missing all your objects live in the main thread, only the code in the run methods live in other threads, which means that the MySlot slot would be called in the main thread and I'm not sure that's what you want your slot will never be called since the main event loop will never been launched : your two calls to wait() will only timeout after a very long time (and you'll probably kill your application before that happens) and I don't think that's what you want either, anyway they really have no use in your code. This code would most likely work (though I have not tested it) and I think it does what you want it to do : class MyObject : public QObject { Q_OBJECT public slots: void MySlot( void ) { std::cout << "slot called" << std::endl; } }; class CThread1 : public QThread { Q_OBJECT public: void run( void ) { std::cout << "thread 1 started" << std::endl; int i = 0; while(1) { msleep( 200 ); i++; if(i==1000) emit MySignal(); } } signals: void MySignal( void ); }; class CThread2 : public QThread { Q_OBJECT public: void run( void ) { std::cout << "thread 2 started" << std::endl; exec(); } }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); CThread1 oThread1; CThread2 oThread2; MyObject myObject; QObject::connect( & oThread1, SIGNAL( MySignal() ), & myObject, SLOT( MySlot() ) ); oThread2.start(); myObject.moveToThread(&oThread2) oThread1.start(); return a.exec(); } Now MyObject will live in thread2 (thanks to moveToThread). MySignal should be sent from thread1 (thought I'm not sure on that one, it might be sent from main thread, it doesn't really matter). No event loop is needed in thread1 since emitting a signal doesn't need an event loop. An event loop is needed in thread2 (lanched by exec()) to receive the signal. MySlot will be called in thread2.
638,260
638,492
Why does this take so long to compile in VCC 2003?
My team need the "Sobol quasi-random number generator" - a common RNG which is famous for good quality results and speed of operation. I found what looks like a simple C implementation on the web. At home I was able to compile it almost instantaneously using my Linux GCC compiler. The following day I tried it at work: If I compile in Visual Studio in debug mode it takes about 1 minute. If I were to compile it in release mode it takes about 40 minutes. Why? I know that "release" mode triggers some compiler optimization... but how on earth could a file this small take so long to optimize? It's mostly comments and static-data. There's hardly anything worth optimizing. None of these PCs are particularly slow, and in any case I know that the compile time is consistent across a range of Windows computers. I've also heard that newer versions of Visual Studio have a faster compile time, however for now we are stuck with Visual Studio.Net 2003. Compiling on GCC (the one bundled with Ubuntu 8.04) always takes microseconds.
To be honest, I'm not really sure the codes that good. It's got a nasty smell in it. Namely, this function: unsigned int i4_xor ( unsigned int i, unsigned int j ) //****************************************************************************80 // // Purpose: // // I4_XOR calculates the exclusive OR of two integers. // // Modified: // // 16 February 2005 // // Author: // // John Burkardt // // Parameters: // // Input, unsigned int I, J, two values whose exclusive OR is needed. // // Output, unsigned int I4_XOR, the exclusive OR of I and J. // { unsigned int i2; unsigned int j2; unsigned int k; unsigned int l; k = 0; l = 1; while ( i != 0 || j != 0 ) { i2 = i / 2; j2 = j / 2; if ( ( ( i == 2 * i2 ) && ( j != 2 * j2 ) ) || ( ( i != 2 * i2 ) && ( j == 2 * j2 ) ) ) { k = k + l; } i = i2; j = j2; l = 2 * l; } return k; } There's an i8_xor too. And a couple of abs functions. I think a post to the DailyWTF is in order. EDIT: For the non-c programmers, here's a quick guide to what the above does: function xor i:unsigned, j:unsigned answer = 0 bit_position = 1 while i <> 0 or j <> 0 if least significant bit of i <> least significant bit of j answer = answer + bit_position end if bit_position = bit_position * 2 i = i / 2 j = j / 2 end while return answer end function To determine if the least significant bit is set or cleared, the following is used: bit set if i <> (i / 2) * 2 bit clear if i == (i / 2) * 2 What makes the code extra WTFy is that C defines an XOR operator, namely '^'. So, instead of: result = i4_xor (a, b); you can have: result = a ^ b; // no function call at all! The original programmer really should have know about the xor operator. But even if they didn't (and granted, it's another obfuscated C symbol), their implementation of an XOR function is unbelievably poor.
638,277
640,908
Loading DLL from a location in memory
As the question says, I want to load a DLL from a location in memory instead of a file, similarly to LoadLibrary(Ex). I'm no expert in WinAPI, so googled a little and found this article together with MemoryModule library that pretty much meets my needs. On the other hand the info there is quite old and the library hasn't been updated for a while too. So I wanted to know if there are different, newer and better ways to do it. Also if somebody has used the library mentioned in the article, could they provide insight on what I might be facing when using it? Just for the curious ones, I'm exploring the concept of encrypting some plug-ins for applications without storing the decrypted version on disk.
Well, you can create a RAM Drive according to these instructions, then copy the DLL you can in memory to a file there and the use LoadLibrary(). Of course this is not very practical if you plan to deploy this as some kind of product because people are going to notice a driver being installed, a reboot after the installation and a new drive letter under My Computer. Also, this does nothing to actually hide the DLL since its just sitting there in the RAM Drive for everybody to watch. Another thing I'm interested about is Why you actually want to do this? Perhaps your end result can be achieved by some other means other than Loading the DLL from memory. For instance when using a binary packer such as UPX, the DLL that you have on disk is different from the one that is eventually executed. Immediately after the DLL is loaded normally with LoadLibrary, The unpacker kicks in and rewrites the memory which the DLL is loaded to with the uncompressed binary (the DLL header makes sure that there is enough space allocated)
638,452
1,060,391
Prolog ECLiPSe - how to implement yield method?
i'm using ECLiPSe programming logic system. i want to implement the yield method for passing the values from prolog to C/C++. Has anyone implemented it? Are there any other ways for passing the values?
The following page tells how to integrate ECLiPSe with C++ using the yield method: http://87.230.22.228/doc/embedding/embroot006.html#toc8
638,704
643,766
Why QWidget::paintEvent doesn't get called?
I have a simple hierarchy of widgets: GraphWidget -> MotionWidget -> NodeWidget. I am new to Qt, so I am not quite sure about how some insides work yet. Basically, GraphWidget creates a single MotionWidget M and sets M's parent to itself. M then goes away and creates a bunch of NodeWidgets. However, NodeWidgets never get painted nor does their paintEvent() function gets called. I tried creating MotionWidget directly, without GraphWidget and everything works. So why does things break if I add GraphWidget to the hierarchy? Here is a paste with the relevant bits of code from my project. I also included the output from GraphWidget::dumpObjectTree() at the top. Edit: forgot to include the paste link ;) http://rafb.net/p/Zp39CF94.html Update: I wrapped MotionWidget into a layout. Before: GraphWidget :: GraphWidget( QWidget *parent ) : QWidget( parent ) { setFixedSize( 500, 500 ); MotionWidget *n = new MotionWidget( 5, this ); } After GraphWidget :: GraphWidget( QWidget *parent ) : QWidget( parent ) { setFixedSize( 500, 500 ); QVBoxLayout *l = new QVBoxLayout; MotionWidget *n = new MotionWidget( 5 ); l->addWidget( n ); setLayout( l ); } Now, the latter works. I.e. everything gets drawn. The question then becomes... Why? Why didn't it work in the first case but worked in the second?
I'm going to disagree with Aiua's answer. Passing the parent to an object will add the child to the visual hierarchy. (Otherwise, using Designer to make a widget including others, but with absolute positioning, wouldn't work.) However, there were probably other factors keeping the painting from happening. Due to the fact that the layout made things work, I'm going to guess that in both versions, MotionWidget has no set size. That would mean in the first example that it would be sized to 0x0 pixels, which Qt will optimize out when trying to paint. In the second example, the layout controls the size of the widgets added to it, and so would enlarge MotionWidget, and thus it would start to receive paint events again. To fix this, you could set the size explicitly like you do for GraphWidget, or you could do some dynamic sizing based on the parent's size, or GraphWidget could control the size, or any of a large number of various options. Layouts can be nice also, but aren't absolutely required.
639,100
639,426
Pointer to member functions - C++ std::list sort
How do i pass a pointer to a member function to std::list.sort()? Is this possible? Thanks struct Node { uint32_t ID; char * Value; }; class myClass { private: uint32_t myValueLength; public: list<queueNode *> MyQueue; bool compare(Node * first, Node * second); bool doStuff(); } bool myClass::compare(Node * first, Node * second) { unsigned int ii =0; while (ii < myValueLength) { if (first-> Value[ii] < second-> Value[ii]) { return true; } else if (first-> Value[ii] > second-> Value[ii]) { return false; } ++ii; } return false; } bool myClass::doStuff() { list.sort(compare); } I want to use a length variable from within the class instead of doing strlen() within the compare function (The Value will always be the same length) Edit: The myValueLength was not the only variable i wanted to access from within the comparison function I just simplified it to make the example shorter.
Elaborating on grieve's response, why not use a functor? E.g.: struct Functor { bool operator()( char * a, char * b ) { return strcmp(a,b) < 0; } }; Then you could just use: Functor f; myList.sort(f); You could even use your class as the Functor by defining operator()... class myClass { ... bool operator()( queueNode * a, queueNode * b ) { return compare( a, b ); } void doStuff() { MyQueue.sort(*this); } }; Simple example code: #include <iostream> #include <list> using namespace std; // Assumes TYPE t; cout << t; is valid. template<class TYPE> inline ostream & operator<< ( ostream & theOstream, const list<TYPE> & theList ) { typename list<TYPE>::const_iterator listIterator = theList.begin(); for ( int i = 0; listIterator != theList.end(); listIterator ++, i ++ ) theOstream << " [" << i << "]: \"" << (*listIterator) << "\"" << endl; return theOstream; } struct Functor { bool operator()( const char * a, const char * b ) { return strcmp(a,b) < 0; } }; int main() { list<char*> l; /* Load up some example test data... */ char s[3]; s[2] = '\0'; for ( s[0]='c'; s[0]>='a'; s[0]-- ) for ( s[1]='c'; s[1]>='a'; s[1]-- ) l.push_back(strdup(s)); /* Show us that test data... */ cout << l << endl; /* Sort list. */ Functor f; l.sort(f); /* Show us what we have now... */ cout << l << endl; }
639,194
639,291
Linker issue: undefined reference
I have a problem with the linker when I build my current project. The error it comes up with is as follows: libmiinddynamic.so: undefined reference to `std::basic_ostream<char, std::char_traits<char> >& SparseImplementationLib::operator<< <double, double, SparseImplementationLib::DefaultPtr<double, double> >(std::basic_ostream<char, std::char_traits<char> >&, SparseImplementationLib::AbstractSparseNode<double, double, SparseImplementationLib::DefaultPtr<double, double> > const&)' This is slightly strange, as as far as I'm aware this method is declared in a file that is definitely being compiled: namespace SparseImplementationLib { template <ActivityType,WeightType,ptr_type = DefaultPtr<ActivityType,WeightType> > class AbstractSparseNode; // A whole bunch of other methods //! All derived classes from AbstractSparseNode can use operator<< template <class ActivityType, class WeightType, class ptr_type> ostream& operator<< ( ostream& s, const AbstractSparseNode<ActivityType,WeightType>& node) { node.ToStream(s); return s; } } Why this error might pop up? N.B. This is compiled using MPICXX on Fedora, and I'm using CCMAKE. EDIT Ok, using nm I've found the following: std::ostream& SparseImplementationLib::operator<< <double, double, SparseImplementationLib::DefaultPtr<double, double> >(std::ostream&, SparseImplementationLib::AbstractSparseNode<double, double, SparseImplementationLib::DefaultPtr<double, double> > const&) when it wants this instead: std::basic_ostream >& SparseImplementationLib::operator<< <double, double, SparseImplementationLib::DefaultPtr<double, double> >(std::basic_ostream >&, SparseImplementationLib::AbstractSparseNode<double, double, SparseImplementationLib::DefaultPtr<double, double> > const&) Unfortunately, I have no idea how to fix this, cus operator<< only takes 2 arguments. (The random \s before all the _s is to try and escape them, stackoverflow is being a little temperamental today and won't do it (otherwise we get lovely italics randomly in my code))
can you nm the object which is generated by above shown code, to see that the signature is indeed what you expect.
639,248
639,276
C++ covariant templates
I feel like this one has been asked before, but I'm unable to find it on SO, nor can I find anything useful on Google. Maybe "covariant" isn't the word I'm looking for, but this concept is very similar to covariant return types on functions, so I think it's probably correct. Here's what I want to do and it gives me a compiler error: class Base; class Derived : public Base; SmartPtr<Derived> d = new Derived; SmartPtr<Base> b = d; // compiler error Assume those classes are fully fleshed out... I think you get the idea. It can't convert a SmartPtr<Derived> into a SmartPtr<Base> for some unclear reason. I recall that this is normal in C++ and many other languages, though at the moment I can't remember why. My root question is: what is the best way to perform this assignment operation? Currently, I'm pulling the pointer out of the SmartPtr, explicitly upcasting it to the base type, then wrapping it in a new SmartPtr of the appropriate type (note that this is not leaking resources because our home-grown SmartPtr class uses intrusive reference counting). That's long and messy, especially when I then need to wrap the SmartPtr in yet another object... any shortcuts?
Both the copy constructor and the assignment operator should be able to take a SmartPtr of a different type and attempt to copy the pointer from one to the other. If the types aren't compatible, the compiler will complain, and if they are compatible, you've solved your problem. Something like this: template<class Type> class SmartPtr { .... template<class OtherType> SmartPtr(const SmartPtr<OtherType> &blah) // same logic as the SmartPtr<Type> copy constructor template<class OtherType> SmartPtr<Type> &operator=(const SmartPtr<OtherType> &blah) // same logic as the SmartPtr<Type> assignment operator };
639,496
639,662
C++ comparing bunch of values with a given one
I need to compare one given value with a retrieved values. I do this several times in the code. I am not satisfied with how it looks and I am seeking for a some sort of an util function. Anyone wrote one? Number of values I am comparing with is known at the compile time. Update: I'd like to get rid of containers as I know exact amount of values ( often not more then 3 ) I want to compare with. And it is not so convenient to put items to the container every time. I don't love if neither because it is not obvious as "find". #include <algorithm> #include <string> #include <vector> std::string getValue1() { return "test"; } std::string getValue2() { return "the"; } std::string getValue3() { return "world"; } int main() { const std::string value = "the"; // simple if if ( value == getValue1() || value == getValue2() || value == getValue3() ) return 1; // using collections like vector, set std::vector<std::string> values; values.push_back( getValue1() ); values.push_back( getValue2() ); values.push_back( getValue3() ); if ( values.end() != std::find( values.begin(), values.end(), value ) ) return 1; // third option I'd use instead // return 0; }
For your request to do if (InSet(value)(GetValue1(), GetValue2(), GetValue3())) { // Do something here... } Try this: template <typename T> class InSetHelper { const T &Value; void operator=(const InSetHelper &); public: InSetHelper(const T &value) : Value(value) {} template<class Other, class Another> bool operator()(const Other &value1, const Another &value2) const { return Value == value1 || Value == value2; } template<class Other, class Another, class AThird> bool operator()(const Other &value1, const Another &value2, const AThird &value3) const { return Value == value1 || Value == value2 || Value == value3; } }; template <typename T> InSetHelper<T> InSet(const T &value) { return InSetHelper<T>(value); } This syntax might be more clear though: if (MakeSet(GetValue1(), GetValue2(), GetValue3()).Contains(value)) { // Do something here... } template <typename T, typename U, typename V> class Set3 { const T& V1; const U& V2; const V& V3; void operator=(const Set3 &); public: Set3(const T &v1, const U &v2, const V &v3) : V1(v1), V2(v2), V3(v3) {} template <typename W> bool Contains(const W &v) const { return V1 == v || V2 == v || V3 == v; } }; template <typename T, typename U> class Set2 { // as above }; template <typename T, typename U, typename V> Set3<T, U, V> MakeSet(const T &v1, const U &v2, const V &v3) { return Set3<T, U, V>(v1, v2, v3); } template <typename T, typename U> Set3<T, U> MakeSet(const T &v1, const U &v23) { return Set3<T, U, V>(v1, v2); } If those values are really part of a tree or a linked list, then you have your set/container already, and your best bet is to just use some recursion: parent.ThisOrDescendantHasValue(value); You'd just add this to whatever class parent and child belong to: class Node { public: Value GetValue(); Node *GetChild(); bool ThisOrDescendantHasValue(const Value &value) { return GetValue() == value || (GetChild() && GetChild->ThisOrDescendantHasValue(value)); } };
639,676
639,702
Overloading global operator new/delete in C++
I am trying to overload the global operator new and delete for a performance sensitive application. I have read the concerns described at http://www.informit.com/articles/article.aspx?p=30642&seqNum=3 and the recommendations to use Intel TBB's allocator http://www.intel.com/technology/itj/2007/v11i4/5-foundations/5-memory.htm Since I am overloading new and delete for the first time, I have a few questions. Should I include my new header Allocator.h (or Pre.h) containing the overloaded new function in all files containing "new" calls? This is tedious. Or should I use "gcc -include Allocator.h ..." which includes Allocator.h (before) into each translation unit? I want to keep the code platform independent as much as possible. Do all compilers support something analogous to "gcc -include"?
If you want to overload the global operator new and operator delete, you just need to implement it. You don't need to explicitly define it everywhere since it already is defined as part of the language. Edit: If you want to define an operator new that takes different parameters, then you'll need to #include it everywhere. However you do that is up to you; it's mostly a matter of style. And don't forget to implement all the variants of global operator new and delete: new, new[], delete, delete[], and the std::nothrow variants.
639,922
640,499
How do you usually return an instance of a user-defined type allocated on the local stack
I am curious about prevalent methodologies. I found myself doing both of these things interchangeably: Note in all cases the object is allocated locally. std::string GetDescription () { std::string desc; /* Create a description */ return desc; } void GetResult (map<int, double> & resultMap) { /*Fill map result map with values*/ } map<int, double> GetResult2(map<int, double> & resultMap) { map<int, double> & resultMap /* Fill map result map with values */ return resultMap; } What is the preferred way to do this?
It greatly depends on the task at hand. I would go for the first approach for functions that create new values while using the second approach for functions that change the parameters. As mentioned by others, in some cases other restrictions (cost of creation / assignment) can affect the decision. The first definition is clearly stating that it will create a new object out of nothing and will return it. That is, the same definition is stating the semantics of the call. The second and third definitions require the caller to create an object before calling the function. This can be a hassle to the user as she cannot just ignore the return value (or use it as an unnamed temporal to feed another function, see snippet 1), and can be limited in cases (i.e. cannot reassign a reference from an already created object, see snippet 2). It is not clear from the function definition what is the use of the parameter inside the function. Will the behavior of the function differ depending on the passed object? It is not clear from the function definition. The third type is, I believe, the worst option. Not only it forces the caller to create a named variable to pass to the function but also makes a copy to return (unless it was a typo and you are returning a [possibly const] reference) At any rate, other considerations can unbalance the advantage of clear semantics that the first approach provides. In some cases performance, or other limitations like objects that cannot be copied (see snippet 3) // snippet 1 // user code to the different approaches class X {}; X f1(); void f2( X& ); X f3( X& ); void g( X const & ); void test1() { g( f1() ); // valid code } void test2() { X x; // must create instance before f2( x ); // then call the function g( x ); } void test3() { X x; // must create instance before g( f3( x ) ); } // snippet 2 class Y {}; class X { public: X( Y & y ) : y_( y ) {} private: Y & y_; }; X f1(); void f2( X & ); X f3( X & ); void test1() { X x = f1(); } void test2or3() { Y y; X x( y ); // user must create with a reference f2( x ); // f2 cannot change the reference inside x to another instance } // snippet 3 class X { private: X( X const & ); X& operator= ( X const & ); }; X f1(); // Returned object cannot be used void f2( X & ); X f3( X & ); void test1() { X x = f1(); // compilation error } void test2() { X x; f2( x ); } void test3() { X x; X y = f3( x ); // compilation error }
639,952
642,351
Linker problem, doesn't find an existing method?
Ok, I'm having issues with the linker on my current project (This is a continuation of another question, ish) Basically, the linker gives an undefined reference in dynamiclib.so for: std::basic_ostream<char, std::char_traits<char> >& SparseImplementationLib::operator<< <double, double, SparseImplementationLib::DefaultPtr<double, double> >(std::basic_ostream<char, std::char_traits<char> >&, SparseImplementationLib::AbstractSparseNode<double, double, SparseImplementationLib::DefaultPtr<double, double> > const&) And I can only find: std::ostream& SparseImplementationLib::operator<< <double, double, SparseImplementationLib::DefaultPtr<double, double> >(std::ostream&, SparseImplementationLib::AbstractSparseNode<double, double, SparseImplementationLib::DefaultPtr<double, double> > const&) within the file. Thing is, they're the same methods, really (basic_ostream and ostream are interchangable?) If I add the first method in manually to the namespace it moans about it being already defined at compile time. Does anyone know what on earth might be going on here? Cheers, Ed NB this is with MPICXX and CCMAKE
Ok, I managed to fix this this morning after about 10 hours hacking away last night. Turns out that it compiles if you make the definitions of the function inline, and make sure it has options for the function with both all the template arguments and just non-defaulted arguments!
640,095
640,761
When using a GL_RGBA16F_ARB-texture, it contains just crap, but I get no error message
I generate a texture like this: GLuint id; glGenTextures(1, &id); glBindTexture(GL_TEXTURE_2D, id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA16, //GL_RGBA16F_ARB, //< Won't work 256, 256, 0, GL_RGBA, GL_FLOAT, NULL ); glBindTexture(GL_TEXTURE_2D, 0); I attach it to a framebuffer object (FBO) for rendering to. All of this works like a charm when I set the internal format to GL_RGBA16. However, I need a higher dynamic range and was thinking that GL_RGBA16F_ARB might do the trick. Unfortunately, if I replace GL_RGBA16 with GL_RGBA16F_ARB in the code given above, the texture seems to stop working. Nothing I try to render to the FBO/texture sticks, and when I use the texture it contains random garbage. (A lot of purple, as it turns out) This would not be so frustrating if I had gotten an error message hinting at what might be wrong, but I can't seem to find one. In other words, glGetError() returns 0 after the glTexImage2D-call, and glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) returns GL_FRAMEBUFFER_COMPLETE_EXT when I have attached the texture I haven't messed with glClampColorARB(...) ... yet :) Have I forgotten to check for errors in a place/way that I haven't thought of? Do GL_RGBA16F_ARB-textures require any special treatment that I haven't given? Is there anything else that might be wrong? I'm stumped, since everything works smoothly with GL_RGBA16... :( EDIT: When using GL_RGBA16F_ARB, the first frame I try to render to screen doesn't make it. Seems to me that I should be getting an error message somewhere..? EDIT: By inspecting ShadowIce's working code example I figured out that the problems disappeared if I changed the depth buffer on my FBO, and give glRenderBufferStorageEXT(...) GL_DEPTH_COMPONENT24 as its second parameter, rather than GL_DEPTH_COMPONENT16. I have no idea why this works, but apparently it does work. Also, ShadowIce's code breaks like mine if I do the opposite substitution there.
There shouldn't be anything special to do for setting up a framebuffer with float textures. Some things I would check: Is the FBO bound and the draw/read buffer set correctly before you call glCheckFramebufferStatusEXT? Also try testing it right before you draw to it. Does the texture look ok after a simple glClear with a specific clear color? If yes, there might be something wrong with your shaders (if you use any) or the way you draw to the FBO. Are your drivers up to date? And does the problem still exist on a PC with different hardware? How about GL_RGBA32F_ARB? Edit: Check the id of your framebuffer and texture, also check if the texture id matches the one attached to your fbo (with glGetFramebufferAttachmentParameteriv). Normally I would guess that everything is ok with that if it works with a RGBA texture but random data (especially purple) is a good sign that nothing was written to the texture or it wasn't cleared properly. I have written a small example application that should work, maybe that helps. I have only tested it on windows, so for linux you might need to change it a bit: link
640,476
3,622,886
Visual Studio 2005 Ignores Preprocessor directives during compile
We just got a new developer and I'm trying to set him up with Dev Studio 2005 (The version we all use at this office), and we're running into a weird problem that I've never seen before. I have some code that works perfectly on my system, and he can't seem to get it compiled. We've tracked the issue down to his copy of dev studio ignoring the preprocessor directives. For example, in the project properties under C/C++|Preprocessor|Preprocessor Directives, I add DEFINE_ME. Which should translate to a /D"DEFINE_ME" for the compiler. And it does in my development environment, but it doesn't on his. I verified that when he checks out the code from the source repository, that he has the same version of the code I do. And if I look in his Project Properties, all of the directives are there. For some reason they're just not getting passed down to the compiler. Any Ideas?
I recently ran into the same symptom with VS2005. Ultimately I was able to resolve it by explicitly adding my preprocessor defines via the Command Line - Additional options dialog: Configuration Properties -> C/C++ -> Command Line When I added '/DPROPERTY' there it was recognized at compile time, whereas adding it under 'Preprocessor -> Preprocessor Definitions' did nothing. Oddly the Command Line dialog did show that Visual Studio was adding the property to the command line, albeit in the form '/D "PROPERTY"'. Unfortunately schedule pressure being what it is I have not been able to dig into the issue deep enough to figure out what the underlying issue was/is, nor why it seems to work out of the box for some of our projects but not others. Nonetheless the workaround above is worth a shot if you're having this symptom. Also, credit where credit is due: the idea came from this thread.
640,518
640,529
Easiest way to repeat a sequence of bytes into a larger buffer in C++
Given (in C++) char * byte_sequence; size_t byte_sequence_length; char * buffer; size_t N; Assuming byte_sequence and byte_sequence_length are initialized to some arbitrary length sequence of bytes (and its length), and buffer is initialized to point to N * byte_sequence_length bytes, what would be the easiest way to replicate the byte_sequence into buffer N times? Is there anything in STL/BOOST that already does something like this? For example, if the sequence were "abcd", and N was 3, then buffer would end up containing "abcdabcdabcd".
I would probably just go with this: for (int i=0; i < N; ++i) memcpy(buffer + i * byte_sequence_length, byte_sequence, byte_sequence_length); This assumes you are dealing with binary data and are keeping track of the length, not using '\0' termination. If you want these to be c-strings you'll have to allocate an extra byte and add in the '\0' a the end. Given a c-string and an integer, you'd want to do it like this: char *RepeatN(char *source, size_t n) { assert(n >= 0 && source != NULL); size_t length = strlen(source) - 1; char *buffer = new char[length*n + 1]; for (int i=0; i < n; ++i) memcpy(buffer + i * length, source, length); buffer[n * length] = '\0'; }
640,657
640,678
What's the difference between C and C++
I know that C++ has the concept of objects but C doesn't. I also know that pretty much all there is to know about C fits into K & R but the C++ library is vastly more complex. There have got to be other big differences though. What are the major differences between C and C++?
Check out Stroustrup's FAQ here, specifically: What is the difference between C and C++? C++ is a direct descendant of C that retains almost all of C as a subset. C++ provides stronger type checking than C and directly supports a wider range of programming styles than C. C++ is "a better C" in the sense that it supports the styles of programming done using C with better type checking and more notational support (without loss of efficiency). In the same sense, ANSI C is a better C than K&R C. In addition, C++ supports data abstraction, object-oriented programming, and generic programming (see The C++ Programming Language (3rd Edition)"; Appendix B discussing compatibility issues is available for downloading).
640,721
640,740
Most used STL algorithm, predicates, iterators
I cannot find this question on stackoverflow. But I am wondering how people use STL (No fancy boost)... just an ol' fashion STL. Tricks/tips/mostly used cases acquired over many, many years... and perhaps gotchas... Let's share it... One tip per answer...with code example -- Edit is it such a bad question as it resulting in downvotes?
I use the STL in almost all of my projects, for things from loops (with iterators) to splitting up the input into a program. Tokenise an input string by spaces and input the result into an std::vector for parsing later: std::stringstream iss(input); std::vector<std::string> * _input = new std::vector<std::string>(); std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter<std::vector<std::string> >(*_input)); Other favourites off course are std::reverse and various other algorithms defined in <algorithm>.
640,731
640,842
Quick way to fill vector, map, and set, using stl functions
I want to fill these containers pretty quickly with some data for testing. What are the best and quick ways to do that? It shouldn't be too convoluted, and thus and inhumanly short, but also NOT to verbose Edit Guys I thought you can do something with memset knowning that vector has an underlining array? Also, what about map?
If you already have the initial data laying around, say in a C style array, don't forget that these STL containers have "2-iterator constructors". const char raw_data[100] = { ... }; std::vector<char> v(raw_data, raw_data + 100); Edit: I was asked to show an example for a map. It isn't often you have an array of pairs laying around, but in the past I have created a Python script that generated the array of pairs from a raw data file. I then #include this code-generated structure and initalized a map with it like this: #include <map> #include <string> #include <utility> using namespace std; typedef map<string, int> MyMap; // this array may have been generated from a script, for example: const MyMap::value_type raw_data[2] = { MyMap::value_type("hello", 42), MyMap::value_type("world", 88), }; MyMap my_map(raw_data, raw_data + 2); Alternatively if you have an array of keys, and and array of data values, you can loop over them, calling map.insert(make_pair(key, value)); You also ask about memset and vector. I don't think there is any real merit to using memset to initialize a vector, because vectors can be given an initial value for all their elements via the constructor: vector<int> v2(100, 42); // 100 ints all with the value of 42 vector<string> v(42, "initial value"); // 42 copies of "initial value"