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 for Windows. Thanks from now!
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 ) error The FILETIME structure is obfuscated, use the function FileTimeToSystemTime() to translate it to a SYSTEMTIME structure which is way easier to use: SYSTEMTIME systemTime; bool res = FileTimeToSystemTime( &creationTime, &systemTime ); if( !res ) error Then you can use fields wYear, wMonth, etc. to compare with your number of days.
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::istringstream may be a little bit more pickish. EDIT: Actually I found that the value of DBL_MAX in my compiler is 1.7976931348623158e+308 which works fine for me to stream. Your number is rounded and slightly larger, hence the failure. EDIT2: The exact value of DBL_MAX in decimal form is given by (2 ^ (1023 - 52)) * (2 ^ 53 - 1) which isn't representable with 16 decimal places.
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 IoCpu trunk tags branches Hardware MainPcb trunk tags branches IoPcb trunk tags branches PowerPcb trunk tags branches Mechanical Chassis trunk tags branches Other trunk tags branches This way all the project files are stored together in the SVN repository. The only down side I've found is that you can't just check out the Project and get the latest FW/HW/MEK files. You have to check out each Head of FW/HW/MEK. The reason for the separate sub-modules for FW/HW/MEK is that they will get separate version tags.
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 want actual encoding translation, you can use locales/codecvt or one of the libraries from another answer, but I'm guessing that's not what you're looking for.
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 destructor that decrements the number of souls (and also does some bragging). When souls reaches 0 the destructor calls the global ::delete, and the cat dies. This sounds quite simple, but does not work as expected. Here's the code: class Cat { public: Cat(string n): name(n), souls(9) { cout << "Myaou... " << name << " is born\n"; } ~Cat(); void operator delete(void *p) { cout << "!!! operator delete called\n"; } void report() { cout << name << "'s here, " << souls << " souls to spend\n"; } friend ostream& operator<< (const ostream& o, const Cat& cat); private: void kill(); const string name; int souls; }; Cat::~Cat() { cout << "!!! dtor called\n"; kill(); } void Cat::kill() { if (--souls) cout << name << " is still alive! I have " << souls << " souls left.\n"; else { cout << name << " is dying... good bye world!\n"; ::delete((void*)this); } } ostream& operator<< (const ostream& o, const Cat& cat) { return o << cat.name << "'s here, " << cat.souls << " souls to spend\n"; } here's the main: int main() { Cat *p = new Cat("Mitzi"); for (;;) { char c[100]; // cout << *p; p->report(); cout << "come on, hit me!"; cin >> c; delete p; } } I'd expect that the loop would run for 9 times, and then something unpleasant (crash) would happen. However, this is the output: Myaou... Mitzi is born Mitzi's here, 9 souls to spend come on, hit me!c !!! dtor called Mitzi is still alive! I have 8 souls left. !!! operator delete called 's here, 8 souls to spend come on, hit me!c !!! dtor called is still alive! I have 7 souls left. *** glibc detected *** /home/davidk/workspace/string_test/Debug/string_test: double free or corruption (fasttop): 0x080cd008 *** Seems that after the first delete the name member is destroyed, and the next delete causes a crash. Any explanations? I am compiling with gcc on Linux, can be a compiler bug? BTW, when I used the operator<<() as in cout << *p instead of repotr(), it was also weird: it entered an infinite loop of calling the constructor from within the operator<<(). What's going on here? :) thanks!
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 operator delete the object will stay alive depending on some internal logic (the number of lives has reached 9) if constructed using new. When constructed on the stack (Cat cat("Chesire cat");) the object will always get destructed when it goes out of scope. In order to achive what you are trying to do you will also need to change the bahaviour of the destructor to "stop destructing". This is not possible, also for very good reasons. So, if you want ref counting, just implement your own mechanism. After all, you can't call yourself a C++ programmer if you haven't done your own ref count memory management at least once :))
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 files into my Xcode project. When I hit "Build & Go", I encountered a few linkage errors such as: Poco::Zip::ZipArchieve .... Symbol(s) not found By using the same way I successfully compiled and linked my testing static library libtest.a. But I failed to link Poco C++ libraries. I don't know whether it's a bug or I missed something. Can anybody help? Thanks
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 to handle the following types: 1BIT, 2BIT, 4BIT, unsigned 8 bit, signed 8 bit, unsigned 16 bit, signed 16 bit, unsigned 32 bit, signed 32 bit, float, double. These are passed in by command line, and i convert them to an enum. I cannot modify the ImageRescaleDepth class since its part of a library. and i don't exactly want to create a giant switch or eliseif block, since there would be a 100 combinations. Is it possible, i can just somehow store these types as variables? Then pass them to the constructor?
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) function TestClass:__init() print('init\n') TestClassParent.__init(self) end function TestClass:__finalize() print('finalize\n') end C++ { luabind::object obj = luabind::call_function<luabind::object>(lua_state, "TestClass"); } printf("before GC\n"); lua_gc(lua, LUA_GCCOLLECT, 0); printf("after GC\n"); Output: init parent init before GC after GC Result: After obj is destroyed, 'TestClass' instance is still alive after garbage collection cycle (__finalize method is not called and memory is not freed). It's destroying only on program exit. Moresome if I use class without parent, garbage is collected correctly. If I try to use adopt policy (to take ownership of created object) luabind::object obj = luabind::call_function<luabind::object>(lua_state, "TestClass")[luabind::adopt(luabind::result)]; I get: in luabind 0.7 - same result as without adopt policy in luabind 0.81 - crash with message "you are trying to use an unregistrerd type" How can I correctly create a lua object in C++ and take it's ownership?
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. What happens (I suppose) is that the linked object created from statinit.cpp is never loaded on runtime, so my static initializations are never run, causing a problem elsewhere in the code (that was very difficult to debug, but I traced it eventually). Is there a standard library function, linker option, compiler option, or something that can let me force that object to load on runtime without referencing one of its elements? What I thought to do is to define a dummy function in statinit.cpp, declare it in a header file that main() sees, and call that dummy function from main(). However, this is a very ugly solution and I'd very much like to avoid making changes in statinit.cpp itself. Thanks, Daniel
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 this object is in a namespace then optionally the implementation can opt to lazy initialize the variable. This just means that it will be fully initialized before first use. So if you are relying on a side affect from construction then put the object in the global namespace. Now a reason you may not be seeing the constructor to this object execute is that it was not linked into the application. This is a linker issue and not a language issue. This happens when the object is compiled into a static library and your application is then linked against the static library. The linker will only load into the application functions/objects that are explicitly referenced from the application (ie things that resolve undefined things in the symbol table). To solve this problem you have a couple of options. Don't use static libraries. Compile into dynamic libraries (the norm nowadays). Compile all the source directly into the application. Make an explicit reference to the object from within main.
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 in p?
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 (i386-redhat-linux-gnu)
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 file to have the line "export GDBHISTFILE="$HOME/.gdb_history". This will save the history in this file. You may want to keep a size check on it which is described in the link. Edited ~/.gdbinit to have the lines: set history save on set history expansion on ran gdb When I quit and restarted gdb, I was able to access previous sessions commands. I use the vi mode in gdb (Esc + Enter) and doing a "Ctrl + r" shows me previous listings. Hope this helps.
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 one. If an associated file was not found, the new file is inserted to the map and its pair is left intact. To explain more: lets say we have 2 files file.1.a and file.1 those files represent a pair and thus should be added to the map as a pair //map<File w/o .a, File w .a> std::map<CString, CString> g_map; int EnumerateFiles(LPCTSTR Dir) { //Search Files.... //Found a File....(for ex: file.1) //Append .a to the string and search for it in the map BOOL bAdded = FALSE; for(std::map<CString, CString>::iterator itr = g_map.begin(); itr != g_map.end(); itr++) { if(StrCmp(tchAssocFile, itr->second) == 0) { bAdded = TRUE; //pair the string with the other one; } } if(!bAdded) //Add the new string to the map and leave its associate blank //Do the same in reverse if the associate was found first.... } I hope this was clear as I can't think of any other way to put it... sry. Can you please help in solving this issue... regards
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 into the map. #include <memory> #include <string> #include <map> typedef std::pair<bool,bool> FileInfo; typedef std::map<std::string,FileInfo> FileMapInfo; FileMapInfo fileMapInfo; void found(std::string const& fileName) { // baseName: We will use this to lookup if either file is found. // The extension ".a" is removed from this name. // aExtension: is true if the file ends with ".a" std::string baseName(fileName); bool aExtension(false); std::string::size_type pos = fileName.find_last_of(".a"); if ((pos != std::string::npos) && (pos == fileName.size()-2)) { // Get the real base baseName = fileName.substr(0,fileName.size() - 2); aExtension = true; } // This looks up the record about the file(s). // If it dies not exist it creates an entry with false,false. FileInfo& fileInfo = fileMapInfo[baseName]; // Now set the appropriate value to true. if (!aExtension) { fileInfo.first = true; } else { fileInfo.second = true; } } int main() { // loop over files. // call found(<fileName>); }
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 with xlopers, then calling this C++ interface from C#. Does anybody who has prior experience of this kind of issues know what would be the best solution for that ? Anthony
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 operRes, int count,... ) { return 0; } extern "C" int __declspec(dllexport) Excel4v(int xlfn, LPXLOPER operRes, int count, LPXLOPER far opers[]) {return 0;} Now suppose I have an XLL called xll-dll.xll with a function called (use "depends.exe" to find out the names of the exported functions) xlAdd that well adds two doubles: extern "C" __declspec(dllexport) XLOPER * __cdecl xlAdd(XLOPER* pA, XLOPER* pB); The following code calls it: # include <windows.h> # include <iostream> // your own header that defines XLOPERs # include <parser/xll/xloper.hpp> // pointer to function taking 2 XLOPERS typedef XLOPER * (__cdecl *xl2args) (XLOPER* , XLOPER* ) ; void test(){ /// get the XLL address HINSTANCE h = LoadLibrary("xll-dll.xll"); if (h != NULL){ xl2args myfunc; /// get my xll-dll.xll function address myfunc = (xl2args) GetProcAddress(h, "xlAdd"); if (!myfunc) { // handle the error FreeLibrary(h); } else { /// build some XLOPERS, call the remote function XLOPER a,b, *c; a.xltype = 1; a.val.num = 1. ; b.xltype = 1; b.val.num = 2. ; c = (*myfunc)(&a,&b); std::cout << " call of xll " << c->val.num << std::endl; } FreeLibrary(h); } } int main() {test();} My exe actually works (to my own surprise), and output 3 as expected. You must have some knowledge of what your XLL actually expects for parameters. If it allocates some memory, you must check if the #define xlbitDLLFree 0x4000 is set on your XLOPER c->type, and call back "xlAutoFree".
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 project only needs to run on my computer. I am normally a C# asp.net Visual Studio kinda guy, but for this project I plan on using c++. Should I do the work in Eclipse on Ubuntu or Visual Studio in Windows? I realize this can be fairly arbitrary, but I wondering if one IDE/OS might be better suited for this kind of work than the other
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 where you will have the biggest knowledge gain (if learning something is a goal of the project.).
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 data from the files). Recently though, I would like to also consume (i.e. read) the data files I have created on my XP machine, on my Linux machine. I must point out at this stage that both machines are PCs (so have the same endianess etc). I can build a reader (and compile for Linux [Ubuntu 9.10 to be precise]), since I am the library creator. My question, before I embark down this road (of building the reader etc) is: Assuming I have succesfully built the reader for Linux, Can I simply copy accross, files that were created on the windows (XP) machine to the Linux (Ubuntu 9.10) machine and use the Linux reader to successfully read the copied over file?
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 to not happen to be hitting any cases for which they are not. At the very least, though, I'd add some sanity checks and/or sentinel members to detect problems.
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 reserve stringstream buffer? (Should I initialize it with a large enough string or is there a more elegant method?)
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 implementations of std::string do this. Another option might be (untested!) std::string str; str.reserve(50); std::stringstream sstr(str); You might find some more ideas in this gamedev thread. edit: Mucking around with the stringstream's rdbuf might also be a solution. This approach is probably Very Easy To Get Wrong though, so please be sure it's absolutely necessary. Definitely not elegant or concise.
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 "error can't find Release/nnet.lib" during link-time. Is there something special I have to do to get this to link on windows? Edit, example: Main shared library (filenames changed to protect the innocent): ADD_LIBRARY(nnet SHARED src/nnet/file_1.cc src/nnet/file_3.cc src/nnet/file_2.cc src/nnet/file_4.cc) And then I'm building a python module that links in the library: # Build python module ADD_LIBRARY (other_lib SHARED ${CMAKE_SOURCE_DIR}/src/boost/boost_main.cc) TARGET_LINK_LIBRARIES (other_lib nnet ${PYTHON_LIBRARIES}) The rest is just boilerplate (eg: changing module extension to .pyd on windows, finding python libraries/headers, etc) And then when building in VS 2008 I get: fatal error LNK1181: cannot open input file 'Release\nnet.lib' when building other_lib. Note no errors are thrown while building nnet.
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 however. Here is my code (vertex is not shown, but it's pretty simple). typedef std::priority_queue<benchmark::vertex*, std::vector<benchmark::vertex*>, std::less<benchmark::vertex*> > q_type; q_type* q = new q_type(); benchmark::vertex* v1 = new benchmark::vertex(0.1,0.1); v1->cost = 4; benchmark::vertex* v2 = new benchmark::vertex(0.1,0.1); v2->cost = 8; benchmark::vertex* v3 = new benchmark::vertex(0.1,0.1); v3->cost = 6; benchmark::vertex* v4 = new benchmark::vertex(0.1,0.1); v4->cost = 10; benchmark::vertex* v5 = new benchmark::vertex(0.1,0.1); v5->cost = 2; q->push(v1); q->push(v2); q->push(v3); q->push(v4); q->push(v5); while (!q->empty()) { std::cout << (*(q->top())).cost << std::endl; q->pop(); } This outputs 2, 10, 6, 8, 4 on my local machine. I'm testing this on a Linux box with GCC (gcc version 4.3.3 (Ubuntu 4.3.3-5ubuntu4)). Obviously, I want it to spit the numbers out in order. How do I make the comparator, so that it looks and compares vertex.cost, when doing comparisons?
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 missing something or is this a good way of doing what I want? #include <stdio.h> class NotOnTheHeap { public: NotOnTheHeap() : foo( 0 ) { } private: void *operator new( size_t ); void operator delete( void* ); void *operator new[]( size_t ); void operator delete[]( void* ); int foo; }; class Heapable { private: NotOnTheHeap noth; }; int main( int argc, char* argv[] ) { NotOnTheHeap noth; Heapable* heapable = new Heapable; return 0; }
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::vector <NotOnTheHeap>, which will allocate objects from your class on the heap. It will also not prevent people from using a NotOnTheHeap as member variable in another class, that is allocated on the heap.
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 solution, I can create and select an x64 option for that project with no issues. But even then, when the x64 build configuration has been created, I still cannot select it for the C++ project - only for the C# project. I have done this before on another system - creating an x64 config for a Win32 C++ project. But I can't do it now. Any ideas why? Something small/obvious no doubt, since google has offered no help. Thanks!
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: int b; static vector<A*> children; public: B(int a, int b): b(b), A(a) { A::AddToChildren(this);}; virtual void Show(); }; class C: public B { protected: int c; public: C(int a, int b, int c): c(c), B(a,b) { B::AddToChildren(this);}; virtual void Show(); }; vector<A*> A::children=vector<A*>(); vector<A*> B::children=vector<A*>(); void A::AddToChildren(A *obj) { children.push_back(obj); } void A::ShowChildren() { for(vector<A*>::iterator i=children.begin(); i!=children.end();i++) (*i)->Show(); } Adding A(0), B(1,1) and C(2,2,2) and calling a.ShowChildren gives: 1,1 ; 2,2,2 ; 2,2,2 Every time I make an instance of class C the A::children is updated instead of B::children and A::children. Sooo... the class C is added twice to the children of A class, but not added to class B. It helps when I copy the AddChildren class (literally copy) to class B, so that every class has its own AddChildren/ShowChildren. Also I've managed to accomplish this task using pointers, but I'm wondering is there a better way. I think that the problem is somewhere in the "using the right vector", but I don't know how to force the compiler to use the right one. I would be grateful for any suggestions on whatever I'm doing wrong here. First of all, thank you all for your comments and help. Using your advice (about my design and virtual GetList()) I managed to simplify my program: class A { protected: int a; virtual vector<A*>* GetList(); public: A(int a): a(a) {;}; A(int a, A* inherited):a(a) { AddToChildren(inherited);}; static vector<A*> children; virtual void AddToChildren(A* obj); virtual void ShowChildren(); virtual void Show(); }; class B: public A { protected: int b; virtual vector<A*>* GetList(); public: static vector<A*> children; B(int a, int b): b(b), A(a,this){;}; B(int a, int b, A* inherited) : b(b), A(a,this){AddToChildren(inherited);}; virtual void Show(); }; class C: public B { protected: int c; public: C(int a, int b, int c): c(c), B(a,b,this) { }; virtual void Show(); virtual vector<A*>* GetList(); }; vector<A*> A::children=vector<A*>(); vector<A*> B::children=vector<A*>(); void A::AddToChildren(A *obj) { GetList()->push_back(obj); } void A::ShowChildren() { for(vector<A*>::iterator i=GetList()->begin(); i!=GetList()->end();i++) (*i)->Show(); } vector<A*> * A::GetList() { return & children; } vector<A*> * B::GetList() { return & children; } vector<A*> * C::GetList() { return & children; } Now its using constructors without calling the upper class, it just calls the proper constructor of the upper class. Its not the best, but i think it's better. Once more, thank you all for help.
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 constructor. Also, class C has no its own children list. Why? Is it supposed to share the children list with B? I can guess that the fact that you are not calling AddToChildren from all constructors means that some constructors are intended to build complete "objects" of given type (these constructors do call AddToChildren), while some other constructors are intended to be used as "intermediate" constructors by descendant classes (these constructors don't call AddToChildren). Such design might be considered quite questionable and error prone. Note, for example, that C::C calls AddToChildren, which supposedly is adding this to B::children (was it the intent?), and also invokes B::B constructor, which will also add this to B::children. So, the same this value is added to the list twice. This does not seem to make any sense. You need to figure out what is it you are trying to do and then fix your design. Once you are done with it, you can "virtualize" the list using the technique proposed by Neil (introducing a virtual GetList method). Neil later wrote incorrectly that it will not work. In fact, it will work perfectly fine (again, assuming that I understand your intended design correctly). (Taking into account the OP's clarifying comments) So, you want B objects to be added to A::children list and C objects to be added to both A::children and B::children lists. This can be achieved by class A { ... int a; static vector<A*> children; ... A(int a) : a(a) {} virtual vector<A*> *GetList() = 0; void AddToChildren(A* obj) { // note: non-virtual GetList()->push_back(obj); } ... }; class B : public A { ... int b; static vector<A*> children; ... B(int a, int b) : b(b), A(a) { AddToChildren(this); } virtual vector<A*> *GetList() { return &A::children; } ... }; class C : public B { ... int c; ... C(int a, int b, int c) : c(c), B(a,b) { AddToChildren(this); }; virtual vector<A*> *GetList() { return &B::children; } ... }; Note that despite what was said by other posters, virtual calls do work here and they work exactly as we need them to work to achieve the requested functionality. Note though, that in this case there's no point to make method AddToChildren virtual, the virtuality of GetList alone is sufficient. Also, the whole thing makes little if AddToChildren just does a push_back. There's no much sense the build such infrastructure for such a "thin" AddToChildren alone. Just do what you want to do explicitly in each constructor.
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 the direction. However I would suggest to use: http://icu-project.org/apiref/icu4c/classNumberFormat.html and createCurrencyInstance member and then use setMaximumIngegerDigits or other functions to make what you need -- that would be much more localized. Try not assume anything about any culture. Because "10,000 USD" my be misinterpreted as "$ 10" in some countries where "," used for fraction part separation. So be careful.
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 nothing to do. I'm looking for a way to get the thread to block while there isn't any work to be done in the io_service. I could add a global event to the mix for the thread to block on. However, that would require users of the io_service to notify the event every time they used the service. Not the ideal solution. Note: there are no actual globals and I never use events for concurrency I just simplified the problem down to my exact need. The real goal is a asio::deadline_timer subclass that doesn't require an io_service as a construction parameter.
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 there any full implementations out there that raise all the usual events, like keypress,keydown,keyup,mousemove,mousedown,vscroll,hscroll,vresize, hresize of the window. Im interested in making sure that ive implemented the class correctly. Secondly how do I properly throttle the events produced by my NativeWindow, as to limit the chattiness of the implementation.
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 AccessViolation exception. You have to P/Invoke ReadProcessMemory() to read the pointed-to structure. That needs to be done for each individual message, you can't count on a generic implementation. That can get quite hairy when you hook a non-trivial window like a ListView or TreeView.
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 into the cache is no longer there. To solve this I had to re insert the data for the second test. Is this intended or is it something I am doing wrong? Here is the code. The last 2 tests is where the issue lies. #include "UnitTestIncludes.hpp" #include "ResourceCache.hpp" #include <SFML/Graphics.hpp> struct ResourceCacheFixture { ResourceCacheFixture() { BOOST_TEST_MESSAGE("Setup Fixture..."); key = "graysqr"; imgpath = "../images/graysqr.png"; } ResourceCache<sf::Image, ImageGenerator> imgCache; std::string key; std::string imgpath; }; // Start of Test Suite BOOST_FIXTURE_TEST_SUITE(ResourceCacheTestSuite, ResourceCacheFixture) // Start of tests BOOST_AUTO_TEST_CASE(ImageGeneratorTest) { ImageGenerator imgGen; BOOST_REQUIRE(imgGen("../images/graysqr.png")); } BOOST_AUTO_TEST_CASE(FontGeneratorTest) { FontGenerator fntGen; BOOST_REQUIRE(fntGen("../fonts/arial.ttf")); } // This is where the issue is. The data inserted in this test is lost for when I do // the GetResourceTest. It is fixed here by reinserting the data. BOOST_AUTO_TEST_CASE(LoadResourceTest) { bool result = imgCache.load_resource(key, imgpath); BOOST_REQUIRE(result); } BOOST_AUTO_TEST_CASE(GetResourceTest) { imgCache.load_resource(key, imgpath); BOOST_REQUIRE(imgCache.get_resource(key)); } // End of Tests // End of Test Suite BOOST_AUTO_TEST_SUITE_END()
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 commandline, so you don't have to run the entire suite. If your tests depend on each others, or on the order in which they're executed, then this would cause tests to fail. Fixtures are intended to set up the environment you need to run the test. If you need resources to be created before the test runs, the fixture should create them, and clean them up again afterwards.
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::assign like this. But, for some reason, not vector::push_back. vector< vector< int > > v( 20, 40 ); // OK: convert 40 to const T& v.assign( 30, 50 ); // OK v.push_back( 2 ); // error: no conversion, no matching function, etc. Are the first two examples actually compliant for some reason? Why can I convert 40 and 50 but not 2? Epilogue: see http://gcc.gnu.org/onlinedocs/libstdc++/ext/lwg-defects.html#438 for why most compilers allow this, but the standard is shifting the other way.
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 in this case). If you build a quick dummy class that has constructor properties similar to std::vector and try the same thing, you'll discover that the compiler correctly refuses to perform construction. The most likely reason why it accepts your code is the well-known formal ambiguity of two-parameter constructor of std::vector. It can be interpreted as (size, initial value) constructor explicit vector(size_type n, const T& value = T(), const Allocator& = Allocator()); or as (begin, end) template constructor with the latter accepting two iterators template <class InputIterator> vector(InputIterator first, InputIterator last, const Allocator& = Allocator()); The standard library specification explicitly states that when two integral values are used as arguments, the implementation must make sure somehow that the formed constructor is selected, i.e. (size, initial value). How it is done - doesn't matter. It can be done at the library level, it can be hardcoded in the core compiler. It can be done in any other way. However, in response to ( 20, 40 ) arguments Comeau compiler appears to erroneously select and instantiate the latter constructor with InputIterator = int. I don't know how it manages to compile the specialized version of the constructor, since integral values can't and won't work as iterators. If you try this vector< vector< int > > v( 20U, 40 ); you'll discover that the compiler reports an error now (since it can no longer use the two-iterator version of the constructor) and the explicit on the first constructor prevents it from converting 40 to a std::vector. The same thing happens with assign. This certainly a defect of Comeau implementation, but, once again, experiments show that most likely the required behavior was supposed to be enforced at the library level (the core compiler seems to work OK), and somehow it got done incorrectly. On the second thought, I see that the main idea in my explanation is correct, but the details are wrong. Also, I can be wrong about calling it a problem in Comeau. It is possible that Comeau is right here. The standard says in 23.1.1/9 that the constructor template <class InputIterator> X(InputIterator f, InputIterator l, const Allocator& a = Allocator()) shall have the same effect as: X(static_cast<typename X::size_type>(f), static_cast<typename X::value_type>(l), a) if InputIterator is an integral type I suspect that if the above is interpreted literally, the compiler is allowed to assume that an explicit static_cast is implied there (well... so to say), and the code is legal for the same reason static_cast< std::vector<int> >(10) is legal, despite the corresponding constructor's being explicit. The presence of static_cast is what makes it possible for the compiler to use the explicit constructor. If the behavior of Comeau compiler is correct (and I suspect that it is in fact correct, as required by the standard), I wonder whether this was the intent of the committee to leave such a loophole open, and allow implementations to work arount the explicit restriction possibly present on the constructor of vector element.
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 using string *myname vs string &myname? What is the difference between & in C++ and * in C to indicate pointers? Similarly: const string &GetMethodName() { ... } What is the & doing here? Is there some website that explains how & is used differently in C vs C++?
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. Since you are passing by reference, the object is not copied, just like if you were passing a pointer. Your second example: const string &GetMethodName() { ... } Would allow you to return a constant reference to, for example, a member variable. This is useful if you do not wish a copy to be returned, and again be guaranteed that the value returned is non-null. As an example, the following allows you direct, read-only access: class A { public: int bar() const {return someValue;} //Big, expensive to copy class } class B { public: A const& getA() { return mA;} private: A mA; } void someFunction() { B b = B(); //Access A, ability to call const functions on A //No need to check for null, since reference is guaranteed to be valid. int value = b.getA().bar(); } You have to of course be careful to not return invalid references. Compilers will happily compile the following (depending on your warning level and how you treat warnings) int const& foo() { int a; //This is very bad, returning reference to something on the stack. This will //crash at runtime. return a; } Basically, it is your responsibility to ensure that whatever you are returning a reference to is actually valid.
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); while (true) { ClientWorker w; w = new ClientWorker(socket.accept()); Thread t = new Thread(w); t.start(); } and then in the ClientWorker BufferedReader inFromClient = new BufferedReader(new InputStreamReader(client.getInputStream())); DataOutputStream outToClient = new DataOutputStream(client.getOutputStream()); String query = inFromClient.readLine(); // process query here String response = "testresponse"; outToClient.writeBytes(response + "\n"); outToClient.close(); inFromClient.close(); client.close(); Right now I can get a java client that works with this server: String query = "testquery"; Socket queryProcessorSocket = new Socket(queryIp,queryPort); DataOutputStream queryProcessorDos = new DataOutputStream(queryProcessorSocket.getOutputStream()); BufferedReader queryProcessorReader = new BufferedReader(new InputStreamReader(queryProcessorSocket.getInputStream())); queryProcessorDos.writeBytes(query + "\n"); String response = queryProcessorReader.readLine(); But how can I get a C++ client to do the same thing as the java client? I've tried many things but nothing seems to work. Ideally I wouldn't want to touch the java server, is that possible? If someone could point me to a good example or some sample code, that would be much appreciated. I searched through a lot of websites but to no avail.
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_family = AF_INET; servaddr.sin_port = htons(server_port); inet_pton(AF_INET, server_address, &servaddr.sin_addr); connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)); //from this point you can start write to the server and wait for its respose std::string buffer = "testquery"; writen(sockfd, buffer.c_str(), buffer.length()); char *ReadBuffer[512]; while(1) { memset(ReadBuffer, 0x00, sizeof(ReadBuffer)); int n = readn(sockfd, ReadBuffer, sizeof(ReadBuffer)); if(n <= 0) { //or you dont have anything to read, or you have a problem break; } //this function does the hard job of knowing what to do with all these data processBuffer(ReadBuffer, n); } close(sockfd); } I'm using Posix standard and the code is very simplified but I think its a start point. Regards.
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 seven layer or they are just logically implemented. In case they are not logically implemented and you can access I want to access the packages passing the physical layer that received from specific address and do some operation before they move to the next layer. also is there any simulation software for OSI?.
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, ','); int scanned = std::sscanf(buffer, "%d:%d:%lf", &hours, &mins, &seconds); It reads in the first column fine for most of the time. However, occasionally the sscanf fails, and when I check what is in the buffer using the Codegear debugger I see that it has read in \000:00:023 for example. For some reason it is collecting a null character ,\0, at the front. When I look in the text file, it appears to be the same format as all the other time values that were read in correctly. Why is it occasionally adding a null character? And is there a work around?
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 separately to complete my c setup, or how do I get it to compile from within eclipse. I did the usual: created a new c project in the eclipse workspace, created a new hello.c file that looks like this: /* * hello.c * * Created on: 2009-12-21 * Author: geek */ main(){ printf("hello world\n"); } Edit: OS is windows Vista Can someone suggest a compiler that's known to play nice with eclipse (or a tutorial that you've used yourself to get this sorted out)
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 using an anonymous integer handle. In the finalize method (destructor) of the managed object I have a call into the unmanaged dll to delete the unmanaged object. All is well as the c# program runs, but I have a problem when the program exits. Becuase I have no control on the order of delete operations on the managed side, the unmanaged dll is deleted from memory BEFORE any managed object. Thus when the managed object's destructor is called (which in turn calls the unmanaged destructor [at least indirectly]), the unmanaged object has already been deleted and the program crashes. So how can I safely delete a unmanaged object in an external c++ dll that is associated with a managed object in a c# program. Thanks Andrew
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 instead (in fact this may be safer in general). Note this merely avoids calling the freed library (i.e. avoids running the unmanaged destructor): if the unmanaged library was holding a resource that won't automatically be freed on process shutdown, then that resource could be leaked. (Most OS resources are freed on process shutdown, so this will often not be a concern.) And as Adam notes the CLR finaliser is intended as a failsafe: you really want to free resources more deterministically. Therefore, if structurally possible, Igor's suggestion to implement IDisposable on the C# class and deterministically Dispose the object would be preferable.
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 keyword. Tested on GCC and VS. */ } What's curious is that the inverse produces a compile time error: void name(); static void name() { /* Illegal */ } So, is this standard and can I expect other compilers to behave the same way? Thanks!
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 declaration therefore alters the linkage of the second declaration. The inverse is banned because: 7.1.1/7: "The linkages implied by successive declarations for a given entity shall agree". So, in your second example, the first declaration has external linkage (by 7.1.1/6), and the second has internal linkage (explicitly), and these do not agree. You also ask about C, and I imagine it's the same sort of thing. But I have the C++ book right here, whereas you're as capable of looking in a draft C standard online as I am ;-)
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 won't work! The file path of msvcr90.dll when I install python is: C:\windows\WinSxS\x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.21022.8_x-ww_d08d0375 I don't really know how python installs this file but there has to be an easy way to do that. Any ideas?
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 manifest to not use SxS linking.
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 as I have googled, array creation within Constructor such as above is in C++ impossible. Alternatively, the array member can be initialized within the Constructor block as follows. class D { public: D() { a[0] = 5; a[1] = 8; } D(int m, int n) { a[0] = m; a[1] = n; } private: C a[2]; }; But then, It is not an array creation anymore, but array assignment. The array elemnts are created automatically by compiler via their default constructor and subsequently they are manually assigned to specific values within the C'tor block. What is annoying; for such a workaround, the class C has to offer a default Constructor. Has anybody any idea which can help me in creating array members upon construction. I know that using std::vector might be a solution but, due to project conditions I am not allowed to use any standard, Boost or third party library.
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 of C, allocate raw memory to it, then initialize each member with "placement new" (that works around the issue of C not having a default constructor, at least).
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 of matrix i mean we get the best of O(n2.81 ) with a complex solution but perfect results but if there is any solution for even an approximation of multiplication of matrices as we have formulas for factorial approximation etc. if there is any you know it will help me regards.
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) complexity.
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 boost::function<>. In C++ we use the term "function object". A function object is anything (including function pointers) that is "callable" via the function call operator(). std::sort takes a "predicate" which is a special function object that doesn't modify its arguments and returns a boolean value.
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 can start with the bare, base system, and just add the packages you want. Even if your board is not x86, Debian supports a really wide range of architectures; you ought to check and see if Debian would work for you. I talked to someone who worked at a company that produced embedded systems, and he told me they started off with a heavyweight distro (Red Hat, it might have been) and later tried to pare away the fat. He told me that was really painful to do, and he wished they had just used Debian and started with the bare minimum Debian packages. Here's a web page I found describing a minimum Debian install. http://users.telenet.be/mydotcom/howto/linux/debian_minimal.htm
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 and then use this value to save to database ? Or any other suggestions will be appreciated.
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://msdn.microsoft.com/en-us/library/ms714562(VS.85).aspx http://www.odbc.net/api/index.shtml
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 event. In all calls this function should call the original window procedure.
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 widths which is not possible when using image lists. However, in order to get the height ok I'd be willing to drop that requirement and use image lists instead of custom draw.
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 closed. Can someone throw some light why GetOpenFileName() is killing my background streams? String Submerge::showFileDialog(char* filters, bool savedialog, char* title) // need to tweak flags for open/save { OPENFILENAME ofn ; char szFile[255] ; HWND hwnd = NULL; //getOgre()->getAutoCreatedWindow()->getCustomAttribute("WINDOW", &hwnd); ZeroMemory( &ofn , sizeof(ofn) ); ofn.hwndOwner = hwnd; ofn.lStructSize = sizeof ( ofn ); ofn.lpstrFile = szFile; ofn.lpstrFile[0] = '\0'; ofn.nMaxFile = sizeof( szFile ); ofn.lpstrFilter = filters ? filters : "All files\0*.*\0"; ofn.nFilterIndex =1; ofn.lpstrFileTitle = NULL ; ofn.nMaxFileTitle = 0 ; ofn.lpstrInitialDir=NULL ; if(title!=NULL) ofn.lpstrTitle=title; //ofn.Flags = OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST ; MeshLoadTest(); // this is where i use background file streams bool success = false; if(savedialog) success = GetSaveFileName( &ofn ); else success = GetOpenFileName( &ofn ); MeshLoadTest(); // this is where i use background file streams if(!success) return ""; String str; str.append(ofn.lpstrFile); return str; return ""; }
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 changed the directory while searching for files. Windows NT 4.0/2000/XP: This flag is ineffective for GetOpenFileName. You should check the current directory before and after making this call; if it changes then this may be your problem. In that case, add code to save and restore the current directory around the call to GetOpenFileName().
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 known in one file. In general, function bodies, and internal variables that should/will never be accessed by other modules, are what belong in .cpp files. In a word, "implementations". The simplest question to ask yourself to determine what belongs where is "if I change this, will I have to change code in other files to make things compile again?" If the answer is "yes" it probably belongs in the header file; if the answer is "no" it probably belongs in the code file.
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\Testing\Debug\Testing.exe', Symbols loaded. 'Testing.exe': Loaded 'C:\Windows\SysWOW64\ntdll.dll' 'Testing.exe': Loaded 'C:\Windows\SysWOW64\kernel32.dll' 'Testing.exe': Loaded 'C:\Windows\SysWOW64\KernelBase.dll' 'Testing.exe': Loaded 'C:\Windows\winsxs\x86_microsoft.vc90.debugcrt_1fc8b3b9a1e18e3b_9.0.30729.1_none_bb1f6aa1308c35eb\msvcp90d.dll' 'Testing.exe': Loaded 'C:\Windows\winsxs\x86_microsoft.vc90.debugcrt_1fc8b3b9a1e18e3b_9.0.30729.1_none_bb1f6aa1308c35eb\msvcr90d.dll' The program '[2644] Testing.exe: Native' has exited with code 0 (0x0). Why is the IDE loading Testing.exe, I just want to test a .cpp? Code below works fine, except,now i get the above error message, I suspect the IDE: // This program will assist the High Adventure Travel Agency // in calculating the costs of their 4 major vacation packages. #include <iostream> #include <iomanip> using namespace std; // Constants for the charges. const double CLIMB_RATE = 350.0; // Base rate - Devil's Courthouse const double SCUBA_RATE = 1000.0; // Base rate - Bahamas const double SKY_DIVE_RATE = 400.0; // Base rate - Sky diving // This program is a driver for testing the showFees function. #include <iostream> using namespace std; // Prototype void showFees(double, int); int main() { // Constants for membership rates const double ADULT = 40.0; const double SENIOR = 30.0; const double CHILD = 20.0; // Perform a test for adult membership. cout << "Testing an adult membership...\n" << "Calling the showFees function with arguments " << ADULT << " and 10.\n"; showFees(ADULT, 10); // Perform a test for senior citizen membership. cout << "\nTesting a senior citizen membership...\n" << "Calling the showFees function with arguments " << SENIOR << " and 10.\n"; showFees(SENIOR, 10); // Perform a test for child membership. cout << "\nTesting a child membership...\n" << "\nCalling the showFees function with arguments " << CHILD << " and 10.\n"; showFees(CHILD, 10); return 0; } //***************************************************************** // Definition of function showFees. The memberRate parameter * // the monthly membership rate and the months parameter holds the * // number of months. The function displays the total charges. * //***************************************************************** void showFees(double memberRate, int months) { cout << "The total charges are $" << (memberRate * months) << endl; } How is a guy suppose to get his/her code on, with this happening? Or what am I suppose to change, I just want to code in C++ and test my code that's all, not mess around with the damn IDE. Solution: Ctrl+5 http://msdn.microsoft.com/en-us/library/ms235629.aspx To build and examine the program 1. On the Build menu, click Build Solution. The Output window displays information about the compilation progress, for example, the location of the build log and a message that states the build status. 2. On the Debug menu, click Start without Debugging. If you used the sample program, a command window is displayed and shows whether certain integers are found in the set.
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 automatically closes. To see the output of your program you have many options: you may set a breakpoint on the return 0 (so the program is paused there, and you can have a look at the console window before it closes), or you may start the program without debugging (in that case VC++ asks you to press a key before ending the program); you could also add the lines cout<<"Press Enter to exit."; cin.sync(); cin.ignore(); before the return 0: in this way the key press before exit will be included in the application (I don't recommend this approach, though, because if you want to run the program from an already opened console you end up having always that annoying message at the end of the application). By the way, this question may hold the record of "most asked question" about VC++ and many other IDEs :) Why is the IDE loading Testing.exe, I just want to test a .cpp? You know... to run a .cpp you must compile it first... and what do you get from a compilation? A .exe... >_> I just want to code in C++ and test my code that's all, not mess around with the damn IDE. When you'll have to debug a big application you'll bless that "damn IDE".
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 to undefined behaviour? What I see here is that if object is a null pointer at the point of CCuriousClass::~CCuriousClass() being called everything will be fine - no action taken - but if object is not null this will be an infinite loop with undefined behaviour inside. Is this most likely a bug or some smart construct I don't understand?
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 that the owner points to the head of a list, and the list can only be deleted at the head. If the head gets deleted, it sets its parent pointer to the new head of the list. If the parent is destructed, it destroys every list element. Now this is clearly code from crazy town.
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 convenience and familiarity for common string operations not included in the standard C++ library. It's also useful in environments where both C++ and python are used. For networking, there is ACE or Boost.Asio. Finally, there is the POCO library that offers many tools.
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 MSVC complain about do-while(0) construct: foo.c(36) : warning C4127: conditional expression is constant What should I do about this warning? Just disable it globally for all files? It does not seems to be good idea for me.
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 invalid. Microsoft recommends using for(;;) for infinite loop if you want to have this warning on, and there is no solution for your case. This is one of very few Level-4 warnings my company's development conventions allow to disable.
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) : error C2440: 'initializing' : cannot convert from 'int (*)[1]' to 'int' This conversion requires a reinterpret_cast, a C-style cast or function-style cast SuperString.cpp(71) : error C2109: subscript requires array or pointer type Thanks!
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) { matrix[i][j] = /* random value! */; } } Dynamic 2d Matrix: const size_t N = 25; // the dimension of the matrix int** matrix = new int*[N]; // each element is a pointer to an array. for(size_t i = 0; i < N; ++i) matrix[i] = new int[N]; // build rows for(size_t i = 0; i < N; ++i) { for(size_t j = 0; j < N; ++j) { matrix[i][j] = /* random value! */; } } // DON'T FORGET TO DELETE THE MATRIX! for(size_t i = 0; i < N; ++i) delete matrix[i]; delete matrix; Matrix using std::vector: // Note: This has some additional overhead // This overhead would be eliminated once C++0x becomes main-stream ;) // I am talking about r-value references specifically. typedef vector< vector<int> > Matrix; typedef vector<int> Row; const size_t N = 25; // the dimension of the matrix Matrix matrix; for(size_t i = 0; i < N; ++i) { Row row(N); for(size_t j = 0; j < N; ++j) { row[j] = /* random value! */; } matrix.push_back(row); // push each row after you fill it } // Once you fill the matrix, you can use it like native arrays for(size_t i = 0; i < N; ++i) { for(size_t j = 0; j < N; ++j) { cout << matrix[i][j] << " "; } cout << endl; } 3d matrix using boost::multi_array (taken from boost multi_array docs): // Note that this is much more efficient than using std::vector! int main () { // Create a 3D array that is 3 x 4 x 2 typedef boost::multi_array<double, 3> array_type; typedef array_type::index index; array_type A(boost::extents[3][4][2]); // Assign values to the elements int values = 0; for(index i = 0; i != 3; ++i) for(index j = 0; j != 4; ++j) for(index k = 0; k != 2; ++k) A[i][j][k] = values++; // Verify values int verify = 0; for(index i = 0; i != 3; ++i) for(index j = 0; j != 4; ++j) for(index k = 0; k != 2; ++k) assert(A[i][j][k] == verify++); return 0; }
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 c++ !!, but I try to draw the idea) class Branch { static lv_count; Leaves lv; //it should have many leaves!! (and should be some pointer) public: add(Leave lv) { lv[lv_count] = lv; lv_count ++ ; } } class Tree { static br_count; Branch br; //it should have many branchs!!! (and should be some pointer) Tree public: add(Branch br) { br[br_count] = lv; br_count ++ ; } } this is for example, reaching a stupid approach: class Branch { static count; Leaves l[1000]; //mmm i don't like this //... } class Tree { static count; Branch b[1000]; //mmm i don't like this //... } I would like to know the formal normal way for doing this, Thanks!!!!!!
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; next = NULL; } else //next code here } } } Node* Node::first = NULL; new Node(); -- OR -- class Node { int var; Node *next; Node() { //next code here } } Node* first = new Node();
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 insert(int val); void remove(int val); // ... and so on ~List() { // ... clean up } private: struct Node { int val; Node* next; Node(int val_ = 0, Node* next_ = 0) : val(val_), next(next_) {} }; Node* first; }; Note that you can place Node outside List if you want to, but this usually doesn't make much sense.
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 instead of structs. thanks
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 mathematical foundations of statistical speech recognition, written by the founder of that area, Frederick Jelinek. The most important concept you have to know is Hidden Markov Models. People have been using them in speech recognition for decades. A recent approach uses Conditional Random Fields, see the paper (PDF) and the associated software toolkit SCARF. It is fairly hard to write your own speech recognizer. It's an active research area with several scientific conferences, e.g. ASRU, Interspeech, ICASSP.
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 constructor is invoked is during this copying, when the object is created and then the values of the corresponding object are copied to it. Thus, whatever values are assigned to the object in the default constructor will never actually be used. The problem I see is that some member variables aren't initialized in a blank default constructor. Should I just write one that gives dummy values instead? Any other recommended ways to handle this? Edit: I understand that a copy constructor doesn't NEED a default constructor if I were to define copy constructors for the other classes, but I didn't, so it does need it.
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 (copy)" << endl; } }; class Bar { Foo f; public: Bar() : f(1) { cout << "Bar constructor (default)" << endl; } Bar(const Bar& b) : f(b.f) { cout << "Bar constructor (copy)" << endl; } }; int main(void) { Bar b; Bar b_=b; return 0; } Results in: Foo constructor (int) Bar constructor (default) Foo constructor (copy) Bar constructor (copy)
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: regula::State t; t["math"]["pi"] = 3.14159; The above is supposed to place the value 3.14159 within variable pi in table math. Basically, it does this by have t return a proxy object representing math, which returns another proxy object representing pi, to which we actually save the variable. The internals of this aren't really relevant to the question, but here is the function header. LObject LObject::operator[] (const std::string name); Basically, in the example above, the program should call t's operator[] with the string "math" and return another object, and then call that object's operator[] with the string "pi", which returns the final object, and then assigns the value to that one using operator=. template <typename T> T LObject::operator= (const T& value); The T returned is just a copy of the value passed. Now, my code produces NO errors in Visual C++ 2008 and works perfectly. But when I try to compile it on Linux with g++, I get the following error: ../../test/regula-test.cpp:100: error: no match for ‘operator=’ in ‘L.regula::State::operator[](std::basic_string<char, std::char_traits<char>, std::allocator<char> >(((const char*)"Numbers"), ((const std::allocator<char>&)((const std::allocator<char>*)(& std::allocator<char>()))))) = Numbers’ ../../include/regula.hpp:855: note: candidates are: regula::LObject& regula::LObject::operator=(const regula::LObject&) For some reason, g++ seems to be trying to call operator= on operator[], rather than on the returned object like it is supposed to be. I can actually fix this error by replacing the return type on operator= with void: template <typename T> /*T*/ void LObject::operator= (const T& value); But this is not preferable, and besides, I have similar errors in several other locations with a similarly overloaded operator==: ../../test/regula-test.cpp:153: error: no match for ‘operator==’ in ‘pi == L.regula::State::operator[](std::basic_string<char, std::char_traits<char>, std::allocator<char> >(((const char*)"pi"), ((const std::allocator<char>&)((const std::allocator<char>*)(& std::allocator<char>())))))’ I don't understand why this error is occurring in g++, or why it is not occurring in Visual C++. Can anyone shed any light on this or recommend any solutions?
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 after the assignment has taken place; the result is an lvalue. Your operator= returns not only the wrong type, but not even an lvalue. Assuming GCC's error message didn't include any other candidates besides operator=(const regula::LObject&), GCC has simply ignored your overload entirely. The operator= it mentions is the default, automatically generated function. On second glance, your operator[] also should return a reference. As written, no assignment expressions like your example should work at all. So, you should have functions LObject &LObject::operator[] (const std::string name); and template <typename T> LObject &LObject::operator= (const T& value);
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 function to my users called settime2, which will allow users to call it, and time a function without destroying the previous calls. In the settime2 implementation I can call settime. and getcurrenttime. and even call settime with settime or settime2 as the function pointer argument. Any advice? thanks
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 and set the timeout to the earliest time required (the head of the timeout list). When the generic handler is called, remove the head of the list and call its function. Do this repeatedly if the head of the list has the same timestamp. If the list is not empty, call settime again with the timestamp at the head of the list. If the timestamp is really a duration (e.g. 10msec), do almost the same thing but have the saved durations be the sum of the all the previous durations and a delta to form the last duration. For example, three calls, with (f,15), (g,7), (h, 7), and (i,20) would make the list head -> (g,7) -> (h,0) -> (f, 8) -> (i,5) The first settime would be at 7 and g and h would get called. the next settime would be 8 after that (a total of 15) and f called, and finally after 5 more (at 20) i would be called. Be careful to handle the list changing when it is active. ;-)
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? Could the linker remove one implementation of each of these methods so that following is possible: push_back call from the second library calls push_back implementation from the first library pop_back call from the first library calls pop_back implementation from the second library
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 identical, you're violating the One-Definition Rule, which means you're heading into Undefined Behavior-land. Anything might happen. Most likely, you'll see random crashes.
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. Not the basics like declarations or dereferencing, but more often things like getting the address of a pointer-to-pointer, or pointer to reference, etc. Essentially anything that goes a level or two of indirection beyond the norm. Typically I fumble with various semi-logical combinations of operators until I trip upon the correct one. Clearly somewhere along the line I missed a rule or two that simplifies and makes it all fall into place. So I guess my question is: do you know of a site or reference that covers this matter with clarity and in some depth?
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)(); // "foo is a pointer to a function returning a pointer to an int" int (*foo[])(); // "foo is an array of pointers to functions returning ints" Most explanations of the right-left-right rule are written for C rather than C++, so they tend to leave out references. They work just like pointers in this context. int &foo; // "foo is a reference to an integer"
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 with an escape character. In the following example, the value 10 will be put in the node 'txt', a child of 'example'. Instead, I want the value 10 to be stored in the node 'example.txt'. ptree pt; pt.put("example.txt", 10); How can I use the full filename for a single node? Thanks in advance for your help!
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 list at the newsgroup gmane.comp.lib.boost.devel posted by Philippe Vaucher.
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 apps to do this but always run into very complicating or overzealous apps, and all I want to turn a list of token types into a parse tree, nothing more, nothing less. Thanks in advance!
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 wondering if you could dynamically pass the necessary information about a method, like a pointer to the method's owner and method in question name, or even better the direct pointer to the method, for a button to call that function/method when clicked ?
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 "registry" of named function pointers at startup, probably some hash table, so the configuration would map a button to the hash key. From experience though I would say that building such facilities are usually overkill, and the configuration quickly becomes heavier then the app itself. Some additional pointers: Boost.Signals, QT Signals, Command and Chain of Responsibility design patterns.
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): Base<T>(other) {} }; int main() { Derived<int> *x=new Derived<int>(1); Derived<int> y(x); } When I try to compile this, I get: 1X.cc: In constructor ‘Derived<T>::Derived(Derived<T>*&) [with T = int]’: 1X.cc:27: instantiated from here 1X.cc:20: error: invalid conversion from ‘Derived<int>*’ to ‘int’ 1X.cc:20: error: initializing argument 1 of ‘Base<T>::Base(int) [with T = int]’ 1) Clearly gcc is being confused by the constructors. If I remove the reference from the constructors, then the code compiles. So my assumption is that something goes wrong with up-casting pointer references. Can someone tell me what is going on here? 2) A slightly unrelated question. If I were to do something horrendous like "delete other" in the constructor (bear with me), what happens when someone passes me a pointer to something on the stack ? E.g. Derived<int> x(2); Derived<int> y(x); where Derived(Derived<T>*& other) { delete other;} How can I make sure that pointer is legitimately pointing to something on the heap?
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 some value into the reference: Base(Base<T> * &other) { Base<T> *thing = new Base<T>(12); other = thing; } You've just written a pointer to something which is not a Derived<T>, into a pointer to Derived<T>. The compiler can't let this happen.
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 Eclipse? Thanks!
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 the perfect scene...but gets the work done.. It would be nice to see it work in eclipse some day :)
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_safe, mutate, create, then malloc. What is going on, and is this really a memory leak? I have set GLIBCXX_FORCE_NEW=1 here as well. Here is example code that duplicates the situation. Note that valgrind shows no leaks and if I don't put a breakpoint before the cout call, there is no leak found by totalview. #include <string> #include <iostream> #include <cstdlib> int main() { std::string str; int len = strlen(getenv("PATH")); char* x = new char[len + 1]; strcpy(x, getenv("PATH")); x[len] = '\0'; str.assign(x); delete[] x; std::cout << str << std::endl; }
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 presence of an exception. Using the vector you grantee the memory is cleaned up because of RAII.
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 actual performance may vary: usually the bitwise operations (such as the logial-and here) are far more efficient than a mod (or div) operation. Of course, you may argue that some compilers will be able to optimize it anyway, and I agree...but some won't. Another point is that the second one might be a little harder to comprehend for less experienced programmers. On that I'd answer that it will probably only benefit everybody if these programmers take that short time to understand statements of this kind. What do you think? The given two snippets are correct only if num is either an unsigned int, or a negative number with a two's complement representation. - As some comments righfuly state.
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 wrong on "some compilers"? Not necessarily the same compilers in each case, but both kinds are extremely rare. Of course if num is of an unsigned type, or one of the C99 fixed-width integer types (int8_t and so on, which are required to be 2's complement), then this isn't an issue. In that case, I consider %2 to be more elegant and meaningful, and &1 to be a hack that might conceivably be necessary sometimes for performance. I think for example that CPython doesn't do this optimisation, and the same will be true of fully interpreted languages (although then the parsing overhead likely dwarfs the difference between the two machine instructions). I'd be a bit surprised to come across a C or C++ compiler that didn't do it where possible, though, because it's a no-brainer at the point of emitting instructions if not before. In general, I would say that in C++ you are completely at the mercy of the compiler's ability to optimise. Standard containers and algorithms have n levels of indirection, most of which disappears when the compiler has finished inlining and optimising. A decent C++ compiler can handle arithmetic with constant values before breakfast, and a non-decent C++ compiler will produce rubbish code no matter what you do.
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 will contain 5 */ } Alternatively, if you know for sure that "apple" is in dict, you can also do: dict["apple"]. For example cout << dict["apple"]; will print out 5. Also, why the typedef in your code? Can't you just use std::make_pair? And, it won't compile the way you wrote it (with the two leading colons)
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. struct stTest { int a; char b[10]; }; stTest one = {0}; stTest two = {}; stTest three[10] = {0}; stTest four[10] = {};
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 out.
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. After hours of searching I found a solution but it developed for windows mobile standard. So they somehow used c++ to make a message box and on standard devices(ie non touch screen phones) the message box can have like scrolling. For some reason this is not the case with professional devices(touch screen devices). So my message box goes off the page and you can never accept or decline the terms. So your stuck and on the screen forever till you do some sort of soft restart. http://www.mobilepractices.com/2008/10/setupdll-sample-and-walkthrough-terms.html The above link is the tutorial but here is the actual file that seems to display the message. #include "stdafx.h" #include "ce_setup.h" // This is a variable containing the text to be displayed // in the Terms & Conditions dialog TCHAR Message[] = _T("TERMS & CONDITIONS\r\n ") _T("Selecting YES you're accepting our terms & conditions.\r\n") _T("This is just a sample application.\r\n") _T("From http://www.mobilepractices.com\r\n") _T("You can replace this text with your own.\r\n") _T("We're using a setup.dll to show this dialog.\r\n") _T("Extra line to force vertical scrollbar.\r\n") _T("Extra line to force vertical scrollbar.\r\n") _T("Extra line to force vertical scrollbar.\r\n") _T("Extra line to force vertical scrollbar.\r\n") _T("Extra line to force vertical scrollbar.\r\n") _T("Extra line to force vertical scrollbar.\r\n") _T("Last line.\r\n") ; // This function will be called when the user // tries to install the cab. According to its return // value the installation continues or is cancelled. // As this could be called more than once // (i.e. if there is not enough space on the target) // we should take care about fFirstCall parameter // to show the dialog only once. codeINSTALL_INIT Install_Init( HWND hwndParent, BOOL fFirstCall, BOOL fPreviouslyInstalled, LPCTSTR pszInstallDir ) { if (!fFirstCall || ::MessageBoxW(0, Message, _T("SplashScreenSample") , MB_YESNO) == IDYES) return codeINSTALL_INIT_CONTINUE; else return codeINSTALL_INIT_CANCEL; } So I want to change this to something that can scroll. Can I use like a panel control since I know what has scroll or something else? Thanks
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 you said you don't want to learn C (this is C, not C++) but I really can't envision you doing this without at least some basic understanding of the fundamentals of Win32, like WndPrcs, etc. Doug Boling's book "Programming Windows CE" has some super-simple UI apps in it that use plain Win32, so those would be a decent start. So would probably any basic tutorial on DialogBox or CreateDialog.
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 < NUM_TIMES; ++i) { /* Code you want to time.. */ } double milliseconds = (GetTimeMs64() - start_time) / (double)NUM_TIMES; All done! (Note that I haven't tried to compile it)
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 falls apart from there. If someone could provide a sample of how exactly to perform this seemingly simple operation that would be great!. My binary data is stored in a unsigned char array. Here is the codenstein that i've stitched together from what little I found on the internet: _RecordsetPtr updSet; updSet.CreateInstance(__uuidof(Recordset)); updSet->Open("SELECT TOP 1 * FROM [BShldPackets] Order by ChunkId desc", _conPtr.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText); _StreamPtr pStream ; //declare one first pStream.CreateInstance(__uuidof(Stream)); //create it after _variant_t varRecordset(updSet); //pStream->Open(varRecordset, adModeReadWrite, adOpenStreamFromRecord, _bstr_t("n"), _bstr_t("n")); _variant_t varOptional(DISP_E_PARAMNOTFOUND,VT_ERROR); pStream->Open( varOptional, adModeUnknown, adOpenStreamUnspecified, _bstr_t(""), _bstr_t("")); _variant_t bytes(_compressStreamBuffer); pStream->Write(_compressStreamBuffer); updSet.GetInterfacePtr()->Fields->GetItem("Chunk")->Value = pStream->Read(1000); updSet.GetInterfacePtr()->Update(); pStream->Close();
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 using streams at the OLE DB level. However, that increases the pain level many times). If, though, your data is always going to be loaded entirely in memory, I think using AppendChunk would be a simpler route: ret = updSet.GetInterfacePtr()->Fields-> Item["Chunk"]->AppendChunk( L"some data" );
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 issues. I really dislike creating a header that contains things like this, because it seems like it makes the code more complex. I'm looking for other's thoughts on what techniques they employ when they run into a situation like this. If they use a "Common" header, etc.
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 two excerpts from my Common.h: typedef unsigned char uint8; typedef signed char int8; typedef unsigned char uint08; typedef signed char int08; typedef unsigned short uint16; typedef signed short int16; typedef unsigned int uint32; typedef signed int int32; typedef unsigned long long uint64; typedef signed long long int64; typedef const char cchar; typedef const bool cbool; typedef char Byte; #ifdef ASSERT /* Re-defining assert */ #undef ASSERT #endif #ifdef DEBUG #ifndef ASSERTIONS #define ASSERTIONS #endif #endif #define ASSERT_ALWAYS(Expression) if (!(Expression)) FatalError(ErrorInfo("Assertion Failure", #Expression, FUNCTION_NAME, __FILE__, __LINE__)) #ifdef ASSERTIONS #ifdef DEBUG #define ASSERT(Expression) ASSERT_ALWAYS(Expression) #else #define ASSERT(Expression) if (!(Expression)) ErrorLog("[Release Assertions]: The following assertion failed: " # Expression) #endif #else #define ASSERT(Expression) #endif
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 Debian systems at least. Is there an easy way to extend this to something that works on other distributions and Mac OS X?
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 wait in the GUI thread use processEvents() or an event loop, this will prevent the GUI from freezing.
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 effect that a whole bunch of B's have little queues with their own objects, and one large queue in A that contains them all. Each instance of B could live in a separate thread. What I am encountering is that frequently a thread will get pre-empted between the two lines of code in B::foo(), meaning A::mQueue contains the object, but B::mQueue does not yet contain the object. What I am wondering is how I can ensure that when B::foo() is called that the object is either pushed onto both queues or neither queue. It seems to me that I would have to have a mutex in A that B can get a hold of, and lock A's mutex in B::foo(). Does anyone have any suggestions how I could accomplish this, or how I could restructure my code to accomplish this? I am using the boost::threading library. Class A { public: A& instance(){/* return singleton */} void addToQueue(SomeObject const& obj) { mQueue.push(obj); } private: concurrent_queue<SomeObject> mQueue; }; Class B { public: void foo() { SomeObject obj; //I would like to guarantee that obj is either present in both queues or neither queue A::instance().addToQueue(obj); mQueue.push(obj); } private: concurrent_queue<SomeObject> mQueue; }; In my actual implementation, it is not the same object that gets queued up in A and B, rather the A queues up structs that contain pointers to B's, which let me dequeue everything in A and dequeue from all the B's in the same order that they were queued up in, but this should be irrelevant to the question.
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 anywhere the queues are modified. Since it will also have the same lifetime as A's queue, I suggest you put it in A. Then modify queue accesses so they look like: A::instance().lockQueue(); //calls A.mQueueAccessMutex.lock(), probably A::instance().addToQueue(obj); mQueue.push(obj); A::instance().unlockQueue(); Or, RAII-style: { LockHolder lh(A::instance().getLock()); //lock called in lh's constructor A::instance().addToQueue(obj); mQueue.push(obj); //unlock called in lh's destructor } Note that concurrent_queue will then be redundant since no two threads will be accessing the queue concurrently. -- And, of course, there's always the very small chance that simply reversing the order you put the items in the queues will solve your problems. :)
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 you also bother including that and this? Normally what I do is include everything that a class needs, regardless of whether would already receive them from another include. Is this redundant?
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" #include "b.h" //whatever a.h has to be opened and read twice -- although the #ifndef will make the preproc ignore a.h's contents in the second inclusion, it still has to at least load the file from disk and read its bytes from the #ifndef to the #endif. This can slow down compilation. It will not break your build or anything though, it'll just be an annoyance in really large projects, where compiles can take many minutes. If you use #pragma once in your headers, there's a good chance an aware compiler will cache the filenames at a higher level, and ignore the second inclusion of a.h altogether. That too can speed up builds.
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, struct tm *result, const int timezone) { <just like localtime_r, except it uses UTC+timezone as the timezone> } This function must be thread safe, so I don't believe that setting the TZ environment variable would be an option.
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 identity; taking the address of a reference gives you the address of the referent; remember: the reference is its referent). Please also see my answer here for a comprehensive list of how references differ from pointers. The reference is its referent
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 = FALSE, UINT timeout = INPUT_TIMEOUT); I can't understand how could string be equal to long? I'm using Visual C++ 6 (yep I know its old, I'm working on legacy code, so I'm pretty much helpless) EDIT: The line of code that is triggering the error is l_szOption = GetInput(13, FALSE, 30 * 10);
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 argument, while the second version of the function requires a conversion for the second argument (FALSE, which is just 0, to string). In this case neither function is better than the other and overload resolution fails. Try explicitly giving the third argument the unsigned type l_szOption = GetInput(13, FALSE, 30U * 10); or l_szOption = GetInput(13, FALSE, (UINT) 30 * 10); (whichever you prefer) and the code should compile as expected. In other words, the compiler is absolutely right to complain about your code. Your code is indeed broken. The problem in your code has exacty the same nature as in the following simple example void foo(int i, unsigned j); void foo(unsigned i, int j); int main() { foo(0, 0); } This code will also fail to compile for precisely the same reason.
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 GetWindowPos() function that gives me answers in the correct units: void GetWindowPos(HWND hWnd, int *x, int *y) { HWND hWndParent = GetParent(hWnd); RECT parentScreenRect; RECT itemScreenRect; GetWindowRect(hWndParent, &parentScreenRect); GetWindowRect(hWnd, &itemScreenRect); (*x) = itemScreenRect.left - parentScreenRect.left; (*y) = itemScreenRect.top - parentScreenRect.top; } If I use this function, I get coordinates that are relative to the top-left of the parent window, but SetWindowPos() wants coordinates relative to the area below the title bar (I'm presuming this is the "client area", but the win32 terminology is all a bit new to me). Solution This is the working GetWindowPos() function (thanks Sergius): void GetWindowPos(HWND hWnd, int *x, int *y) { HWND hWndParent = GetParent(hWnd); POINT p = {0}; MapWindowPoints(hWnd, hWndParent, &p, 1); (*x) = p.x; (*y) = p.y; }
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 case the number i can varry from 1 to 10. If e.g. I use the first method, I need to create 10times as e.g.: void *ThreadMain1(void *xxx) { ... } until ... void *ThreadMain10(void *xxx) { ... } But if I use the second method, I need to create just : void *ThreadMain(void *xxx) { ... } So which one is correct? Thanks for your time and replies,
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 can do the same job in constructor() and destructor() but I can't solve below problem. Can anyone help me? Thanks in advance. I cannot use exceptions because my company doesn't like it. class Foo { private: AnotherClass a; public: Foo() { if(a.Initialize() == false) { //??? //Can I notify the failure to the user of this class without using exception? } } ... }; Foo obj;
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. The caller will be responsible for checking this method. If you go with either of these techniques, make sure your destructor can handle an instance where the constructor has failed.
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() { long long temp; DataNode inputData; inputData.type= read_some_input(&temp); switch(inputData.type) { case INTEGER: inputData.value.v_int = (int)temp; break; case FLOAT_POINT: inputData.value.v_float = (float)temp; break; case STRING: inputData.value.v_string = (char*)temp; break; } } void printDataNode(DataNode* ptr) { printf("I am a "); switch(ptr->type){ case INTEGER: printf("Integer with value %d", ptr->value.v_int); break; case FLOAT_POINT: printf("Float with value %f", ptr->value.v_float); break; case STRING: printf("String with value %s", ptr->value.v_string); break; } } If you want to see how unions are used HEAVILY, check any code using flex/bison. For example see splint, it contains TONS of unions.
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 value of v==0xffffeeeeddddcccc used environment: Ubuntu-Karmic 32bit g++ version: v4.4.1 EDIT: here is the complete and compilable main.cpp #include <iostream> #include <iomanip> using namespace std; int main(void) { unsigned long long v=(unsigned long long)0xffffeeeeddddcccc; const unsigned v_size = sizeof(unsigned long long); cout << "sizeof(unsigned long long)==" << v_size << endl; cout << "value of v==0x" << setw(v_size) << setfill('0') << hex << v << endl; return 0; }
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++ Standard allows to use ull suffix. g++ 4.4.1 supports this suffix as well as Visual C++ 2008. You could use it as follows: unsigned long long v=0xffffeeeeddddccccULL;
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::size_t?
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 guaranteed to be big enough for any array index so it is a natural type for a loop by index over an array. If you are just counting up to a number then it may be more natural to use either the type of the variable that holds that number or an int or unsigned int (if large enough) as these should be a natural size for the machine.
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 though I forgot the important header (#include<cstdlib>)?
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 initializers (9.4.2), and as integral or enumeration non-type template arguments (14.3). constant-expression: conditional-expression An integral constant-expression can involve only literals (2.13), enumerators, const variables or static data members of integral or enumeration types initialized with constant expressions (8.5), non-type tem- plate parameters of integral or enumeration types, and sizeof expressions. Floating literals (2.13.3) can appear only if they are cast to integral or enumeration types. Only type conversions to integral or enumeration types can be used. In particular, except in sizeof expressions, functions, class objects, pointers, or references shall not be used, and assignment, increment, decrement, function-call, or comma operators shall not be used.
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 Inner; class Cont { public: Cont(); virtual ~Cont(); private: std::auto_ptr<Inner> m_inner; }; Now, the constructor initialized the auto_ptr and the destructor does nothing. But it doesn't work. the problem seem to arise when I'm instantiating this class. I get this warning: warning C4150: deletion of pointer to incomplete type 'Inner'; no destructor called Well, this is obviously very bad and I understand why it happens, The compiler doesn't know about the d'tor of Inner when instantiating the template of auto_ptr<Inner> So my question: Is there a way to use auto_ptr with a forward declaration like I did in the version that uses just plain pointers? Having to #include every class I declare a pointer to is a huge hassle and at times, just impossible. How is this problem usually handled?
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 Cont { virtual ~Cont(); std::auto_ptr<Inner> m_inner; }; // Cont.cpp #include <Cont.h> #include <Inner.h> Cont::~Cont() { }
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 same when including? Thanks.
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 to know which file systems are case sensitive and which aren't, there is a comprehensive list on Wikipedia: Comparison of file name limitations.
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 'extern C' the symbols. Another way to accomplish this would be to leave the C library as standard native code and write a thin C++/CLI layer for it. Then expose the C++/CLI layer to your .NET application.
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 lvalue of type const int, then the cast simply casts away the constness, which is also superfluous in the above context. If n1 is an lvalue of some other type, the cast simply reinterprets memory occupied by n1 as an object of type int (this is called type punning). If n1 is not an lvalue the code is ill-formed. So, in the code like int n2 = (int&) n1 the cast to int & is only non-redundant (has some actual effect) when it does type punning, i.e when n1 is an lvalue of some other type (not int). For example float n1 = 5.0; int n2 = (int &) n1; which would be equivalent to int n2 = *(int *) &n1; and to int n2 = *reinterpret_cast<int *>(&n1); Needless to say, this is a pretty bad programming practice. This is, BTW, one of the cases when using a dedicated C++-style cast is strongly preferred. If the author of the code used reinterpret_cast instead of C-style cast, you probably wouldn't have to ask this question. Of course, if n1 itself is of type int, there's no meaningful explanation for this cast. In that case it is, again, completely superfluous. P.S. There's also a possibility that n2 is a class with overloaded conversion operator to int & type, which is a different story entirely... Anyway, you have to tell what n2 is when you ask questions like that.
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 cgi to return instantly so the browser can continue about its business. I have found several solutions for this (some complete/ some not) but there are still a few things I'd like to clear up. Solution 1 (easiest): The entry-point cgi is a bash script which can then run a C++ process cgi in the background by sending the output to /dev/null/ 2/&>1& (simples! but not very elegant). Solution 2: Much like solution 1, except the entry-point cgi is in C++ and uses system() to run the proc/s and send the output to /dev/null/ 2/&>1& again. [question] This works well but I'm not sure if shared hosting companies allow use of the system() function. Is this the case? Solution 3 (incomplete): I've looked into using fork()/pthread_create() to spawn separate threads which seems more elegant as I can stay in the realms of C. The only problem being: It seems that the parent thread doesn't exit until all child threads have returned. [question] Is there any way to get the parent thread to exit whilst allowing child threads to continue in the background. [idea] Maybe I can send the child proc/s output to the black hole! Can I simply redirect stdout to /dev/null. If so, how do I do this? I hope this makes sense to someone. I'm still a bit of a noob with C stuff so I may be missing very basic concepts (please have mercy!). I'd be very grateful of any advise on this matter. Many thanks in advance, Josh
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(0); // close stdin, stdout, stderr. close(1); close(2); } Looks like modern Linux machines have a daemon() library function that presumably does the same thing. It's possible that the first exit should be _exit, but this code has always worked for me.
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 memcpy to handle such overlap problems. I assume std::copy works like memcpy, in that it doesn't pay any regard to overlap between the source and destination regions. If you try to shift objects "down" in a std::vector with std::copy, you'll corrupt the data. Is there an STL algorithm analogue of memmove to handle situations like this? Or should I roll my own with reverse iterators?
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 first method? UPDATE: The suggestions from initial answers (b myClass ::operator()) does not work :( b myClass::operator() Function "myClass::operator()" not defined. Thanks!
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), m_Hour(_hour){} int GetHour() const {return m_Hour;} int GetJulianDay() const {return m_JulianDay;} int GetYear() const {return m_Year;} bool operator==(const TimeParameter &_rhs); bool operator < (const TimeParameter &_rhs); operator size_t() const; friend bool operator<(const TimeParameter &_lhs, const TimeParameter &_rhs); private: int m_Hour, m_JulianDay, m_Year; }; with the cpp file as TimeParameter::operator size_t() const { return (size_t)(8765u * (m_Year % 6)) + (size_t)(m_JulianDay*24u) + (size_t)m_Hour; } bool operator<(const TimeParameter &_lhs, const TimeParameter &_rhs) { if( _lhs.GetYear() > _rhs.GetYear() ) { return false; } else if( _lhs.GetYear() == _rhs.GetYear() && _lhs.GetJulianDay() > _rhs.GetJulianDay() ) { return false; } else if( _lhs.GetYear() == _rhs.GetYear() && _lhs.GetJulianDay() == _rhs.GetJulianDay() && _lhs.GetHour() > _rhs.GetHour() ) { return false; } return true; } bool TimeParameter::operator==(const TimeParameter &_rhs) { return m_Hour == _rhs.GetHour() && m_JulianDay == _rhs.GetJulianDay() && m_Year == _rhs.GetYear(); } bool TimeParameter::operator <(const TimeParameter &_rhs) { if( m_Year > _rhs.GetYear() ) { return false; } else if( m_Year == _rhs.GetYear() && m_JulianDay > _rhs.GetJulianDay() ) { return false; } else if( m_Year == _rhs.GetYear() && m_JulianDay == _rhs.GetJulianDay() && m_Hour > _rhs.GetHour() ) { return false; } return true; } If I then use this class as a key in a hash_multimap<'TimeParameter,Foo'> I can't then use hash_multimap::find() to find anything. What did I do wrong? Note: Yes, I realize this is yet another datetime style class (my wheel is square!) We have to create a class for every row of every DB table as project requirements. And yes, they really did create a table just for year, day, hour instead of using the well established DateTime type columns. Since they're paying us, we're not arguing. Also, feel free to harp on me for violating DRY. Update: Changing the size_t() operator to return 0; did not solve the problem. It still can't find anything. Changing the operators to always yield true also did not solve the problem. There must be something I've not done right somewhere else in the program to cause such an error.
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 public.
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::operator()( Status&, std::set<std::string> const&, std::vector<My_parameter*> const&, My_attribute_set const&, std::vector<My_parameter_base*> const&, std::vector<My_parameter> const&, std::set<std::string> const& ) { // ... } When this function is in the traceback, the mangled output on my platform is: (_ZN30My_callbackclER11StatusRKSt3setISsSt4lessISsESaISsEERKSt6vectorIP13My_parameterSaISB_EERK17My_attribute_setRKS9_IP18My_parameter_baseSaISK_EERKS9_ISA_SaISA_EES8_+0x76a) [0x13ffdaa] c++filt kindly demangles it to (My_callback::operator()(Status&, std::set<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const&, std::vector<My_parameter*, std::allocator<My_parameter*> > const&, My_attribute_set const&, std::vector<My_parameter_base*, std::allocator<My_parameter_base*> > const&, std::vector<My_parameter, std::allocator<My_parameter> > const&, std::set<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > const&)+0x76a) [0x13ffdaa] This is the same problem as compiler errors encountered when using templates. However, the STL is a fairly regular and recognizable package of templates. So what I'm hoping is that someone out there has created an enhanced version of c++filt which would dump something closer to the original function signature. Any hints?
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.