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
439,580
1,445,301
best way to programmatically modify excel spreadsheets
I'm looking for a library that will allow me to programatically modify Excel files to add data to certain cells. My current idea is to use named ranges to determine where to insert the new data (essentially a range of 1x1), then update the named ranges to point at the data. The existing application this is going to i...
I ended up using Aspose.Cells as I mentioned in my original post, since it seemed like the easiest path. I'm very happy with the way it turned out, and their support is very good. I had to create a wrapper around it in C# that exported a COM interface to my C++ application.
439,704
441,182
What is the best ORB for Java/C++ interoperation using CORBA?
I have a client-server application written in Java using CORBA for the communication. The ORB used is orbd, the one provided by the Java6 platform. I have to replace the Java server implementation with another one written in C++. So the question is, of the free source implementations of CORBA libraries, which one bette...
It's a long time I didn't use CORBA for Java and C++ interoperability, so maybe my answer will be a bit outdated. What I found to work very well together was omniORB (C++) and JacORB (Java). You may search for those libraries on google and see if they are still supported. I also remember I have had big problems with "n...
439,840
440,868
Cannot execute program if using boost (C++) libraries in debug-version on WinXP
I'm using boost for several C++ projects. I recently made a upgrade (1.33.1 to 1.36, soon to 1.37), since then I cannot run any debug-builds anymore. To be sure that no other project issues remain, I've created a minimum test-project, which only includes boost.thread, and uses it to start one method. The release buil...
So you are using the pre-built libraries from BoostPro? If so, your environment might somehow be slightly different to the one they were built in (TR1 feature pack or not, etc). Perhaps best to try building Boost yourself in your specific environment.
439,915
440,010
UTF-8 From File to TextBox VC++ 6.0
How do I get an old VC++ 6.0 MFC program to read and display UTF8 in a TextBox or MessageBox? Preferably without breaking any of the file reading and displaying that is currently written in there (fairly substantial). I read a line into CString strStr, then used this code: int nLengthNeeded = MultiByteToWideChar(CP_UT...
I feel like this won't be helpful, but it's a starting point... I'm assuming it doesn't 'just work', and I don't think you want to try to screw around with wacky code pages that may or may not get you what you want. How about just using MultiByteToWideChar(CP_UTF8, ...) to convert it to utf16 and then calling the W ve...
440,069
440,145
Database Access Libraries for C++
Background: I have an application written in native C++ which uses the wxWidgets toolkit's wxODBC database access library which is being removed from all future versions of wxWidgets . I need to replace this with another database access method that supports the assumptions and contraints outlined below. I don't require...
I use SQLAPI++. Well worth a look. http://www.sqlapi.com/
440,133
440,240
How do I create a random alpha-numeric string in C++?
I'd like to create a random string, consisting of alpha-numeric characters. I want to be able to be specify the length of the string. How do I do this in C++?
Mehrdad Afshari's answer would do the trick, but I found it a bit too verbose for this simple task. Look-up tables can sometimes do wonders: #include <ctime> #include <iostream> #include <unistd.h> std::string gen_random(const int len) { static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOP...
440,161
440,618
Dll compatibility between compilers
Is there some way to make c++ dlls built with diffrent compilers compatible with each other? The classes can have factory methods for creation and destruction, so each compiler can use its own new/delete (since diffrent runtimes have there own heaps). I tried the following code but it crashed on the first member method...
You should be able to mix modules built with different compilers if you lower your expectations and stick to simple functions. The way classes and virtual functions behave is defined by the C++ standard, but the way that's implemented is up to the compiler. In this case, I know that VC++ builds objects which have virt...
440,167
440,183
C++ file handling (structures)
Following code, when compiled and run with g++, prints '1' twice, whereas I expect '1' to be printed only once, since I am dumping a single structure to the file, but while reading back it seems to be reading two structures. Why? #include <iostream.h> #include <fstream.h> int main(){ struct student { i...
eof only gets set after a read fails, so the read runs twice, and the second time, it doesn't modify the buffer. Try this: while(filin.read((char*)&tmpStu,sizeof(tmpStu))) { cout << tmpStu.rollNo << endl; } Or while(!filin.read((char*)&tmpStu,sizeof(tmpStu)).eof()) { cout << tmpStu.rollNo << endl; } Read r...
440,200
440,332
How do I create a strong password string in C++?
Would like to create a strong password in C++. Any suggestions? I assume it should use alpha (upper and lower), numeric, special characters. It would be good to be able to specify a minimum length. It would be great to avoid characters that are hard to visually distinguish like "O" and "O" It would be great to void al...
APG (Automated Password Generator) implements all but your last requirement (no dictionary words / usernames / repeated characters). It includes both pronounceable and fully random password generation algorithms. Pronounceable passwords look something like this: yevGaijra clishahopp jewnAms8 RacMevOm Duheamch& raicsa...
440,694
440,717
for(;true;) different from while(true)?
If my understanding is correct, they do exactly the same thing. Why would anyone use for the "for" variant? Is it just taste? Edit: I suppose I was also thinking of for (;;).
for (;;) is often used to prevent a compiler warning: while(1) or while(true) usually throws a compiler warning about a conditional expression being constant (at least at the highest warning level).
440,827
664,129
Crash writing simple WSO2/C++ web service client
Has any been able to successfully run with a client using the WSO2/C++ web services package? I've tried just about everything I can think of yet every time I try to run a very simple client I get a crash. Here's some sample code from one of their example programs... #include <stdio.h> #include <WSRESTClient.h> #inclu...
Have you considered putting a try/catch-all block around the WRESTClient object construction? If you're core dumping on this line then the chances are that it's throwing an exception, and if you catch it then you might be able to get more useful error information out of that exception. Other than that, time to break ou...
441,067
441,120
c++ push_back, non const copy constructor
I have a class that i want to push_back into a deque. The problem is when i push back i need the original object to be changed thus i need a non const copy ctor. Now if i implement that my const copy ctor gets called. If i removed the const ctor i get an compile error about no available ctors. How do i implement this i...
Your problem is that a fundamental requirement of standard containers is that objects are copy-constructible. That not only means that they have a copy constructor, but that also means that if you copy the object, the copy and the original are the same. Your object, however, resembles a move-constructor semantic. That...
441,128
444,630
How to compile a simple Qt and c++ application using g++ on mac os x?
I am trying to use Qt for a project in school but am running into problems. I started following the tutorials and I am running into Makefile problems. Most of the tutorials say to run qmake -project, then qmake and finally make. But when I try this I run into the error make: *** No targets specified and no makefile fou...
qmake on OS X creates Xcode project files. You can create a Makefile with: qmake -spec macx-g++ If you don't want the Makefile to create an app bundle, you could also remove 'app_bundle' your configuration, for example by adding the following lines to your project file. mac { CONFIG -= app_bundle }
441,203
441,231
"Proper" way to store binary data with C++/STL
In general, what is the best way of storing binary data in C++? The options, as far as I can tell, pretty much boil down to using strings or vector<char>s. (I'll omit the possibility of char*s and malloc()s since I'm referring specifically to C++). Usually I just use a string, however I'm not sure if there are overhead...
vector of char is nice because the memory is contiguious. Therefore you can use it with a lot of C API's such as berkley sockets or file APIs. You can do the following, for example: std::vector<char> vect; ... send(sock, &vect[0], vect.size()); and it will work fine. You can essentially treat it just like any ot...
441,306
441,810
make shared_ptr not use delete
in my code i would like boost::shared_ptr not to call delete but call ptr->deleteMe() instead. Also i have a few C styled functions that return a ptr. Can i make it call lib_freeXYZ(ptr); instead of trying to delete?
Or how about using the stl to provide the wrapper functor - Doug T. description but without the custom caller. boost::shared_ptr<T> ptr( new T, std::mem_fun_ref(&T::deleteMe) ); boost::shared_ptr<S> ptr( new S, std::ptr_fun(lib_freeXYZ) );
441,552
441,629
Scope resolution operator on enums a compiler-specific extension?
On this question, there's an answer that states: You can use typedef to make Colour enumeration type accessible without specifying it's "full name". typedef Sample::Colour Colour; Colour c = Colour::BLUE; That sounds correct to me, but someone down-voted it and left this comment: Using the scope resolution operator...
I tried the following code: enum test { t1, t2, t3 }; void main() { test t = test::t1; } Visual C++ 9 compiled it with the following warning: warning C4482: nonstandard extension used: enum 'test' used in qualified name Doesn't look like it's standard.
441,568
441,683
When can you omit the file extension in an #include directive?
I'm playing around with gmock and noticed it contains this line: #include <tuple> I would have expected tuple.h. When is it okay to exclude the extension, and does it give the directive a different meaning?
The C++ standard headers do not have a ".h" suffix. I believe the reason is that there were many, different pre-standard implementations that the standard would break. So instead of requiring that vendors change their exiting "iostream.h" (for example) header to be standards compliant (which would break their existing...
441,744
441,778
Inheritance instead of typedef
C++ is unable to make a template out of a typedef or typedef a templated class. I know if I inherit and make my class a template, it will work. Examples: // Illegal template <class T> typedef MyVectorType vector<T>; //Valid, but advantageous? template <class T> class MyVectorType : public vector<T> { }; Is doing thi...
C++0x will add template typedefs using the using keyword. Your solution declares a new type, not a type "alias", e.g. you cannot initialize a MyVectorType & (reference) with a vector<T>. This might not be a problem for you, but if it is, but you don't want to reference vector in your code, you can do: template <typenam...
441,757
453,847
Simple option handling using Boost library (C++)
For instance, using the following syntax: -I [file] -A 1 2 3 Question: How to check if a file was specified and additionally if three (integer) values were specified. I understand the following: po::options_descriptions desc("Allowed options"); desc.add_options() How to then use the specified arguments, for instance...
You use the variables_map to check whether options were specified. If you added an option called "file" and your variables_map was called vm: if(vm.count("myoption")) { ... } // Returns 0 if myoption not specified. 1 or more if it was. Once you've used add_options to add some options, you can access them like so, assu...
441,814
891,027
Fully thread-safe shared_ptr implementation
Does anybody know of a fully thread-safe shared_ptr implementation? E.g. boost implementation of shared_ptr is thread-safe for the targets (refcounting) and also safe for simultaneous shared_ptr instance reads, but not writes or for read/write. (see Boost docs, examples 3, 4 and 5). Is there a shared_ptr implementation...
Adding the necessary barriers for such a fully thread-safe shared_ptr implementation would likely impact performance. Consider the following race (note: pseudocode abounds): Thread 1: global_ptr = A; Thread 2: global_ptr = B; Thread 3: local_ptr = global_ptr; If we break this down into its constituent opera...
441,831
441,837
Calling delete on variable allocated on the stack
Ignoring programming style and design, is it "safe" to call delete on a variable allocated on the stack? For example: int nAmount; delete &nAmount; or class sample { public: sample(); ~sample() { delete &nAmount;} int nAmount; }
No, it is not safe to call delete on a stack-allocated variable. You should only call delete on things created by new. For each malloc or calloc, there should be exactly one free. For each new there should be exactly one delete. For each new[] there should be exactly one delete[]. For each stack allocation, the...
441,983
475,381
dynamic cast with interfaces
I have a class with implements 2 interfaces and inherits 1 class. So, generally it looks like this: class T : public A, public IB, public IC { }; There is one point in the code where I have an IB *, but could really use an A *. I was hoping that a dynamic cast would like this: IB *b_ptr = new T; // it's really more co...
I finally figured it out, Daniel Paull was correct in that a "sideways dybnamic_cast" should be allowed. My problem was because my code is involving shared libraries. The typeinfo from PluginA was not available in PluginB. My solution was to effectively add RTLD_NOW and RTLD_GLOBAL to my load process technically it wa...
442,354
442,364
Commandline arguments not working - Skips over them completely
Alright, I'm trying to get arguments to work properly with a small test application. My code is below. I'm not too experienced at C++, so I'm not sure why when I launch test with -print (or --print) it automatically states "Not a valid option" and then finishes up. #include <iostream> int main(int argc, char* argv[]) ...
You're comparing the memory address of the string "-print" to the memory address of argument. This won't work! Use strcmp() to compare string values. Instead of: if (argument == "-print") do if (strcmp(argument, "-print") == 0)
442,550
442,561
Why the functions doesn't execute completely?
When I try to debug the following function segment, the execution brakes (jumps out of the function) at line pCellTower->m_pCellTowerInfo = pCellInfo: RILCELLTOWERINFO* pCellInfo = (RILCELLTOWERINFO*)lpData; CCellTower *pCellTower = (CCellTower*)cbData; if(pCellTower != NULL) { pCellTower->m_pCellTowerInfo = pCell...
The most likely explanation is that pCellTower isn't set either. It could contain random bits, and end up pointing outside the memory allocated to your app. The OS cannot allow your program to write outside the space allocated to it, so it sends the program some kind of message (Windows:exception, Unix/Linux:signal) th...
442,593
442,674
Porting Windows library using Qt to MacOSX, event loops
I'm inserting a hook in the MFC message loop so that the Qt events are treated, without running ->exec() on qApp (because it's blocking): LRESULT CALLBACK myHookFn(int ncode, WPARAM wparam, LPARAM lparam) { if (qApp) qApp->sendPostedEvents(); return CallNextHookEx(0, ncode, wparam, lparam); } and int argc = 0;...
This should happen automatically with Qt Mac 4.5 (both Carbon and Cocoa ports) - since Qt's registered as a CFRunLoopSource in CFRunLoop and the callback will invoke sendPostedEvents. See also qeventdispatcher_mac.mm in src/gui/kernel of Qt 4.5
442,699
442,785
Returning a variable sized array of doubles from C++ to C# - a simpler way?
I have the following C++ method : __declspec(dllexport) void __stdcall getDoubles(int *count, double **values); the method allocates and fills an array of double and sets *count to the size of the array. The only way i managed to get this to work via pinvoke is : [System.Runtime.InteropServices.DllImportAttribute("xx....
I think you can use Marshal.Copy( source, destination, 0, size );
442,735
442,973
How can I embed unicode string constants in a source file?
I'm writing some unit tests which are going to verify our handling of various resources that use other character sets apart from the normal latin alphabet: Cyrilic, Hebrew etc. The problem I have is that I cannot find a way to embed the expectations in the test source file: here's an example of what I'm trying to do.....
A tedious but portable way is to build your strings using numeric escape codes. For example: wchar_t *string = L"דונדארןמע"; becomes: wchar_t *string = "\x05d3\x05d5\x05e0\x05d3\x05d0\x05e8\x05df\x05de\x05e2"; You have to convert all your Unicode characters to numeric escapes. That way your source code becomes encodi...
442,784
442,798
destructors: triviality vs implicit definition
As I understand the standard, a trivial destructor is one which is implicitly declared and whose class has only base and non-static members with trivial destructors. Given the recursivity of this definition, it seems to me that the only "recursion-stopping" condition is to find a base or non-static member with a non-im...
No. An implicitly defined, trivial destructor is by definition trivial :) The difference between the declare and define thingy is that in order for the compiler to even see that a destructor is available, there must always a declaration. So if you don't provide one, it will implicitly provide one. But now, it will als...
443,090
443,184
What are the major differences between C and C++ and when would you choose one over the other?
For those of you with experience with both, what are the major differences? For a newcomer to either, which would be better to learn? Are there situations where you might choose C but then other situations where you would choose C++? Is it a case of use the best tool for the job or one is significantly better than t...
While C is a pure procedural language, C++ is a multi-paradigm language. It supports Generic programming: Allowing to write code once, and use it with different data-structures. Meta programming: Allowing to utilize templates to generate efficient code at compile time. Inspection: Allows to inspect certain properties ...
443,095
443,484
Questions about COM/ActiveX objects
I have good knowledge on the working of a "traditional" .dll. Also the differences between dynamic loading and static loading, etc. But I have the following doubts about the working of COM objects, Is it mandatory to register COM objects with regsvr32? can I have two versions of a registered COM object lying in the sa...
1) No - it is NOT necessary to register COM objects. Registration is needed to create new COM objects. There are many interfaces (COM or native functions) that want a COM object. Their API tells you which interface your COM object should support. Since you pass in an existing COM object, they don't need registration in...
443,141
443,271
Visual Studio 6 VC++ Project version - how do I increment it?
I am making changes to an old program written in VC++6. the project resources include a 'version' set which include the following: Block Header Comments Company Name File Version Product Version Both FileVersion and ProductVersion are at 1.0.0.97 (where the 97 is a build number and increments each time I build the proj...
Those are in an rc .file Open the resource editor and look in the version tab/section. If you make the changes and save it then they should remain that way. I would check to see if there is any other task or something that is overwriting those. Note that one of the fields (I forget which) is a "slave" of another one...
443,147
443,192
C++ mix new/delete between libs?
If I use the new keyword in my library (which is built differently than my main app), when I delete it in my main app with delete, is there a chance that I may get a crash/error?
yes indeedy. In particular you see problems with debug/release heaps being different, also if your library uses placement new, or any custom heap you'll have a problem. The Debug/Release issue is by far the most common though.
443,295
444,054
Caching policies and techniques for matrices
as explained before, I'm currently working on a small linear algebra library to use in a personal project. Matrices are implemented as C++ vectors and element assignment ( a(i,j) = v; ) is delegated to the assignment to the vector's elements. For my project I'll need to solve tons of square equation systems and, in ord...
template<class T> class matrix { public: class accessor { public: accessor(T& dest, matrix& parent) : dest(dest), parent(parent) { } operator T const& () const { return dest; } accessor& operator=(T const& t) { dest = t; parent.invalidate_cache(); return *this; } private: T& ...
443,642
443,715
What is the best unit testing tool for a mix of managed and unmanaged C++?
I am going to start implementing some unit tests for a codebase that is a mix of managed and unmanaged C++. Can NUnit hack it with unmanaged code? Is there a better alternative?
It's possible to use NUnit to test unmanaged code, example: // Tests.h #pragma once #include <cmath> using namespace System; using namespace NUnit::Framework; namespace Tests { [TestFixture] public ref class UnitTest { public: UnitTest(void) {} [Test] void TestCos() ...
443,809
489,355
How to know if a MFC message loop is already running?
Is there any way to know whether a MFC message loop is already running? EDIT: Context: A library (with event handling) needs to know whether its event filtering has to attach to an existing MFC message loop or create its own message loop: in case a main message loop already exists it must not create its own loop becaus...
There is no way to do it without waiting some time, for instance while trying to send an event and wait for it, or wait 5 sec using a special MFC function which is dedicated to detect stalled applications (which one? I can't remember its name...). If you need to do it, find another way, make other assumptions. Sorry.
444,322
444,347
C++ Question about default constructor
What does it mean to call a class like this: class Example { public: Example(void); ~Example(void); } int main(void) { Example ex(); // <<<<<< what is it called to call it like this? return(0); } Like it appears that it isn't calling the default constructor in that case. Can someone give a reason why that wo...
Currently you are trying to call the default constructor like so. Example ex(); This is not actually calling the default constructor. Instead you are defining a function prototype with return type Example and taking no parameters. In order to call the default constructor, omit the ()'s Example ex;
444,726
444,742
Efficient way to handle COM related errors (C++)
Efficient way to handle COM related errors in C++. For instance: switch (HRESULT_CODE(hresult)) { case NOERROR: cout << "Object instantiated and " "pointer to interface IS8Simulation " "obtained" << endl; break; //Specifed Class not registered case R...
Use FormatMessage to get the error text -- it already knows how to look up the localized text for most HRESULTs and Win32 result codes. Use the FAILED and SUCCEEDED macros to work out if something has worked or not. exit takes 32-bit numbers. You can use an HRESULT as your process exit code: HRESULT hr; if (FAILED(hr =...
444,746
444,755
Passing an array as a function parameter in C++
In C++, arrays cannot be passed simply as parameters. Meaning if I create a function like so: void doSomething(char charArray[]) { // if I want the array size int size = sizeof(charArray); // NO GOOD, will always get 4 (as in 4 bytes in the pointer) } I have no way of knowing how big the array is, since I ...
Without changing the signature? Append a sentinel element. For char arrays specifically, it could be the null-terminating '\0' which is used for standard C strings. void doSomething(char charArray[]) { char* p = charArray; for (; *p != '\0'; ++p) { // if '\0' happens to be valid data for your app,...
445,015
445,026
Suppressing Linking Errors in G++ 3.4.6
Don't ask why, but is there any way to suppress a failed linking error? Such as: undefined reference to BLANK This is in GCC 3.4.6
No, because they are errors and not warnings. By definition this means that the function was referenced someplace but not defined... that's not something you can just ignore.
445,127
445,135
Passing "this" to a function from within a constructor?
Can I pass "this" to a function as a pointer, from within the class constructor, and use it to point at the object's members before the constructor returns? Is it safe to do this, so long as the accessed members are properly initialized before the function call? As an example: #include <iostream> class Stuff { public:...
When you instantiate an object in C++, the code in the constructor is the last thing executed. All other initialization, including superclass initialization, superclass constructor execution, and memory allocation happens beforehand. The code in the constructor is really just to perform additional initialization once...
445,139
452,595
How to get Program Files folder path (not Program Files (x86)) from 32bit WOW process?
I need to get the path to the native (rather than the WOW) program files directory from a 32bit WOW process. When I pass CSIDL_PROGRAM_FILES (or CSIDL_PROGRAM_FILESX86) into SHGetSpecialFolderPath it returns the WOW (Program Files (x86)) folder path. I'd prefer to avoid using an environment variable if possible. I want...
I appreciate all the help and, especially, the warnings in this thread. However, I really do need this path and this is how I got it in the end: (error checking removed for clarity, use at your own risk, etc) WCHAR szNativeProgramFilesFolder[MAX_PATH]; ExpandEnvironmentStrings(L"%ProgramW6432%", ...
445,295
576,411
Why does OpenCV reject cvLoadImage("string.ext"), but accept cvLoadImage(argv[1])?
#include "cv.h" #include "highgui.h" #include <stdio.h> int main(int argc, char* argv[]){ cvNamedWindow("Window1", CV_WINDOW_AUTOSIZE); IplImage* image = 0; ->->image = cvLoadImage(argv[1]);<-<- if(!image) printf("Unable to load image!"); cvShowImage("Window1", image); char c = cvWaitKey(0); ...
Under Project->Properties->Configuration Properties->Debugging there is a field "Working Directory". Set that to the directory you want to execute in and that should fix the problem.
445,301
500,505
Avoiding UAC in vista
im writing an application that downloads and installs addons for programs which needs to save the data to program files (for the programs in question). Now this works fine on xp and vista with uac disabled however it is failing on normal vista due to the virtual folders. How would one get around this with out needing t...
I got around uac by making a windows service that does the work i need and only runs while the app is running.
445,315
445,348
Why is snprintf faster than ostringstream or is it?
I read somewhere that snprintf is faster than ostringstream. Has anyone has any experiences with it? If yes why is it faster.
std::ostringstream is not required to be slower, but it is generally slower when implemented. FastFormat's website has some benchmarks. The Standard library design for streams supports much more than snprintf does. The design is meant to be extensible, and includes protected virtual methods that are called by the pub...
445,382
447,380
How to get process info programmatically in C/C++ from a Solaris system?
Is there a C/C++ library, and documentation about how to collect system and process information on Solaris? Although I could parse command-line tools, I'd rather use a library that makes the task easier to do. Thanks Edit: It has been suggested to use the /proc virtual directory to collect information, however its not ...
You can get this kind of information with kstat API. man -s 3KSTAT kstat You can see how it is used in OpenSolaris vmstat and iostat source. For information about processus, I'd look at ps.
445,570
445,591
When can't an object be converted to a reference?
I want to compile the following line of code from http://code.google.com/p/enhsim: enh::eout << enh::setw(26); gcc gives the following error: error: no match for 'operator<<' in 'enh::eout << enh::setw(26)' But the EnhSimOutput class (of which enh::eout is an instance) does declare: EnhSimOutput& operator<< (setw& p)...
The value enh::setw(26); is an rvalue . Actually, temporaries like that are rvalues. Rvalues have special properties. One of them is that their address can't be taken (&enh::setw(26); is illegal), and they can't generally bind to references to non-const (some temporaries can bind to references to non-const, but these u...
445,702
445,724
Template class with "typename"
I have a template class where I want to use objects of that class (along with the parameterized type) inside a map. So far this is the solution that I've been able to arrive at: class IStatMsg; template <typename T> class ITier { public: // Methods ITier(TierType oType) : o_Type(oType){}; virtual ~ITier()...
Line 60 does not access a depending name. What you use is ITier<T> of which the compiler knows it's a template given an argument. Instead of typename you want to use typedef ;) Line 64 does access the depending name iterator which is a type-name, so you have to put typename before std::map. I put the two disambiguation...
445,905
446,011
XML Schema to C++ Classes
I have to write a C++ Application (using the Qt Framework for the GUI) that can edit data stored in xml files described by a xsd schema file. Is there a tool to convert the xsd schema into C++ Classes?
Sounds to me like CodeSynthesis is exactly what you are looking for. It's open source and c++.
446,000
449,733
Resizing a Webbrowser control hosted by an Explorer Bar in IE
I have a custom explorer bar (a band object) that hosts a webbrowser control. I can initialize the WebBrowser control properly and have it display web pages. However, I've noticed that when I resize the explorer bar, the webbrowser control doesn't resize appropriately to the size of the bar: Before Resize: After Resiz...
Typically, when a container hosting an OLE control is resized, it queries the embedded object for its IOleInPlaceObject interface, and uses the SetObjectRects() on that interface to tell the control its new size.
446,205
446,295
Can I continue to use an iterator after an item has been deleted from std::multimap<>?
Can I continue to use an multimap iterator even after a call to multimap::erase()? For example: Blah::iterator iter; for ( iter = mm.begin(); iter != mm.end(); iter ++ ) { if ( iter->second == something ) { mm.erase( iter ); } } Should this be expected to run correctly, or is the itera...
http://www.sgi.com/tech/stl/Multimap.html Multimap has the important property that inserting a new element into a multimap does not invalidate iterators that point to existing elements. Erasing an element from a multimap also does not invalidate any iterators, except, of course, for iterators that actually point to the...
446,296
446,327
Where can I get a "useful" C++ binary search algorithm?
I need a binary search algorithm that is compatible with the C++ STL containers, something like std::binary_search in the standard library's <algorithm> header, but I need it to return the iterator that points at the result, not a simple boolean telling me if the element exists. (On a side note, what the hell was the s...
There is no such functions, but you can write a simple one using std::lower_bound, std::upper_bound or std::equal_range. A simple implementation could be template<class Iter, class T> Iter binary_find(Iter begin, Iter end, T val) { // Finds the lower bound in at most log(last - first) + 1 comparisons Iter i = s...
446,411
446,615
remote procedure calls
Does any one know a good way to do remote procedure calls in windows (non .net) environmental? I cant find much information on how to do it and the msdn only has the .net version. . Edit: Thanks for the answers so far. What i need it for is to communicate with a service on the same computer which will send progress rep...
If you are only interested in talking between processes on the same machine, boost::interprocess is a cool way of getting a channel for them to talk through. More windows specific solutions is a shared memory mapped file and system global mutexes/signals or named pipes. boost::serialize and google protocol buffers are ...
446,565
446,612
get stack trace when exception is thrown
I am now debugging a program that utilizes many different threads. there is an exception that is thrown from time to time. the problem is that there is no way to know what thread caused the problem... does anyone know an easy way to get the stack trace after the exception is thrown? I thought about simply writing a de...
Unless I'm very much mistaken, you need to know which thread triggered the exception in order to use the Visual Studio debugger's call stack view, which is obviously the catch-22 situation you're in at the moment. One thing I would try is to see if you can get the debugger to break when the exception is thrown (using D...
446,758
446,768
How to use existing C++ code in .NET (C#)
I would like to create a C# project and implement the existing native (C++) code. Does anyone know about any good tutorial about it? Thanks!
You can use P/Invoke and you can call unmanaged methods. I'll post you some examples: This is a reference to MSDN official documentation. This is a community mantained website with most of the common Windows unmanaged libraries along with method signatures and examples
446,866
446,880
Boost::multi_array performance question
I am trying to compare the performance of boost::multi_array to native dynamically allocated arrays, with the following test program: #include <windows.h> #define _SCL_SECURE_NO_WARNINGS #define BOOST_DISABLE_ASSERTS #include <boost/multi_array.hpp> int main(int argc, char* argv[]) { const int X_SIZE = 200; c...
Are you building release or debug? If running in debug mode, the boost array might be really slow because their template magic isn't inlined properly giving lots of overhead in function calls. I'm not sure how multi array is implemented though so this might be totally off :) Perhaps there is some difference in storage ...
446,987
447,098
Windows service to control access to a file in "All Users\Application Data"
Here is my situation: I have an application that use a configuration file. The configuration file applies to all users of the system and all users can make change to the configuration. I decided to put the configuration file in "All Users\Application Data" folder. The problem is that the file is writable only by the ...
I wouldn't even bother with COM. Named pipes to your service work fine, too, and it's a lot easier to secure those with ACLs. The service will be so simple I wouldn't even bother with MFC or .NET, pure C++ should be fine. All the heavy lifting is done by your real app; the service just checks if the request piped in ar...
447,206
447,307
C++ IsFloat function
Does anybody know of a convenient means of determining if a string value "qualifies" as a floating-point number? bool IsFloat( string MyString ) { ... etc ... return ... // true if float; false otherwise }
If you can't use a Boost library function, you can write your own isFloat function like this. #include <string> #include <sstream> bool isFloat( string myString ) { std::istringstream iss(myString); float f; iss >> noskipws >> f; // noskipws considers leading whitespace invalid // Check the entire stri...
447,352
447,450
How to know whether we are in a console or a windowed app?
Context : programming a c/c++ win32-mfc library How to know whether we are in a console or a windowed app?
You can determine if there is a console currently attached to the process by calling the win32 function GetConsoleWindow. If it returns NULL then there is no console attached to the process. However this will not necessarily tell you if you are running in a windowed app or not. For example I could have a windowed app t...
447,379
447,404
What is the use of "delete this"?
Today, I have seen some legacy code. In the destructor there is a statement like "delete this". I think, this call will be recursive. Why it is working? I made some quick search on Y!, I found that if there is a need to restrict the user to create the stack object, we can make destructor private and provide an interfac...
"delete this" is commonly used for ref counted objects. For a ref counted object the decision of when to delete is usually placed on the object itself. Here is an example of what a Release method would look like [1]. int MyRefCountedObject::Release() { _refCount--; if ( 0 == _refCount ) { delete this; ret...
447,520
457,130
What's the recommended workaround if numeric_limits<double>::has_infinity is false?
I need to check a double value for infinity in a C++ app on Linux. On most platforms this works by comparing with std::numeric_limits<double>::infinity(). However, on some old platforms (RedHat 9 for example, with gcc 3.2.2) this is not available, and std::numeric_limits<double>::has_infinity is false there. What worka...
Ok, I have now resorted to using the INFINITY and NAN macros on that particular machine - seems to work fine. They come from math.h.
447,854
448,050
Delete or update a dataset in HDF5?
I would like to programatically change the data associated with a dataset in an HDF5 file. I can't seem to find a way to either delete a dataset by name (allowing me to add it again with the modified data) or update a dataset by name. I'm using the C API for HDF5 1.6.x but pointers towards any HDF5 API would be useful....
According to the user guide: HDF5 does not at this time provide an easy mechanism to remove a dataset from a file or to reclaim the storage space occupied by a deleted object. So simple deletion appears to be out of the question. But the section continues: Removing a dataset and reclaiming the space it used can be ...
447,871
448,780
Cross-thread exception throwing
I have an application that allows users to write their own code in a language of our own making that's somewhat like C++. We're getting problems, however, where sometimes our users will accidentally write an infinite loop into their script. Once the script gets into the infinite loop, the only way they can get out is t...
It's possible. Detect the keystroke in a separate thread, a hidden window and WM_HOTKEY for example. Call SuspendThread() to freeze the interpreter thread. Now use GetThreadContext() to get the CPU registers of the interpreter thread. Modify CONTEXT.Eip to the address of a function and call SetThreadContext(). Hav...
448,056
448,068
C++ singleton GetInstance() return
When implementing a singleton in C++, is it better for GetInstance() to return a pointer to the singleton object, or a reference? Does it really matter?
I prefer a reference. I use reference instead of a pointer whenever I want to document that: It can't be null It won't be changed (to point to something else) It mustn't be deleted
448,258
448,272
Calling virtual method in base class constructor
I know that calling a virtual method from a base class constructor can be dangerous since the child class might not be in a valid state. (at least in C#) My question is what if the virtual method is the one who initializes the state of the object ? Is it good practice or should it be a two step process, first to create...
(This answer applies to C# and Java. I believe C++ works differently on this matter.) Calling a virtual method in a constructor is indeed dangerous, but sometimes it can end up with the cleanest code. I would try to avoid it where possible, but without bending the design hugely. (For instance, the "initialize later" o...
448,457
448,483
How to use multiple versions of GCC
We have a new application that requires glibc 2.4 (from gcc 4.1). The machine we have runs on has gcc 3.4.6. We can not upgrade, and the application must be run on this machine. We installed gcc 4.1, however, when it comes to compile time it is using all the includes, etc, from 3.4.6. How do we get around this? A...
Refer "How to install multiple versions of GCC" here in the GNU GCC FAQ. There's also a white paper here.
448,671
448,730
Convert System::DateTime to _timeb
I have a legacy C++-based application that timestamps incoming network traffic using the CRT _ftime() function. The _ftime() function returns a _timeb structure, which has a 32-bit and a 64-bit implementation. We are using the 32-bit implementation, which looks like this: struct _timeb { long time; /...
You're aware of the Y2K38 problem? I assume you checked the sign of .timezone. Avoid the cleverness of using dateTime.Millisecond, that just confuses the next guy. Looks good otherwise.
448,828
449,008
Quickest way to build a bunch of DLL files with the same settings in VS 2008
I'm currently porting a POSIX C++ application to run on Windows without Cygwin or anything. No problem so far. Now, the application (ZNC, an IRC bouncer, in case you're interested) supports loading modules from .so shared library files on Linux/BSD etc. I ported the main executable without much of a problem, all wrappe...
As far as I know there is no built in way to do this. So here is what I would do: Convert one of the modules into a DLL, make sure it works and everything is kosher. Write a script to generate the other 20 vcproj's from the one reference vcproj that works. I don't know the details of your module system so i'm not sure...
449,436
449,823
Singleton instance declared as static variable of GetInstance method, is it thread-safe?
I've seen implementations of Singleton patterns where instance variable was declared as static variable in GetInstance method. Like this: SomeBaseClass &SomeClass::GetInstance() { static SomeClass instance; return instance; } I see following positive sides of this approach: The code is simpler, because it's com...
In C++11 it is thread safe: §6.7 [stmt.dcl] p4 If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. In C++03: Under g++ it is thread safe. But this is because g++ explicitly adds code to guarantee it. One ...
449,485
449,501
C++ SQL Sanitization Libraries or Query Builders Offering Sanitization
In a project I am working on, I need to insert data into a SQLite3 database via C++. In order to avoid a "little Bobby Tables" incident, I need to sanitize my database inputs. I would like to find a library that does this in C++ rather than rolling my own since that usually leads to issues. Since the application will b...
Short answer: do not sanitise your input. Use parameterised queries instead. They are safer and faster.
449,827
449,832
Virtual functions and performance - C++
In my class design, I use abstract classes and virtual functions extensively. I had a feeling that virtual functions affects the performance. Is this true? But I think this performance difference is not noticeable and looks like I am doing premature optimization. Right?
A good rule of thumb is: It's not a performance problem until you can prove it. The use of virtual functions will have a very slight effect on performance, but it's unlikely to affect the overall performance of your application. Better places to look for performance improvements are in algorithms and I/O. An excellen...
449,851
449,862
Why do we need to use `int main` and not `void main` in C++?
Why do we need to use int main and not void main in C++?
The short answer, is because the C++ standard requires main() to return int. As you probably know, the return value from the main() function is used by the runtime library as the exit code for the process. Both Unix and Win32 support the concept of a (small) integer returned from a process after it has finished. Return...
449,940
582,236
Is there already some std::vector based set/map implementation?
For small sets or maps, it's usually much faster to just use a sorted vector, instead of the tree-based set/map - especially for something like 5-10 elements. LLVM has some classes in that spirit, but no real adapter that would provide a std::map like interface backed up with a std::vector. Any (free) implementation of...
I just stumbled upon your question, hope its not too late. I recommend a great (open source) library named Loki. It has a vector based implementation of an associative container that is a drop-in replacement for std::map, called AssocVector. It offers better performance for accessing elements (and worst performance for...
450,107
450,129
Why does compiling a VCC .sln run in the background with no stdout?
I'm trying to compile a project from the command line, like this: devenv.exe myproj.sln /build release It looks like the code compiles well, but that's not all I need: I want to be able to capture the output (e.g. warnings, errors) from the compiler as they occur. Unfortunately as soon as I issue the above command I a...
devenv uses this interesting dispatcher that switches between command line mode and windowed mode. There's actually a devenv.com in addition to devenv.exe, and since *.com takes precedence over *.exe, it gets invoked first. devenv.com analyzes the command line and decides what to invoke. In other words, change your c...
450,136
450,145
C++ Custom GUI Button Question
I am designing a graphical application for which I've decided to write my own menu. I would like this menu to be platform independent. For the time being, my menu will mostly consist of a number of buttons. My issue involves the handling of events when a button is clicked. My dilemma is with a button "knowing" abou...
You can take a look at the Command Pattern. You can associate a command to a menu item, the command would contain the code to be executed.
450,415
450,528
Visual Studio: breakpoint excluding calls from a specific function
I want to set a breakpoint in unmanaged C++, in Visual Studio 2005, but I would like to ignore this breakpoint if the call stack is in a specific function. Is there a way to do this?
If you have a commercial edition of Visual Studio, you should be able to set a breakpoint early in the calling routine, then change its "When Hit..." behaviour to "Run a macro". You'll need to write a macro that programmatically disables the breakpoint in the called function -- use this as the macro to run. (Hopefull...
450,471
450,531
Unknown crash in a C++ Memory Pointers Exercise
I recently wrote a program to help me understand the basics of memory pointers in C++, I chose a simple prime number finder. I finally got it to work. (yay for debugging!) And I let it run to see how far it goes, it gets to prime #815389 with my verbose tells me is the 65076th prime, I get an app crash. The one thing I...
Sean is right, two.nxt is never initialised. In fact, num.nxt is never initialised for any instance of num. The member nxt is unnecessary if the class is made more robust. The nxt pointer can be used instead: class num { private: long i; num *nxtnum; public: num (long value) : i (value), nxtnum (0) { } ...
450,488
450,745
A Good C++ Library for SOAP
What are the alternatives for SOAP development in C++? Which one do you prefer and is most supported/modern?
Check out Apache Axis. That is my all times favorite SOAP implementation. It's SOAP done right! Exists for C++ and Java. http://ws.apache.org/axis/ And in best traditions of Apache Foundation, it is FREE and OPENSOURCE. So, enjoy!
450,558
450,582
Simplified algorithm for calculating remaining space in a circular buffer?
I was wonder if there is a simpler (single) way to calculate the remaining space in a circular buffer than this? int remaining = (end > start) ? end-start : bufferSize - start + end;
If you're worried about poorly-predicted conditionals slowing down your CPU's pipeline, you could use this: int remaining = (end - start) + (-((int) (end <= start)) & bufferSize); But that's likely to be premature optimisation (unless you have really identified this as a hotspot). Stick with your current technique, w...
450,561
450,578
How best to implement BCD as an exercise?
I'm a beginner (self-learning) programmer learning C++, and recently I decided to implement a binary-coded decimal (BCD) class as an exercise, and so I could handle very large numbers on Project Euler. I'd like to do it as basically as possible, starting properly from scratch. I started off using an array of ints, wher...
Just one note, using an array of bitset<4>'s is going to require the same amount of space as an array of long's. bitset is usually implemented by having an array of word sized integers be the backing store for the bits, so that bitwise operations can use bitwise word operations, not byte ones, so more gets done at a ti...
450,585
450,697
Debugging a crash after exiting? (After main returned)
This is a fairly involved bug, and I've tried looking around to find other sources of help, but for reasons I don't understand, "Program Crashes in Vista" is not the most helpful query. The issue I'm having is that the program I'm working on - a graphical, multithreaded data visualization software that uses OpenGL and ...
I've done a little digging around, and I've found a couple of posts around that suggest you're not the only one suffering from this: http://developer.nvidia.com/forums/index.php?showtopic=318 http://objectmix.com/xml-soap/115379-problem-latest-ms-patches-msxml4-vista.html Particularly, the second one is of interest, ...
450,630
450,785
Visual C++ 2005 hangs during qt builds
At my shop, the main product app is a mongrel built on MFC, QT and other random things devs have thrown in over the years. In the current stack, Qt toolkit is on the way out, but still features heavily. If I have SQL 2005 Management studio open and have to do a full build, it usually hangs a CPU (even after the offendi...
In my experience, some of these tools are capable of looping forever (qt4: lupdate/lrelease for sure).
450,832
451,220
How do I make Microsoft VCC crash out on the first build-error?
My automated build process uses a command-line to build something like this: devenv.exe myproj.sln /build release It is a very long build-process which integrates components made by a team of developers. It takes about half an hour to run in release mode. Usually if one thing goes wrong then plenty of other dependanci...
I use the following macro in Visual Studio 2005 to do this, but it should also work in 2003. Add this to the EnvironmentEvents module in the Macros IDE: Private Sub BuildEvents_OnBuildProjConfigDone(ByVal Project As String, ByVal ProjectConfig As String, ByVal Platform As String, ByVal SolutionConfig As String, ByV...
451,102
451,129
How to work with the data in Binary in C/C++
I have to do some work work with integers, but I am interested in treat them as binary data, in a way that for example I can take the 4 most significant bits of an 32 bit value. What I am trying to do is, I have several 32 bit value I want to take for example, in the first one 4 bits, the second one 6 bits and the last...
It seems that you don't need a library for that. Just bit shifting, logical and, or and xor should be sufficient for what you want to do. EDIT: Just to give an example. Suppose a is a 32-bit int, and you want to take the first 4 bit and store it in the lowest bit positions in another integer b, you could do this: b = ...
451,126
451,212
How to define an object whose address is null?
I am wondering how I can define an object in C whose reference will be null? // definition of foo ... void * bar = &foo; // bar must be null There is some ways I could find to do it, but none fit my needs. __attribute__((weak)) extern int foo; //not working with cygwin/gcc 3.4 __attribute__((at(0))) int foo; //...
You are trying to create a symbol with an address of zero. Your last example is probably the only way of doing this within the C compiler / language. The approach that is most likely to solve your problem is to look at the input file to the linker program. Most linkers allow you to define the label foo as zero. In a un...
451,475
451,553
How to print out dash or dot using fprintf/printf?
As of now I'm using below line to print with out dot's fprintf( stdout, "%-40s[%d]", tag, data); I'm expecting the output would be something like following, Number of cards..................................[500] Fixed prize amount [in whole dollars]............[10] Is this a high winner prize?.....................[ye...
A faster approach: If the maximum amount of padding that you'll ever need is known in advance (which is normally the case when you're formatting a fixed-width table like the one you have), you can use a static "padder" string and just grab a chunk out of it. This will be faster than calling printf or cout in a loop. st...
451,534
454,545
Good logging library for managed/unmanaged application?
What logging library or approach would you recommend for this case: We want to be able to log both from managed and unmanaged code For the unmanaged code, the implementation should not cross back into managed code, because this could cause our unmanaged threads to get 'caught' during a garbage collection. Performance ...
Pantheios might meet your requirements. It's open-source.
451,595
451,669
Blocking the standard error output of a programmatically run system command
I have this program in c++: #include <iostream> using namespace std; int main() { char buf[50]; cin.getline(buf,49); system(buf); return 0; } When I run and compile it and type for example "helo", my program prints the error: "helo" not found. Can I stop this error from being displayed? Is there any way to disable...
You can't change the way system displays errors. C and C++ put very little to no requirements on implementations in that regard, so that large parts of it are left unspecified, to allow them to be as flexible as possible. If you want more precise control, you should use the functions of your runtime library or operatio...
451,749
451,888
Is there a TRACE statement for basic win32 C++?
In MFC C++ (Visual Studio 6) I am used to using the TRACE macro for debugging. Is there an equivalent statement for plain win32?
_RPTn works great, though not quite as convenient. Here is some code that recreates the MFC TRACE statement as a function allowing variable number of arguments. Also adds TraceEx macro which prepends source file and line number so you can click back to the location of the statement. Update: The original code on CodeG...
451,884
514,311
Similar String algorithm
I'm looking for an algorithm, or at least theory of operation on how you would find similar text in two or more different strings... Much like the question posed here: Algorithm to find articles with similar text, the difference being that my text strings will only ever be a handful of words. Like say I have a string: ...
I can't mark two answers here, so I'm going to answer and mark my own. The Levenshtein distance appears to be the correct method in most cases for this. But, it is worth mentioning j_random_hackers answer as well. I have used an implementation of LZMA to test his theory, and it proves to be a sound solution. In my ...
451,983
451,997
Why won't cout << work with overloaded * operator?
I'm creating my first class, mainly guided by Overland's C++ Without Fear. I've made the overloaded friend ostream operator<<, which works fine. I've also overloaded the * operator, and that works fine. What doesn't work is when I try to output the result of the * operator directly: BCD bcd(10); //bcd is initialised t...
What's happening is that bcd * 2 is generating a temporary BCD, which cannot bind to a BCD &. Try replacing the << operator with one of these: friend ostream &operator<<(ostream &os, const BCD &bcd); or friend ostream &operator<<(ostream &os, BCD bcd); or even friend ostream &operator<<(ostream &os, const BCD bcd);...
452,390
452,417
Best way to organize a class hierarchy including an overridable "Update" function
I have a base class "Foo" that has an Update() function, which I want to be called once per frame for every instance of that class. Given an object instance of this class called "foo", then once per frame I will call foo->Update(). I have a class "Bar" derived from my base class, that also needs to update every frame....
That's a great question, I've encountered it many many times. Unfortunately, there are at present no language mechanisms that I am familiar with for mainstream languages like C++ to do that, though I expect (at least in the future) for Java to have something with annotations. I've used a variety of techniques includin...
452,435
452,456
Is there a way to programmatically hide an carbon application on osx?
I have a carbon C++ application and I would like to programmatically do the equivalent of Command-H (to hide the application) which is available in the Application menu for my app. I have explored the carbon API for TransitionWindow and HideWindow and while these can hide my window, they do not do the equivalent of Com...
Sorry to answer my own question but the ShowHideProcess() API seems to do what I want. If there are better solutions I would love to hear them.
452,498
453,327
When are constructors called?
If I define a local variable instance of a class halfway down my function without using a pointer and new, does the constructor get called on entering the function or where it is defined? If I define another instance of a class globally within the file does that constructor get called when executable is first loaded? W...
If I define a local variable instance of a class halfway down my function without using a pointer and new, does the constructor get called on entering the function or where it is defined? Such variables have local scope. Their constructor is called when they're defined. For local statics, the constructor is only call...
452,771
452,789
Create an array of class objs
Consider following class class test { public: test(int x){ cout<< "test \n"; } }; Now I want to create array of 50 objects of class test . I cannot change class test. Objects can be created on heap or stack. Creating objs on stack is not possible in this case since we dont have default constructor in class test objs(...
You cannot create an array of objects, as in Foo foo [N], without a default constructor. It's part of the language spec. Either do: test * objs [50]; for() objs[i] = new test(1). You don't need malloc(). You can just declare an array of pointers. c++decl> explain int * objs [50] declare objs as array 50 of pointer t...
453,045
453,072
Service Crash loading dll
I have made a new windows service which works fine using barebone code (just the basic framework for a service), however, when i link it against my dlls, lib file to use the functionality in the dll it crashes on start up with a 0xc0000034 error. Is there a special place to put the dlls for a service or a special way t...
0xc0000034 stands for STATUS_OBJECT_NAME_NOT_FOUND, which suggests a missing file. Are you placing the dlls in correct path? EDIT: I think, as it is win service, path to the dll that it loads should be absolute path or it should be in PATH environmental variable(COM servers works like that) Just copy the dlls to the Sy...
453,099
453,104
Size of static array
I declare a static char array, then I pass it to a function. How to get the no. of bytes in the array inside the function?
You would have to pass it to the function. You can use sizeof() to get the size of an array. const char foo[] = "foobar"; void doSomething( char *ptr, int length) { } doSomething(foo, sizeof(foo)); This MSDN page has explains more about sizeof and has a bigger example. Edit: * see j_random_hacker's answer for an ...
453,293
454,448
c++; things to take care in multicore environment
What are all the things one needs to be careful about when coding in a multicore environment? For example, for a singleton class, it is better to create a global object and then return its reference than a static object. i.e Rather than having MyClass & GetInstance() { static Myclass singleMyclass; return singleMycla...
My first answer addressed your example of singleton initialisation, but as you emphasised in an edit to your question, you are after more general pit falls of C++ as we move to multi-core and multi-threaded applications. The following is a real surprise when you first encounter it. Though not C++ specific, it definite...
453,372
453,387
Writing function definition in header files in C++
I have a class which has many small functions. By small functions, I mean functions that doesn't do any processing but just return a literal value. Something like: string Foo::method() const{ return "A"; } I have created a header file "Foo.h" and source file "Foo.cpp". But since the function is very small, I am th...
If the function is small (the chance you would change it often is low), and if the function can be put into the header without including myriads of other headers (because your function depends on them), it is perfectly valid to do so. If you declare them extern inline, then the compiler is required to give it the same ...
453,407
453,595
What do *you* use C++ ABC constructors for?
What do people here use C++ Abstract Base Class constructors for in the field? I am talking about pure interface classes having no data members and no non-pure virtual members. Can anyone demonstrate any idioms which use ABC constructors in a useful way? Or is it just intrinsic to the nature of using ABCs to implement...
Can anyone demonstrate any idioms which use ABC constructors in a useful way? Here's an example, although it's a contrived, uncommon example. You might use it to keep a list of all instances: class IFoo { private: //static members to keep a list of all constructed instances typedef std::set<IFoo*> Set; static S...
453,432
453,462
Difference in initializing and zeroing an array in c/c++?
In c (or maybe c++) , what's the difference between char myarr[16]={0x00}; and char myarr[16]; memset(myarr, '\0', sizeof(myarr)); ?? edit: I ask this because in vc++ 2005 the result is the same.. edit more : and char myarr[16]={0x00,}; ? maybe can get more comprehensive answer and not ambiguous as some a...
The important difference is that the first default initializes the array in an element-specific manner: Pointers will receive a null pointer value, which doesn't need to be 0x00 (as in all-bits-zero), booleans will be false. If the element type is a class type that's not a so-called POD (plain old data-type), then you ...