question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,938,939
1,938,986
Get File Last Modify Time and Compare
I want a piece of function which will take a file and last how many days, if it was older than that date, will return 0 otherwise 1... Something like that... For example: int IsOlder(TCHAR *filename, int days) { do operation. If last modify date was older than days variable return 0 else return 1 } It's MS VC++ 6 f...
Windows has an API function called GetFileTime() (doc on MSDN) taking a file handle in parameter and 3 FILETIME structures to be filled with date-time info: FILETIME creationTime, lpLastAccessTime, lastWriteTime; bool err = GetFileTime( h, &creationTime, &lpLastAccessTime, &lastWriteTime ); if( !err )...
1,939,284
1,939,329
How to convert string (containing double max) to double
I have no problem converting "normal" double values, but I can't convert numeric_limits<double>::max() or DBL_MAX string representations? std::string max = "1.79769313486232e+308"; std::istringstream stream(max); double value; // enters here, failbit is set if (!(stream >> value))
Could it be something like the actual value of DBL_MAX isn't exactly representable in exponential notation with 16 decimal places (say the decimal value is very slightly larger than the two based represenation) but initializing a double with the DBL_MAX will nevertheless set the correct value (due to rounding). std::is...
1,939,473
1,941,977
How to organize sources of complex program?
We're creating very complex embedded system and «sources» contains few projects of Visual C++, IAR, Code Composer Studio and Altium Designer schemes and pcbs. All of that possibly could be in few versions. So, what practice could you advice me to arrange all that stuff? Thank you
I have the same setup as you. I use Altium Designer for the hardware schematics and PCB design. But I also have Firmware source files and related utilities. And I have mechanical design files. Here's how I do it: Project Name Firmware MainCpu trunk tags branches ...
1,939,475
1,962,504
Wide to narrow characters
What is the cleanest way of converting a std::wstring into a std::string? I have used W2A et al macros in the past, but I have never liked them.
The most native way is std::ctype<wchar_t>::narrow(), but that does little more than std::copy as gishu suggested and you still need to manage your own buffers. If you're not trying to perform any translation but just want a one-liner, you can do std::string my_string( my_wstring.begin(), my_wstring.end() ). If you wan...
1,939,556
1,939,663
overloading operator delete, or how to kill a cat?
I am experimenting with overloading operator delete, so that I can return a plain pointer to those who don't wish to work with smart pointers, and yet be able to control when the object is deleted. I define a class Cat that is constructed with several souls, has an overloaded operator delete that does nothing, and dest...
operator delete calls the object destructor and after that you are in no man's land. As others pointed out, what you are trying to do is not possible. What you are doing is also a bit dodgy in the way of inconsistent behaviour when the object is constructed on the heap and on the stack. With your idea to override opera...
1,939,848
3,809,238
Linkage issue when using Poco C++ 1.3.6 for iPhone Xcode project
I managed to compile Poco C++ 1.3.6 library for iPhone by the following commands: ./configure --config=iPhone --no-tests --omit=Data,Cryptor,NetSSL_OpenSSL ./make Then I created a new view-based Application for iPhone and add Header search paths and changed my .m file to .mm. And then I added the newly compiled .a f...
Define POCO_STATIC in your project. Apparently, unless POCO_STATIC is defined, Poco headers attempt to use the dynamic libraries.
1,939,853
1,939,866
Storing a Type as a Variable? for a templated class?
i have a templated class, with the following definition: ImageRescaleDepth<PIXEL_TYPE_INPUT, PIXEL_TYPE_OUTPUT> This class uses templates, for pretty much everything since its supposed to be generic. Anyways i need to make a command line version of this application, to do image rescaling, currently the system is setup...
No, the type of a template class must be known at compile time, so the image types types have to be supplied to the template then. I have to say, that if this class is intended to perform conversions between many different formats, the use of template parameters to specify the conversion smacks of very poor design.
1,939,864
1,946,431
Storing a lua class with parent in luabind::object
Using C++, lua 5.1, luabind 0.7-0.81 Trying to create a lua class with parent and store it in a luabind::object. Lua class 'TestClassParent' function TestClassParent:__init() print('parent init\n') end function TestClassParent:__finalize() print('parent finalize\n') end class 'TestClass' (TestClassParent) f...
This is a known bug in 0.8.1; a reference to the last constructed object is left in the "super" function upvalue. It has been fixed in 0.9-rc1: http://github.com/luabind/luabind/commit/2c99f0475afea7c282c2e432499fd22aa17744e3
1,939,899
1,941,092
How do I make an unreferenced object load in C++?
I have a .cpp file (let's call it statinit.cpp) compiled and linked into my executable using gcc. My main() function is not in statinit.cpp. statinit.cpp has some static initializations that I need running. However, I never explicitly reference anything from statinit.cpp in my main(), or in anything referenced by it. W...
It is not exactly clear what the problem is: C++ does not have the concept of static initializers. So one presume you have an object in "File Scope". If this object is in the global namespace then it will be constructed before main() is called and destroyed after main() exits (assuming it is in the application). If t...
1,939,953
1,939,971
How to find if a given key exists in a C++ std::map
I'm trying to check if a given key is in a map and somewhat can't do it: typedef map<string,string>::iterator mi; map<string, string> m; m.insert(make_pair("f","++--")); pair<mi,mi> p = m.equal_range("f");//I'm not sure if equal_range does what I want cout << p.first;//I'm getting error here so how can I print what is...
Use map::find and map::end: if (m.find("f") == m.end()) { // not found } else { // found }
1,940,394
4,577,973
DDD debugger: save A command history between sessions
I noticed that my command history remains only during the current session, and once I re-start ddd, say with the same process, it starts with a clean slate. Is there way I can force the latest history to persist/reload. I couldn't find any relevant options in Edit-> Preference/GDB sessions. I am using GNU DDD 3.3.9 (...
I am not using DDD. Am using GDB command line on an ubuntu box. This answer may be useful to those who want to save their gdb history within sessions: As per the documentation available: here, history saving is disabled by default. To enable it and to do so everytime I run gdb, I did the following: Edited ~/.bashrc fi...
1,940,652
1,941,250
Dynamically inserting strings to a std::map
I am trying to create a map of file pairs... First I am searching a specified directory for files using the FindFirstFile and FindNextFile and when a file is found I search the map to see if the associated file is there. If the other file was added to the map, the new found file is inserted beside the previously found ...
You have two files. {X} and {X}.a You want to search some directory space and store which ones you find. Let us store the information of a find in a std::pair<bool,bool>. The first value represents if we find {x} the second value represents if we find {X}.a These pair values are stored in a map using {X} as the index i...
1,940,747
16,592,552
Calling Excel/DLL/XLL functions from C#
I have a particular function in an Excel addin(xll). The addin is proprietary and we do not have access to the source code. However we need to call some functions contained within the addin and we would like to call it from a C# program. Currently, I was thinking of writing a C++ interface calling the Excel function wi...
You need to create a fake xlcall32.dll, put it in the same directory as your XLL (do not put excel's own xlcall32.dll in the PATH). Here is some code: # include <windows.h> typedef void* LPXLOPER; extern "C" void __declspec(dllexport) XLCallVer ( ) {} extern "C" int __declspec(dllexport) Excel4 (int xlfn, LPXLOPER o...
1,940,787
1,940,813
Which IDE should I use for this art project?
I have an art project that will require processing a live video feed to use as the basis of a particle system, which will be rendered using OpenGL and projected on a stage. I have a CUDA enabled graphics card, and I was thinking it would be nice to be able to use that for the image and particle system processing. This...
As far as the CUDA or OpenGL support is concerned you are fine with either of them. The nVidia examples are also multiplatform. The real question is if you plan on using any GUI Toolkit as there are a only a few choices that are really portable. In the end I'd recommend going with what you feel more comfortable with or...
1,940,846
1,940,862
Binary files and cross platform compatibility
I have written a C++ library that saves my data (a collection of custom structs etc) into a binary file. I currently use (i.e. create and consume) the files locally, on my Windows (XP) machine. For simplicity, lets think of the library in two parts: a writer (Creates the files) and a reader or consumer (simply reads da...
For the files to be binary compatible: endianness must match (as it does for you) bitfield packing order must be the same sizes and signedness of types must be the same the compiler must make the same decisions about padding and alignment It's certainly possible for all of these conditions to be fulfilled, or for you...
1,941,064
1,941,127
Should I preallocate std::stringstream?
I use std::stringstream extensively to construct strings and error messages in my application. The stringstreams are usually very short life automatic variables. Will such usage cause heap reallocation for every variable? Should I switch from temporary to class-member stringstream variable? In latter case, how can I re...
Have you profiled your execution, and found them to be a source of slow down? Consider their usage. Are they mostly for error messages outside the normal flow of your code? As far as reserving space... Some implementations probably reserve a small buffer before any allocation takes place for the stringstream. Many im...
1,941,443
1,943,631
CMake linking against shared library on windows: error about not finding .lib file
I've got a library definition in CMake that builds a shared library out of a small set of files, and I've got it compiling just fine on both linux and windows. However, I've also got another library that links against the shared library and it works fine on linux, however, on windows I get a message along the lines or ...
Ah, my problem was I forgot to include a __declspec(dllexport) in suitable places when building the library (can you tell I don't do windows programming a lot?).
1,941,487
1,941,510
C++ templating question regarding comparators
Probably a very newb C++ question. Say I have a class, vertex, with several properties and methods. I want to stuff a bunch of vertices into a queue, and have them ordered by a special property on the vertex class (doing a basic Dijkstra graph algo for school yes). I'm having some problems penetrating the C++ syntax ho...
replace std::less<benchmark::vertex*> with any function or functor that takes two vertex pointers as parameters and returns true iff the first parameter belongs before the second. std::less<benchmark::vertex*> is going to compare the two pointers, so the result you have seen shows their order in memory.
1,941,517
1,941,629
Explicitly disallow heap allocation in C++
I have a number of classes that I would like to explicitly disallow heap allocation for. It occurred to me this weekend that I could just declare operator new private (and unimplemented)... Sure enough, this results in compile errors when you attempt to new the class... My question is: Is there more to this? Am I missi...
Depends on what you mean with "explicitly disallow heap allocation". If you just want to prevent direct allocation on the heap, i.e.: NotOnTheHeap *n = new NotOnTheHeap(); it is good enough. But it will not prevent that your object exists on the heap in general. For example, it won't prevent people from using std::vec...
1,941,520
1,941,566
VS2008: No option to convert Win32 C++ project to x64?
I am running VS Team System 2008 on WinXP. I make a new Win32 C++ project (Empty project). I go to Build Configuration to add a configuration for x64. The only options I have are: - Pocket PC 2003 (ARMV4) - Smartphone 2003 (ARMV4) I have no option for x64 (or Itanium). However, if I make a C# project within the same so...
Maybe you didn't install the native x64 compiler. Try to run setup again, and look if you selected the native x64 C++ compiler.
1,941,777
1,942,114
Polymorphism and inheritance of static members in C++
I need to keep a list(vector) of children for every class, and I've got a tricky problem: class A { protected: int a; static vector<A*> children; public: A(int a): a(a) {;}; virtual void AddToChildren(A* obj); virtual void ShowChildren(); virtual void Show(); }; class B: public A { protected...
Your design intent is not sufficiently clear, which is why the authors of some other answers got confused in their replies. In your code you seem to make calls to AddToChildren from some constructors but not from the others. For example, you have a children list in A but you never call the AddToChildren from A::A const...
1,941,818
1,968,351
ICU Custom Currency Formatting (C++)
Is it possible to custom format currency strings using the ICU library similar to the way it lets you format time strings by providing a format string (e.g. "mm/dd/yyy"). So that for a given locale (say USD), if I wanted I could have all currency strings come back "xxx.00 $ USD".
See http://icu-project.org/apiref/icu4c/classDecimalFormat.html, Specifically: http://icu-project.org/apiref/icu4c/classDecimalFormat.html#aadc21eab2ef6252f25eada5440e3c65 For pattern syntax see: http://icu-project.org/apiref/icu4c/classDecimalFormat.html#_details I didn't used this but from my knowledge of ICU this is...
1,942,550
1,942,622
dedicated thread for io_service::run()
I want to provide a global io_service that is driven by one global thread. Simple enough, I just have the thread body call io_service::run(). However, that doesn't work as run (run_one, poll, poll_one) return if there is no work to do. But, if the thread repeatedly calls run(), it will busy loop when there is nothin...
You need to create an io_service::work object. See this section of the documentation: Stopping the io_service from running out of work
1,942,596
1,942,803
Implementing windows hooks using NativeWindow properly
I dont have much of a C++ background but have successfully hooked a window and converted its msgs into raised events that my application can consume, Ive started by inheriting from NativeWindow and overriding WndProc and have determined the msgs that im interested in, WM_VSCROLL and WM_HSCROLL for instance. Firstly are...
I assume you are talking about hooking a window in another application. That's a non-trivial problem, the wparam and lparam arguments may contain pointers instead of simple values. Those pointers are however only valid in the virtual memory space of the process who's window you hooked. Ignoring this will buy you an ...
1,942,725
1,942,768
Boost Test Fixture object clearing between tests
I am having a issue with boost unit testing. Basically I create a fixture which is part of a suite to unit test a Resource cache. My main issue is between tests the Resource cache is becoming empty. So the first test that tests the cache passes then the second one will fail because the data the first test inserted i...
It is intended. One of the key principles of unit testing is that every test is run in isolation. It should be given a clean environment in which to run, and that environment should be cleaned up again afterwards, so that tests do not depend on each others. With Boost.Test, you can specify which tests to run from the c...
1,942,855
1,942,895
Any new stuff in libpng 1.4 series?
What is new in the soon to be released libpng 1.4 series? The DLL is almost twice the size of 1.2.41
The many changes are listed here, starting with the line version 1.4.0beta1 [April 20, 2006]
1,943,228
1,943,497
implicit constructor conversion works on explicit vector::vector, only sometimes
I like to initialize 2-dimensional arrays as vector<vector<int> >(x,y). x is passed to vector<vector<int> >'s constructor and y is passed to vector<int>'s constructor, x times. Although this seems to be forbidden by C++03, because the constructor is explicit, it always works, even on Comeau. I can also call vector::ass...
Your assumption about Comeau implicitly calling an explicit constructor is most likely incorrect. The behavior is indeed broken, but the problem is different. I suspect that this is a bug in the implementation of Standard Library that comes with Comeau, not with core Comeau compiler itself (although the line is blurry ...
1,943,276
1,943,382
What does '&' do in a C++ declaration?
I am a C guy and I'm trying to understand some C++ code. I have the following function declaration: int foo(const string &myname) { cout << "called foo for: " << myname << endl; return 0; } How does the function signature differ from the equivalent C: int foo(const char *myname) Is there a difference between usin...
The "&" denotes a reference instead of a pointer to an object (In your case a constant reference). The advantage of having a function such as foo(string const& myname) over foo(string const* myname) is that in the former case you are guaranteed that myname is non-null, since C++ does not allow NULL references. Si...
1,943,383
1,943,491
Network Communication between a java socket (server) and a C++ socket (client)
I know this must be a pretty common problem, but I haven't been able to find a definitive answer on how to do it. First, assume we have a java server that accepts queries such as (I've just put the relevant lines, and I've taken out the exception handling for clarity): ServerSocket socket = new ServerSocket(port); ...
Here I put a simple code to connect to a server. It may help you if this is your problem. void client(const char* server_address, short server_port) { int sockfd; struct sockaddr_in servaddr; sockfd = socket(AF_INET, SOCK_STREAM, 0); memset(&servaddr, 0x00, sizeof(servaddr)); servaddr.sin...
1,943,471
1,943,543
Access data passing through the networkcard using C++
Is there a way to control the data coming from the internet from specific address through the network card before it received by the kernel of the operating system using C++ or any language? In another word, Is there a way to access OSI Seven Layer Model using C++ to control the data passing through any layer of the s...
Device driver is what sits between between hardware and kernel so this is your only choice. It depends of the OS but one can write a device driver in C++ for all the major ones. Be ready to encounter plain C interface though.
1,943,481
1,943,513
How come I am getting weird results with istream::get(char*, streamsize n, char delim)?
I am reading in a file with a format similar to: TIME, x, y, z 00:00:00.000 , 1, 2 , 3 00:00:00.001 , 2 , 3 , 4 etc, and code similar to the following: std::ifstream& istream; char buffer[15]; double seconds, hours, mins; // initialised properly in real code // to read in first column istream.get(buffer, 14, ','); i...
You have read a blank line, or you are trying to read past the end of the file. The first character is \0, which signifies the end of the string. Any characters after that are untouched memory.
1,943,753
1,943,766
Eclipse & C/C++ - do I need to install a compiler separately?
I'm starting to learn C, and installed the eclipse plugin for C/C++ development (the CDT plugin). I'm testing the setup with a hello world program, but it looks like the eclipse C plugin (CDT) doesn't have a compiler built in. I thought eclipse plugins were usually self-sufficient? Do I need to install a compiler separ...
On OS X, you can install Xcode from your installation CD to get the gcc compiler, or in [Li|U]nix you probably already have gcc installed. If you're on Windows check out MinGW. Thats a free C/C++ compiler based on gcc.
1,943,830
1,943,850
Managing destructors of managed (C#) and unmanaged (C++) objects
I have a managed object in a c# dll that maintains an anonymous integer handle to an unmanaged object in a c++ dll. Inside the c++ dll, the anonymous integer is used in an std::map to retrieve an unmanaged c++ object. Through this mechanism, I can maintain a loose association between a managed and unmanaged object usin...
You may be able to solve this quickly by checking Environment.HasShutdownStarted in the finaliser of your C# object (and not calling into the C++ DLL / deleting the C++ object if HasShutdownStarted is true). If you are not in the main AppDomain then you might need to check AppDomain.Current.IsFinalizingForUnload inste...
1,943,847
1,943,871
Declaring a function static and later non-static: is it standard?
I noticed a very curious behavior that, if standard, I would be very happy to exploit (what I'd like to do with it is fairly complex to explain and irrelevant to the question). The behavior is: static void name(); void name() { /* This function is now static, even if in the declaration * there is no static key...
C++ standard: 7.1.1/6: "A name declared in a namespace scope without a storage-class-specifier has external linkage unless it has internal linkage because of a previous declaration" [or unless it's const]. In your first case, name is declared in a namespace scope (specifically, the global namespace). The first ...
1,943,973
1,944,022
Installing msvcr90.dll easy way! (without C++ Redistributable Package)
My program is a converted python file to exe file. The problem with this exe file is that it does not run without python installed and it only needs mscvr90.dll! I don't want to install C++ Redistributable Package just for this dll file! That big fat package! If I copy this msvcr90.dll to my application folder it just ...
The VCRT libraries are hardly a 'big fat' package. I'm looking at them now and they're just over 2mb - almost nothing. That said the only real way to circumvent the SxS linking would be to change the manifest of the executable that is linking to the files. You can use Visual Studio to open the .exe and edit the manif...
1,944,321
1,944,339
open failed: No such file or directory
I have built a standalone executable which references my .so object. both are in the same directory. when I try to run executable it gives me the following error: ld.so.1: myExec: fatal: libMine.so: open failed: No such file or directory what am I doing wrong?
Unix systems don't look in the current directory for .so files automatically. You can get around this for development by setting LD_LIBRARY_PATH, but during the normal installation they should be installed in the appropriate place on the system. See also why you shouldn't make your users use LD_LIBRARY_PATH
1,944,609
1,944,630
C++ Array Constructor
I was just wondering, whether an array member of a class could be created immediately upon class construction: class C { public: C(int a) : i(a) {} private: int i; }; class D { public: D() : a(5, 8) {} D(int m, int n) : a(m,n) {} private: C a[2]; }; As far...
Arrays -- a concept older than C++ itself, inherited straight from C -- don't really have usable constructors, as you're basically noticing. There are few workaround that are left to you given the weird constraints you're mentioning (no standard library?!?!?) -- you could have a be a pointer to C rather than an array ...
1,944,621
1,944,648
Is there any method for multiplying matrices having O(n) complexity?
I want to multiply two matrices but the triple loop has O(n3) complexity. Is there any algorithm in dynamic programming to multiply two matrices with O(n) complexity? ok fine we can't get best than O(n2.81 ) edit: but is there any solution that can even approximate the result upto some specific no. of columns and rows...
The best Matrix Multiplication Algorithm known so far is the "Coppersmith-Winograd algorithm" with O(n2.38 ) complexity but it is not used for practical purposes. However you can always use "Strassen's algorithm" which has O(n2.81 ) complexity but there is no such known algorithm for matrix multiplication with O(n) c...
1,944,682
1,944,723
What is meant by delegates in C++?
What is mean by delegates in c++, does sort function in c/c++ which takes a compare function/functor as last parameter is a form of delegate?
"delegate" is not really a part of the C++ terminology. In C# it's something like a glorified function pointer which can store the address of an object as well to invoke member functions. You can certainly write something like this in C++ as a small library feature. Or even more generic: Combine boost::bind<> with boos...
1,944,717
1,944,806
linux distro for Embedded development?
I have an embedded board . Can someone suggest an Ideal Linux distro for such a configuration, keeping in mind that it also needs to capture images in realtime. I plan to use Qt_Embedded for application development on such a system.
You can get special distros of Linux that are specifically intended for embedded development from various companies. However, the board you are describing sounds like it might be a standard x86 board. Is it a Via C7, or an Atom, or something like that? If it is, you could totally just use Debian. With Debian, you ca...
1,944,971
1,945,507
How do you save data in MFC?
I still remember in Delphi, developer can just make the UI(textbox, listbox...) directly connect to database, and then when user click a button, just call the post action, then the data will be saved automatically. What I want to know is that is there any similar mechanism in MFC? Or I can use GetDlgItem(...).Text a...
In VC++ , you have to use Microsoft ActiveX Data Object Library (ADO typelib) . To store data you can follow these steps: 1.Retrive data from all controls 2.Validate the data retrived 3.Use sql query to store the data to database. You can use ODBC API which is independent of any database management system. http://m...
1,944,994
1,945,004
Notification when Windows Dialog is opened
I want to do some processing when a particular dialog is opened but I am not able to find any way to get notification when that dialog is opened. Is there any way to get notification in application for opening of a particular windows dialog? The only available information about the dialog is its title and its unique.
The general solution is to use windows hooks, filter to WH_CBT, filter to WM_CREATE, or something like that, get the window text and see if it is the one of your interest. One more important point: in hook you should use SetWindowLongPtr() to set window process to your own function, that will actually receive WM_CREATE...
1,945,232
1,945,301
How to set toolbar button height?
When adding buttons to a toolbar (using the old Windows API) I can't seem to find a way to change the height of a button. I need to be able to increase the button's height because I'm using large icons. I'm currently painting everything myself using custom draw because I wanted to be able to have icons with different w...
Have you tried the TB_SETBUTTONSIZE message? // hWndToolbar is a handle to the toolbar window. int width = 32, height = 32; SendMessage(hWndToolbar, TB_SETBUTTONSIZE, 0, MAKELPARAM(width, height);
1,945,584
1,945,605
GetOpenFileName() kills my background open streams :(
Its a little strange. Ok so I am working with OGRE game engine which has a "SceneManager" class which keeps some files streams open in background. If i use those streams just BEFORE using GetOpenFileName() those streams work fine, but if I try to use those streams AFTER GetOpenFileName() those strams are found to be cl...
Note that GetOpenFileName() can and will change the current directory of your whole process. This might be interfering with whatever else you have going on. There is an option called OFN_NOCHANGEDIR, but according to the documentation, it's ineffective: Restores the current directory to its original value if the user ...
1,945,846
1,945,866
What should go into an .h file?
When dividing your code up into multiple files just what exactly should go into an .h file and what should go into a .cpp file?
Header files (.h) are designed to provide the information that will be needed in multiple files. Things like class declarations, function prototypes, and enumerations typically go in header files. In a word, "definitions". Code files (.cpp) are designed to provide the implementation information that only needs to be kn...
1,946,067
1,946,127
Visual C++ 2008 Issues
Okay, this is getting stupid, I have Microsoft Visual Studio 2008, was working fine, now whenever I run a .cpp program my command prompt windows has a default color of gray when I initially had lime green for the output. Error Message: 'Testing.exe': Loaded 'C:\Users\codebox\Documents\Visual Studio 2008\Projects\Testin...
There's no error... the messages you reported are just VC++ notifying you about which dlls are loaded, which debug symbols are available, etc. The last line tells you that the program terminated with return code 0. If you don't see your program running it's just because it's very fast, and at its end the console automa...
1,946,092
1,946,152
What could this curious combination of "while" and "delete" mean?
Reviewing a quite old project I found the following curious code snippet (only relevant code extracted): class CCuriousClass { ~CCuriousClass(); CSomeType* object; }; CCuriousClass::~CCuriousClass() { while( object != NULL ) { delete object; } } Have I overseen anything or is it a plain road t...
Since your question seems to imply "What could somebody have meant with this?" and not "Why is this a fantastic idea?" I suggest the following: class CSomeType { CCuriousClass* m_plistentry; CSomeType* m_pnext; ~CSomeType() { m_plistentry->object = m_pnext; } }; The basic idea could have been ...
1,946,153
1,946,170
Need Good C++ Libraries For Strings & HTTP Streams
I'll soon be starting a project of mine that heavily involves reading and interacting with websites. So I'd like to start pulling in some decent libraries to cut down on some of the dirty work that needs to be done in C++. Thus far I've found 'The Better String Library' for string manipulation. Any other suggestions?
If the features provided by std::string are not enough, you can have a look at pystring. Pystring is a collection of C++ functions which match the interface and behavior of python's string class methods using std::string. Implemented in C++, it does not require or make use of a python interpreter. It provides convenie...
1,946,445
1,946,485
C/C++: How to use the do-while(0); construct without compiler warnings like C4127?
I'm often use do-while(0) construct in my #defines, for the reasons described in this answer. Also I'm trying to use as high as possible warning level from compiler to catch more potential problem and make my code more robust and cross-platform. So I'm typically using -Wall with gcc and /Wall with MSVC. Unfortunately M...
Summary: This warning (C4127) in this particular case is a subtle compiler bug. Feel free to disable it. In depth: It was meant to catch situations when logical expression evaluates to a constant in non-obvious situations (such as, if(a==a && a!=a), and somehow, it turned while(true) and other useful constructs into in...
1,946,830
1,946,866
Multidimensional variable size array in C++
hi I want to do something like this: int op(string s1, string s2){ int x = s1.size(); int y = s2.size(); int matrix = new int[x][y] /* do stuff with matrix */ } For some reason I get the following errors: SuperString.cpp(69) : error C2540: non-constant expression as array bound SuperString.cpp(69) : er...
Here is a summary of how to build a 2d array in C++ using various techniques. Static 2D Matrix: const size_t N = 25; // the dimension of the matrix int matrix[N][N]; // N must be known at compile-time. // you can't change the size of N afterwards for(size_t i = 0; i < N; ++i) { for(size_t j = 0; j < N; ++j) {...
1,947,014
1,947,043
How add objects dynamically
This is the question : How to do IT Right ? IT = add objects dynamically (mean create class structures to support that) class Branch { Leaves lv; //it should have many leaves!! } class Tree { Branch br; //it should have many branchs!!! } Now a Non-Working Example (neither is...
std::vector is the thing, you are looking for, I guess... class Tree { std::vector<Branch> branches; };
1,947,654
1,947,674
Pointing to the first object in a linked list, inside or outside class?
Which of these is a more correct way to store the first object in a linked list? Or could someone please point out the advantages/disadvantages of each. Thanks. class Node { int var; Node *next; static Node *first; Node() { if (first == NULL) { first = this; ...
It's most usual to have a separate List class and a separate Node class. Node is usually very simple. List holds a pointer to the first Node and implements the various list operations (add, remove, find and so on). Something like the following class List { public: List() { first = new Node(); } void inser...
1,947,682
1,947,710
Is boost tuple mutable?
I have been using a using a boost tuple as the value in an STL map. Up until now, I only had to construct the tuple and insert into the map and at a later stage retrieve the values. Now I need to be able to change the tuple in the map. Is this possible, or have I run into the one place you should'nt be using tuples ins...
As long as the tuple is the map value and not the key, the tuple is perfectly mutable: http://www.boost.org/doc/libs/1_41_0/libs/tuple/doc/tuple_users_guide.html#accessing_elements
1,947,717
1,951,015
How to implement speech recognition and text-to-speech in C++?
I want to know about various techniques to do speech recognition and text to speech conversion. Also please let me know about any resources like links, tutorials ,ebooks etc. on it. Which is the most efficient technique to achieve it ?
I'm going to answer the part about speech recognition (since I don't know much about text-to-speech): http://ecx.images-amazon.com/images/I/4190SZC61CL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg This book, "Statistical Methods for Speech Recognition" is a classic that explains the ...
1,947,752
1,947,874
How to handle required default constructor
In writing a copy constructor for one of my classes ( which holds a few objects of other UDTs ), I am required to create a default constructor for those UDTs, even though they were never really meant to have one. Is it fine to just implement a blank default constructor and be done with it? The only time the default con...
If you use an initializer list in the copy constructor, you don't need a default constructor: #include <iostream> using namespace std; class Foo { Foo(); /* no default constructor */ public: Foo(int i) { cout << "Foo constructor (int)" << endl; } Foo(const Foo& f) { cout << "Foo constructor (co...
1,947,971
1,951,011
Why is g++ saying 'no match for ‘operator=’ when there clearly is, and Visual Studio can see that there is?
I'm writing an interface library that allows access to variables within tables (up to a theoretically infinite depth) in an object of type regula::State. I'm accomplishing this by overloading operator[] within a class, which then returns another of that same class, and calls operator[] again as needed. For example: reg...
Section 5.17 of the ISO standard says There are several assignment operators, all of which group right-to-left. All require a modifiable lvalue as their left operand, and the type of an assignment expression is that of its left operand. The result of the assignment operation is the value stored in the left operand aft...
1,947,976
1,948,085
Function Pointer Calls
Let's say there is an imaginary operating system... There is a function in it called settime that gets a pointer to function and a timestamp. The catch is that every time the function is called it runs over the last call (so only the new function being provided as parameter will be called). I want to expose a new funct...
Working under the assumption that the function that gets called is called at a specific time... What settime2 needs to do is keep a linked list of function pointers and timestamp values. Insert a new function/timestamp value into the list in sorted order: earliest first. Use settime to set up a generic handler function...
1,948,032
1,948,445
hashing a dictionary in C++
hi I want to use a hashmap for words in the dictionary and the indices of the words in the dicionary. What would be the fastest hash algorithm for this? Thanks!
At the bottom of this page there is a section A Note on Hash Functions with some information which you might find useful. For convenience, I'll just replicate some links here: Bob Jenkins Paul Hsieh Fowler/Noll/Vo (FNV) MurmurHash
1,948,204
1,948,337
Two static libs, two different vector implementations, what would the linker do?
Imagine that we have two static libraries built with different implementations of std::vector. Both of these binaries would have the code for both push_back and pop_back (since vector is usually header only). What would the linker do when we tried to use both of these libraries in a project. Would it give an error? Co...
Would it give an error? Depends on how you define "error". It probably would not give you an error at link-time. But it would certainly corrupt your executable. The linker assumes, when it encounters multiple definitions of a symbol, that they are identical, and so all but one of them can be discarded. If they're not i...
1,948,467
1,949,047
About pointer and reference syntax
Embarrassing though it may be I know I am not the only one with this problem. I have been using C/C++ on and off for many years. I never had a problem grasping the concepts of addresses, pointers, pointers to pointers, and references. I do constantly find myself tripping over expressing them in C syntax, however. N...
I found the right-left-right rule to be useful. It tells you how to read a declaration so that you get all the pointers and references in order. For example: int *foo(); Using the right-left-right rule, you can translate this to English as "foo is a function that returns a pointer to an integer". int *(*foo)(); // ...
1,948,745
2,282,975
Boost Property Tree with filename as key
I am trying to use filenames as the key in boost::PropertyTree However, the '.' character in a filename such as "example.txt" causes an additional layer to be added within the property tree. The most obvious solution would be to replace '.' with another character, but there is likely a better way to do this, such as w...
The problem was that the documentation was outdated. A path type object must be created as follows, with another character that is invalid for file paths specified as the delimiter as follows: pt.put(boost::property_tree::ptree::path_type("example.txt", '|'), 10); I found a path to the solution from the boost mailing ...
1,948,865
1,948,974
How to turn type-labeled tokens into a parse-tree?
So I'm writing a programming language in C++. I've written pretty much all of it except for one little bit where I need to turn my tokens into a parse tree. The tokens are already type labeled and ready to go, but I don't want to go through the effort of making my own parse tree generator. I've been looking around for ...
Depending on what exactly your requirements are, Boost.Spirit might be an alternative. Its modular, so you should be able to use only components of it as well.
1,949,046
1,949,154
Subscribe a button to trigger some function dynamically in C++?
I'm trying to make a button class (abstract) so I can set what function is that button going to trigger when clicked dynamically when my program load. I want to construct all my buttons by reading XML files, this is to avoid code replication so having only 1 "generic" button class is really useful for me. I was wonderi...
Since pointer to function is a runtime artifact you cannot store that in the offline configuration. I see two solutions that might fit what you describe: put your functions into a dynamic library and load them by name - that way your configuration would map a button to library path/function name pair, build a "registr...
1,949,117
1,949,277
Upcasting pointer reference
I have the following contrived example (coming from real code): template <class T> class Base { public: Base(int a):x(a) {} Base(Base<T> * &other) { } virtual ~Base() {} private: int x; }; template <class T> class Derived:public Base<T>{ public: Derived(int x):Base<T>(x) {} Derived(Derived<T>* &other): B...
Base<T> is a base type of Derived<T>, but Base<T>* is not a base type of Derived<T>*. You can pass a derived pointer in place of a base pointer, but you can't pass a derived pointer reference in place of a base pointer reference. The reason is that, suppose you could, and suppose the constructor of Base were to write s...
1,949,234
1,982,714
Remote developing with Eclipse
I'm trying to set-up a remote C++ development with Eclipse Galileo, but just can't make it work. Trying the NetBeans 6.8 worked almost out of box, as described in this article: http://netbeans.org/kb/docs/cnd/remotedev-tutorial.html Is there any good article or tutorial, explaining how to setup such environment with Ec...
I tried it a few months back but it didn't work for me either. Instead I use X-windows to open Eclipse from a remote linux box onto my Mac. This works well in office ( both machines are on a LAN in the same geographical location), but not from home. When working from home use emacs-gui to do the same things. Its not th...
1,949,237
1,949,319
Malloc call on delete[] showing up as memory leak in totalview
I am using HDF5 to read a string into a char* allocated by new[]. I then use a string::assign() call to copy this data to where I actually want it. I then call delete[] on that char*. This is showing up as the source of a memory leak using totalview. It shows mangled calls in stdlibc++ under delete[] to replace_saf...
It should be fine: But I would suggest using std::vector rather than newing an array of char: std::vector<char> x(len+1); strcpy(&x[0], getenv("PATH")); The reason I would do this is that the method assign() can potentially throw an exception. As such the delete may not be called and thus you could leak in the presen...
1,949,271
1,949,324
Would you use num%2 or num&1 to check if a number is even?
Well, there are at least two low-level ways of determining whether a given number is even or not: 1. if (num%2 == 0) { /* even */ } 2. if ((num&1) == 0) { /* even */ } I consider the second option to be far more elegant and meaningful, and that's the one I usually use. But it is not only a matter of taste; The actu...
If you're going to say that some compilers won't optimise %2, then you should also note that some compilers use a ones' complement representation for signed integers. In that representation, &1 gives the wrong answer for negative numbers. So what do you want - code which is slow on "some compilers", or code which is wr...
1,949,470
1,949,488
how to look up hash_map in C++?
Here's what I have, I am new to C++ so I am not sure if this is right... typedef pair<string, int>:: make_pair; hash_map <string, int> dict; dict.insert(make_pair("apple", 5)); I want to give my hash_map "apple", and I want to get back 5. How do I do it?
hash_map is not standard C++ so you should check out the documentation of whatever library you're using (or at least tell us its name), but most likely this will work: hash_map<string, int>::iterator i = dict.find("apple"); if (i == dict.end()) { /* Not found */ } else { /* i->first will contain "apple", i->second wil...
1,949,544
1,949,617
Are all members of following structs and arrays initialized with zero?
Furthermore, is there a difference between the initialization of the variables one and two, and the initialization of the varibles three and four? Background of the Question is, that i get an compiler error in Visual Studio 6.0 with the initialization of variable two and four. With Visual Studio 2008 it compiles well. ...
Yes, all of them a required to be initialized with 0 by the language standard (C++98). Visual Studio 6 is known not to perform the proper handling of {} case: it doesn't even support {} syntax, if I remember correctly. However, Visual Studio 6 is a pre-standard compiler. It was released before the C++98 standard came...
1,949,580
1,949,719
How do I make a full screen scrolling messagebox or window?
First let me start of saying I know absolutely nothing about c++ and I am really just more interested in getting this to work then learning c++(I got enough on my plate to learn). So basically I am trying to make a terms of service for my windows mobile 6 professional application but it seems I need to use c++ to do it...
I'd probably create a DialogBox with the TOS text in a TextBox on it. That way you can take advantage of the fact that a TextBox automatically can do scrolling. You'd then use CreateDialog or DialogBox to do the actual display. A side bonus here is that you can use the resource editor for basic window layout. I know y...
1,949,752
1,949,768
How to know calculate the execution time of an algorithm in c++?
I want to test which data structure is the best by looking at the run-time performance of my algorithm, how do I do it? For example I already have a hashmap<string, int> hmp; assuming I have "apple" in my hashmap I want to know how long the following statement takes to execute: hmp["apple"]. How can I time it? Thanks!
First of all take a look at my reply to this question; it contains a portable (windows/linux) function to get the time in milliseconds. Next, do something like this: int64 start_time = GetTimeMs64(); const int NUM_TIMES = 100000; /* Choose this so it takes at the very least half a minute to run */ for (int i = 0; i < ...
1,949,808
1,950,134
Writing BLOB data to a SQL Server Database using ADO
I need to write a BLOB to a varbinary column in a SQL Server database. Sounds easy except that I have to do it in C++. I've been using ADO for the database operations (First question: is this the best technology to use?) So i've got the _Stream object, and a record set object created and the rest of the operation fal...
As far as ADO being the best technology in this case ... I'm not really sure. I personally think using ADO from C++ is a painful process. But it is pretty generic if you need that. I don't have a working example of using streams to write data at that level (although, somewhat ironically, I have code that I wrote usin...
1,950,003
1,950,047
Practice of having a "Common" header
By common I don't mean utility, I mean a header that holds enums that multiple types want to use, etc. For example, if multiple types can have a Color, which is an enum, you'd want to make that available. Some people would say to put it into the class that it "fits best with", but this can create header dependency issu...
I always use a Common.h file that almost never changes and contains definitions that are extremely likely to be needed in virtually all files. I think it increases productivity so that you don't have to open another .cpp file and copy the list of all the headers you know you'll definitely need. For example, here are tw...
1,950,127
1,950,208
Posixy way to launch browser?
Is there a 'Posixy' way to open an URL, preferrably in the default browser? I would like to do something like ShellExecute(0, _T("open"), url, 0, 0, SW_SHOWDEFAULT); that works on GNU/Linux and MAC. I read some answer saying that` if (fork() == 0) system("sensible-browser http://wherever.com"); does the trick on ...
On a Mac, you can just use the open command. open http://www.google.com from the Terminal opens a new Chrome tab for me. Just wrap that up in a system call.
1,950,160
2,141,415
what can I use to replace sleep and usleep in my Qt app?
I'm importing a portion of existing code into my Qt app and noticed a sleep function in there. I see that this type of function has no place in event programming. What should I do instead? UPDATE: After thought and feedback I would say the answer is: call sleep outside the GUI main thread only and if you need to wai...
It is not necessary to break down the events at all. All I needed to do was to call QApplication::processEvents() where sleep() was and this prevents the GUI from freezing.
1,950,413
1,950,573
How can I add an item to two queues and guarantee that it exists in both or none (multi-threaded)
I have the following problem. I have two classes, in this case A and B, which both own a concurrent_queue. The assumption here is that concurrent_queue is a thread-safe queue, with a blocking push() function. When an object is enqueued in B, it accesses the singleton A and it is queued up in A as well. This has the eff...
You'll need to atomicize your operation of "adding objects to both queues." You'll need a lock or some other kind of synchronization primitive around your two function calls. Same for removing items from the queues. boost::mutex looks fit for the job. You'll need a single instance and need it to be accessible from anyw...
1,950,489
1,950,670
Should you rely on another header for the headers it includes?
Assuming that all headers are guarded, let's say you had an abstract data type. #include "that.h" #include "there.h" class Foo { protected: // Functions that do stuff with varOne and varTwo private: that varOne; there varTwo; ... }; Then in the classes that inherit from foo ( and thus include foo.h ), would...
There is one downside to redundantly including header files that would otherwise have been included directly: it forces the compiler to reopen and reparse them. For example, in a.h: #ifndef __A_H #define __A_H // whatever #endif b.h: #ifndef __B_H #define __B_H #include "a.h" // whatever #endif c.cpp: #include "a.h"...
1,950,633
1,950,702
Thread-safe timezone-specific time display in C/C++
I have a multi-threaded application which needs to display certain dates to the user. The dates are stored using UTC Unix time values. However, the date must be displayed in the time zone of the user, not the local server time or UTC. Basically, I need a function like this: struct tm *usertime_r(const time_t *timer, st...
If you know the user's offset-from-UTC in seconds, you can just add/subtract that from the time_t and pass the result to gmtime_r. For example, Australian Eastern Daylight Time is +11, which means you'd add (11*3600) to the time value.
1,950,779
1,950,826
Is there any way to find the address of a reference?
Is there any way to find the address of a reference? Making it more specific: The address of the variable itself and not the address of the variable it is initialized with.
References don't have their own addresses. Although references may be implemented as pointers, there is no need or guarantee of this. The C++ FAQ says it best: Unlike a pointer, once a reference is bound to an object, it can not be "reseated" to another object. The reference itself isn't an object (it has no...
1,950,840
1,951,023
C++ Function Overloading Similar Conversions
I'm getting an error which says that two overloads have similar conversions. I tried too many things but none helped. Here is that piece of code CString GetInput(int numberOfInput, BOOL clearBuffer = FALSE, UINT timeout = INPUT_TIMEOUT); CString GetInput(int numberOfInput, string szTerminationPattern, BOOL clearBuffer ...
The problem is caused by the fact that you are supplying the timeout argument as a signed integer value, which has to be converted to an unsigned one for the first version of the function (since the timeout parameter is declared as UINT). I.e. the first version of the function requires a conversion for the third argum...
1,950,993
1,951,181
How do I get the position of a control relative to the window's client rect?
I want to be able to write code like this: HWND hwnd = <the hwnd of a button in a window>; int positionX; int positionY; GetWindowPos(hwnd, &positionX, &positionY); SetWindowPos(hwnd, 0, positionX, positionY, 0, 0, SWP_NOZORDER | SWP_NOSIZE); And have it do nothing. However, I can't work out how to write a GetWindowPo...
Try to use GetClientRect to get coordinates and MapWindowPoints to transform it.
1,951,007
1,951,043
what is the difference when the number of threads is determined and undetermined?
what the difference when the number of threads is determined, as e.g.: for (i*10){ ... pthread_create(&thread[i], NULL, ThreadMain[i], (void *) xxx); ... } and when it is undetermined, just like this: ... pthread_create(&threadID, NULL, ThreadMain, (void *) xxx); ... In my cas...
If the threads are doing the same tasks, they should use the same function (with different input maybe), so one ThreadMain is the correct way.
1,951,093
1,951,129
How can I check the failure in constructor() without using exceptions?
All of the classes that I'm working on have Create()/Destroy() ( or Initialize()/Finalized() ) methods. The return value of the Create() method is bool like below. bool MyClass::Create(...); So I can check whether initialization of the instance is successful or not from the return value. Without Create()/Destroy() I ...
If you don't want to use exceptions, there are two ways to let the caller know whether the constructor succeeded or not: The constructor takes a reference/pointer to a parameter that will communicate the error status to the caller. The class implements a method that will return the error status of the constructor. Th...
1,951,269
1,951,401
C: Where is union practically used?
I have a example with me where in which the alignment of a type is guaranteed, union max_align . I am looking for a even simpler example in which union is used practically, to explain my friend.
I usually use unions when parsing text. I use something like this: typedef enum DataType { INTEGER, FLOAT_POINT, STRING } DataType ; typedef union DataValue { int v_int; float v_float; char* v_string; }DataValue; typedef struct DataNode { DataType type; DataValue value; }DataNode; void myfunct() ...
1,951,509
1,951,530
g++: warning: integer constant is too large for ‘long’ type
What can I do (programmatically) to get rid of the warning? ... unsigned long long v=(unsigned long long)0xffffeeeeddddcccc; ... g++ main.cpp -o main main.cpp:6: warning: integer constant is too large for ‘long’ type but when I run the program everything is fine as expected: ./main sizeof(unsigned long long)==8 ...
According to C++ Standard 2.13.1/2: The type of an integer literal depends on its form, value, and suffix. If it is decimal and has no suffix, it has the first of these types in which its value can be represented: int, long int; if the value cannot be represented as a long int, the behavior is undefined. New C++ Stan...
1,951,519
1,951,547
When to use std::size_t?
I'm just wondering should I use std::size_t for loops and stuff instead of int? For instance: #include <cstdint> int main() { for (std::size_t i = 0; i < 10; ++i) { // std::size_t OK here? Or should I use, say, unsigned int instead? } } In general, what is the best practice regarding when to use std::s...
A good rule of thumb is for anything that you need to compare in the loop condition against something that is naturally a std::size_t itself. std::size_t is the type of any sizeof expression and as is guaranteed to be able to express the maximum size of any object (including any array) in C++. By extension it is also g...
1,951,573
1,951,585
C++ Function clarification
Given: x = MyFunc(2); My understanding: The variable x is assigned to the function MyFunc(2). First, MyFunc( ) is called. When it returns, its return value if any, is assigned to x.?
This cannot be answered completely without: x's declaration MyFunc's declaration MyFunc's definition But your sentence "When MyFunc(2) is called it returns the value 2 to x" is wrong. MyFunc is invoked and 2 is passed as the actual parameter value. MyFunc may return anything, which is then assigned to x.
1,951,735
1,951,767
C++ code runs with missing header, why?
I just realized that I am supposed to include the #include<cstdlib> required by abs() for the abs() function. #include<iostream> using namespace std; int main() { int result; result = abs(-10); cout << result << "\n"; return 0; } Why does this code still work, even tho...
That's because iostream indirectly includes definition for abs(). It is allowed by the Standard, but should not be relied upon, because it's implementation-dependant (i.e. your code may not compile on some other compilers).
1,951,741
1,952,685
invalid static assert behavior
I am trying to setup a static assert (outside the main function) with GCC v4.3.x: #define STATIC_ASSERT(cond) extern void static_assert(int arg[(cond) ? 1 : -1]) STATIC_ASSERT( (double)1 == (double)1 ); // failed but when I use float numbers, the assert always failed. Is it possible to run this static assert properly ...
C++ Standard 2003, 5.19 "Constant expressions", paragraph 1. In several places, C++ requires expressions that evaluate to an integral or enumeration constant: as array bounds (8.3.4, 5.3.4), as case expressions (6.4.2), as bit-field lengths (9.6), as enumerator initializers (7.2), as static member initi...
1,951,933
1,951,967
C++: auto_ptr + forward declaration?
I have a class like this: class Inner; class Cont { public: Cont(); virtual ~Cont(); private: Inner* m_inner; }; in the .cpp, the constructor creates an instance of Inner with new and the destructor deletes it. This is working pretty well. Now I want to change this code to use auto_ptr so I write: class I...
You need to include the header defining class Inner into the file where Cont::~Cont() implementation is located. This way you still have a forward declaration in teh header defining class Cont and the compiler sees class Inner definition and can call the destructor. //Cont.h class Inner; // is defined in Inner.h class ...
1,951,951
1,951,969
When including header files, is the path case sensitive?
Given this directory tree: src/MyLibrary/MyHeader.h src/file.cpp file.cpp: #include "mylibrary/myheader.h" ... Compiling file.cpp works with VS, fails in gcc. What does the standard say? If the path is case sensitive, why is this wise? What's the best practice, keep all file/folder names lowercase and thus do the s...
The case sensitivity depends on the Operating System. Windows is not case sensitive. Linux is. EDIT: Actually, as observed by Martin York's comment, the case sensitivity depends on the file system. By default Windows uses a case insensitive file system, while Linux uses a case sensitive one. For whoever is interested t...
1,952,049
1,952,111
Compile C code into Visual C++ dll?
Is it possible to compile C code into a Visual C++ dll? I'm looking at using some C code with a .Net project and trying to determine whether this is even an option. Thanks, Becky
Given that C++ is largely backward compatible with C, you should be able to recompile the code using the C++ compiler unless the code uses some C99 features. However, keep in mind that C++/CLI is not standard C++ so there might be additional issues. As aJ said, if you want to avoid the name mangling, you'll have to 'ex...
1,952,383
1,952,445
Interaction of namespace and friend in C++?
Is it possible to make a namespace friend of a class, say I have a unit test namespace with many classes and I wanted the test namespace to be friend to a class so that it has access to private implementation details.
No, this is not possible in C++. Frankly, it smacks of poor design.
1,952,471
1,953,347
Ampersand inside casting
I come across this code int n1 = 10; int n2 = (int &)n1; I don't understand the meaning of this casting, n2 is not reference since modifying n1 doesn't reflect n1. Strangely this code throws compiler error in gcc where as compiles fine in VC++. Anybody know the meaning of this casting?
Assuming n2 is of some built-in type, the cast to int & type performs the reinterpretation of lvalue n1 (whatever type it had) as an lvalue of type int. In the context of int n2 = (int &) n1 declaration, if n1 is by itself an lvalue of type int, the cast is superfluous, it changes absolutely nothing. If n1 is an lvalu...
1,952,900
1,954,215
Running C++ CGI Script As Background Process?
I'm working on an audio encoder cgi script that utilises libmp3lame. I'm writing in a mixture of C/C++. I plan to have an entry-point cgi that can spawn multiple encoding processes that run in the background. I need the encoding processes to be asynchronous as encoding can take several hours but I need the entry-point ...
You probably want the standard Unix daemon technique, involving a double fork: void daemonize(void) { if (fork()) exit(0); // fork. parent exits. setsid(); // become process group leader if (fork()) _exit(0); // second parent exits. chdir("/"); // just so we don't mysteriously prevent fs unmounts later close...
1,952,972
1,952,990
Does std::copy handle overlapping ranges?
When copying data from one range to another, you have to be careful if there's partial overlap between the source and destination ranges. If the beginning of the destination range overlaps the tail of the source range, a plain sequential copy will garble the data. The C run-time library has memmove in addition to mem...
It doesn't handle overlapping ranges if the beginning of the output range overlaps with the input range. Fortunately, you can use std::copy_backward instead (which requires that you don't overlap the end of the output range with the input range).
1,953,082
1,953,137
How can I find the largest (in size) of two integer types?
For instance: template <typename Type1, typename Type2> void fun(const Type1 &v1, const Type2 &v2) { largest<Type1, Type2>::type val = v1 + v2; . . . }; I'd like to know if there's a "largest" somewhere, perhaps in boost.
template<bool, typename T1, typename T2> struct is_cond { typedef T1 type; }; template<typename T1, typename T2> struct is_cond<false, T1, T2> { typedef T2 type; }; template<typename T1, typename T2> struct largest { typedef typename is_cond< (sizeof(T1)>sizeof(T2)), T1, T2>::type type; };
1,953,330
1,953,362
How do I set a breakpoint for operator() in gdb for C++?
I have 2 methods in C++ class as follows: class myClass { public: void operator()( string myString ) { // Some code } void myMethod() { ... } } For a regular method, I can simply set the breakpoint in GDB as: b myClass::myMethod But how do I set the breakpoint for the fi...
gdb will also take breakpoints at specific line numbers. For example b file.cc:45
1,953,552
1,956,055
Trouble finding key on hash_multimap search
I've done something wrong in defining my class which is causing Microsoft's implementation of the hash_multimap to "miss." Here is my class: class TimeParameter { public: TimeParameter(int _year, int _julianDay, int _hour) : m_Year(_year), m_JulianDay(_julianDay),...
This is the problem with rolling your own DateTime function. Not only has it been done ad nauseum but it is also a constant source of errors. I'd like to blame the project requirements but who am I really kidding? I didn't make the check of equals in the less than operators. So small, so stupid, and now, so very pub...
1,953,574
1,953,632
Seeking STL-aware c++filt
In my development environment, I'm compiling a code base using GNU C++ 3.4.6. Code is under development, and unfortunately crashes now and then. It's nice to be able to run the traceback through a demangler, and I use c++filt 3.4. The problem comes when functions have a number of STL parameters. Consider My_callback::o...
STLFilt simplifies and/or reformats long-winded C++ error and warning messages, with a focus on STL-related diagnostics. The result renders many of even the most cryptic diagnostics comprehensible.