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
268,121
268,335
When to build your own buffer system for I/O (C++)?
I have to deal with very large text files (2 GBs), it is mandatory to read/write them line by line. To write 23 millions of lines using ofstream is really slow so, at the beginning, I tried to speed up the process writing large chunks of lines in a memory buffer (for example 256 MB or 512 MB) and then write the buffer ...
A 2GB file is pretty big, and you need to be aware of all the possible areas that can act as bottlenecks: The HDD itself The HDD interface (IDE/SATA/RAID/USB?) Operating system/filesystem C/C++ Library Your code I'd start by doing some measurements: How long does your code take to read/write a 2GB file, How fast...
268,260
268,286
How do I write a console application in Windows that would minimize to the system tray?
I have a written a Visual C++ console application (i.e. subsystem:console) that prints useful diagnositic messages to the console. However, I would like to keep the application minimized most of the time, and instead of minimizing to the taskbar, appear as a nice icon on the system tray. I would also like to restore th...
This is going to be an ugly hack. First, you have to retrieve the hWnd / hInstance of you console application. Right now, I can only come up with one way: Create a Guid with CoCreateGuid() Convert it to a string Set the title of the console window to this guid with SetConsoleTitle() Find the hWnd of the your window wi...
268,587
268,591
Can I use identical names for fields and constructor parameters?
class C { T a; public: C(T a): a(a) {;} }; Is it legal?
Yes it is legal and works on all platforms. It will correctly initialize your member variable a, to the passed in value a. It is considered by some more clean to name them differently though, but not all. I personally actually use it a lot :) Initialization lists with the same variable name works because the syntax ...
268,604
268,693
How to set the width of the exponent field for an ostream?
This code: #include <iostream> int main( int, char **argv ) { std::cout << 1.23e45 << std::endl; } prints 1.23e+045 when compiled with MS Visual Studio 2003, and 1.23e+45 on my Linux machine. How can I specify the width of the exponent field (and why is there a difference in the first place)?
I don't think this is possible with standard manipulators. (if it is, I'd love to be corrected and learn how) Your only remaining option is creating a streambuf yourself, and intercepting all exponent numbers that go to the stream, reformat them by hand, and pass them on to the underlying stream. Seems a lot of work, a...
268,772
268,780
Run-Time Check Failure #2 - Stack around the variable 'x' was corrupted
I receive this Run-Time Check Failure upon the return in the following code. I believe similar code is running fine elsewhere in the program. Any ideas? String GetVariableName(CString symbol, CString filepath) { char acLine[512]; char acPreviousLine[512]; CString csFile; FILE *fp; csFile.Format(...
There is no variable 'x' in the above example, but I'll presume you edited the error message! acLine isn't initialised, so the first time you copy it to acPreviousLine, you are copying whatever happens to be on the stack. This can give you a buffer overflow and therefore stack corruption in some situations - not all, b...
269,054
269,079
How To Set Errorlevel On Exit of MFC App
I have an MFC legacy app that I help to maintain. I'm not quite sure how to identify the version of MFC and I don't think it would make a difference anyway. The app can take some parameters on the command line; I would like to be able to set an errorlevel on exiting the app to allow a bat/cmd file to check for failu...
I can't take credit for this so please don't up this reply. CWinApp::ExitInstance(); return myExitCode; This will return the errorlevel to the calling batch file for you to then evaluate and act upon.
269,081
269,206
is it possible to have templated classes within a template class?
template <class M, class A> class C { std::list<M> m_List; ... } Is the above code possible? I would like to be able to do something similar. Why I ask is that i get the following error: Error 1 error C2079: 'std::_List_nod<_Ty,_Alloc>::_Node::_Myval' uses undefined class 'M' C:\Program Files\Microsoft Visual Studi...
My guess: you forward declared class M somewhere, and only declared it fully after the template instantiation. My hint: give your formal template arguments a different name than the actual ones. (i.e. class M) // template definition file #include <list> template< class aM, class aT > class C { std::list<M> m_List...
269,135
269,210
How do you structure unit tests for cross-compiled code?
My new project is targeting an embedded ARM processor. I have a build system that uses a cross-compiler running on an Ubuntu linux box. I like to use unit testing as much as possible, but I'm a little bit confused about how to proceed with this setup. I can't see how to run unit tests on the ARM device itself (somebo...
With embedded device it depends on what interfaces (hardware) you have. For example the motion control cards I deal with uses a command line interface. The IDE they ship uses it as it primary method of interacting with the cards. It works the same way regardless if I am using PCI, IDE, Serial, or Ethernet. The DLL the...
269,223
269,251
Could C++ have not obviated the pimpl idiom?
As I understand, the pimpl idiom is exists only because C++ forces you to place all the private class members in the header. If the header were to contain only the public interface, theoretically, any change in class implementation would not have necessitated a recompile for the rest of the program. What I want to kno...
This has to do with the size of the object. The h file is used, among other things, to determine the size of the object. If the private members are not given in it, then you would not know how large an object to new. You can simulate, however, your desired behavior by the following: class MyClass { public: // publi...
269,241
269,313
There's a way to declare Copy Constructor non-public AND using default copy Constructor?
I have a not-so-small class under development (that it changes often) and I need not to provide a public copy constructor and copy assignment. The class has objects with value semantics, so default copy and assignment work. the class is in a hierarchy, with virtual methods, so I provide a virtual Clone() to avoid slici...
An object from a polymorphic hierarchy, and with value semantics ? Something is wrong here. If you really do need your class to have a value semantics, have a look at J.Coplien's Envelop-Letter Idiom, or at this article about Regular Objects [1]. [1] Sean Parent. “Beyond Objects”. Understanding The Software We Write. h...
269,268
269,289
How to implement big int in C++
I'd like to implement a big int class in C++ as a programming exercise—a class that can handle numbers bigger than a long int. I know that there are several open source implementations out there already, but I'd like to write my own. I'm trying to get a feel for what the right approach is. I understand that the gener...
Things to consider for a big int class: Mathematical operators: +, -, /, *, % Don't forget that your class may be on either side of the operator, that the operators can be chained, that one of the operands could be an int, float, double, etc. I/O operators: >>, << This is where you figure out how to properly create y...
269,384
269,502
Understanding wxWidgets sizers
I'm still getting used to the sizers in wxWidgets, and as such can't seem to make them do what I want. I want a large panel that will contain a list of other panels/boxes, which each then contain a set of text fields ---------------------- | label text box | | label2 text box2 | ---------------------- -----------...
"If theres too many to fit in the containing panel a vertical scroll bar is also required." You could have a look at wxScrolledWindow. "additional added items are just a small box in the top left of the main panel" I am not sure, but, maybe a call to wxSizer::Layout() will help. "Also whats the best way to lay out the ...
269,633
269,688
MFC: Accessing Views from Mainframe
I am trying to access a view inside a splitter from my mainframe. At the moment I have this: CWnd* pView = m_wndSplitter.GetPane( 0, 0 ); However this gets me a pointer to the CWnd not the CMyViewClass object. Can anyone explain to me what I need to do in order to access the view object itself so I can access member fu...
Just cast it: // using MFC's dynamic cast macro CMyViewClass* pMyView = DYNAMIC_DOWNCAST(CMyViewClass, m_wndSplitter.GetPane(0,0)); if ( NULL != pMyView ) // whatever you want to do with it... or: // standard C++ CMyViewClass* pMyView = dynamic_cast<CMyViewClass*>(m_wndSplitter.GetPane(0,0)); if ( NULL != ...
269,794
270,160
Can't initialize an object in a member initialization list
I have this code: CCalcArchive::CCalcArchive() : m_calcMap() { } m_calcMap is defined as this: typedef CTypedPtrMap<CMapStringToPtr, CString, CCalculation*> CCalcMap; CCalcMap& m_calcMap; When I compile in Visual Studio 2008, I get this error: error C2440: 'initializing' : cannot convert from 'int' to 'CCalcArchive::...
The int is coming from the fact that CTypedPtrMap has a constructor that takes an int argument that is defaulted to 10. The real problem that you're running into is that the m_calcMap reference initalization you have there is trying to default construct a temporary CTypedPtrMap object to bind the reference to. However...
269,837
867,675
How do I display custom tooltips in a CTreeCtrl?
I have a class derived from CTreeCtrl. In OnCreate() I replace the default CToolTipCtrl object with a custom one: int CMyTreeCtrl::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CTreeCtrl::OnCreate(lpCreateStruct) == -1) return -1; // Replace tool tip with our own which will // ask us for the text t...
Finally! I (partially) solved it: It looks like the CDockablePane parent window indeed caused this problem... First I removed all the tooltip-specific code from the CTreeCtrl-derived class. Everything is done in the parent pane window. Then I edited the parent window's OnCreate() method: int CMyPane::OnCreate(LPCREATES...
269,918
270,143
C++ string diff (a la Python's difflib)
I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example, varies_in_single_number_field('foo7bar', 'foo123bar') # Returns True, because 7 != 123, and there's only one varying # number region between the two strings. In Python I can use the...
This might work, it at least passes your demonstration test: EDIT: I've made some modifications to deal with some string indexing issues. I believe it should be good now. #include <iostream> #include <string> #include <vector> #include <algorithm> #include <cctype> bool starts_with(const std::string &s1, const std::st...
269,932
269,973
string to char* marshaling
I wrote a managed C++ class that has the following function: void EndPointsMappingWrapper::GetLastError(char* strErrorMessage) { strErrorMessage = (char*) Marshal::StringToHGlobalAnsi(_managedObject->GetLastError()).ToPointer(); } As you can see, this is a simple method to copy the managed string of the last error...
You are assigning the value of the passed parameter (strErrorMessage) instead of copying to that address the content of the buffer returned by Marshal::StringToHGlobalAnsi. A correct implementation should be: void EndPointsMappingWrapper::GetLastError(char* strErrorMessage, int len) { char *str = (char*) Marshal::Stri...
270,347
271,644
Replacing auto_ptr in VC++ 8
std::auto_ptr is broken in VC++ 8 (which is what we use at work). My main gripe with it is that it allows auto_ptr<T> x = new T();, which of course leads to horrible crashes, while being simple to do by mistake. From an answer to another question here on stackoverflow: Note that the implementation of std::auto_ptr in ...
Move to boost smart pointers. In the meantime, you may want to extract a working auto_ptr implementation from an old / another STL, so you have working code. I believe that auto_ptr semantics are fundamentally broken - it saves typing, but the interface actually is not simpler: you still have to track which instance is...
270,408
270,435
Is it better in C++ to pass by value or pass by reference-to-const?
Is it better in C++ to pass by value or pass by reference-to-const? I am wondering which is better practice. I realize that pass by reference-to-const should provide for better performance in the program because you are not making a copy of the variable.
It used to be generally recommended best practice1 to use pass by const ref for all types, except for builtin types (char, int, double, etc.), for iterators and for function objects (lambdas, classes deriving from std::*_function). This was especially true before the existence of move semantics. The reason is simple: i...
270,455
270,464
Is it possible to program iPhone in C++
I'm all for language diversity, but Objective C is insane. So I'm curious: is it possible to code iPhone apps with C++ while using the Cocoa API, etc?
Short answer, yes, sort of. You can use Objective-C++, which you can read about at Apple Developer Connection. If you know C++ already, learning Objective-C would be pretty simple, if you decided to give that a try. More info on that topic is at the ADC as well.
270,488
270,515
Is assert(false) ignored in release mode?
I am using VC++. Is assert(false) ignored in release mode?
If compiling in release mode includes defining NDEBUG, then yes. See assert (CRT)
270,527
270,608
ASSERT vs. ATLASSERT vs. assert
I am refactoring some MFC code that is littered with ASSERT statements, and in preparation for a future Linux port I want to replace them with the standard assert. Are there any significant differences between the two implementations that people know of that could bite me on the backside? Similarly, I have also come a...
No. The MFC version just includes an easy to debug break point.
270,542
270,704
Testing for assert in the Boost Test framework
I use the Boost Test framework to unit test my C++ code and wondered if it is possible to test if a function will assert? Yes, sounds a bit strange but bear with me! Many of my functions check the input parameters upon entry, asserting if they are invalid, and it would be useful to test for this. For example: void M...
I don't think so. You could always write your own assert which throws an exception and then use BOOST_CHECK_NOTHROW() for that exception.
270,592
270,599
If abstract base class is an interface, is it obligatory to call base class constructor in derived class constructor?
class AbstractQuery { virtual bool isCanBeExecuted()=0; public: AbstractQuery() {} virtual bool Execute()=0; }; class DropTableQuery: public AbstractQuery { vector< std::pair< string, string> > QueryContent; QueryValidate qv; public: explicit DropTableQuery(const string& qr): AbstractQuery(), q...
No, in fact for it is unnecessary for the base class to have an explicitly defined constructor (though make sure you have a virtual destructor). So for a typical interface you could have something like this: class MyInterface { public: virtual ~MyInterface() {} virtual void execute() = 0; }; EDIT: Here's a rea...
270,623
270,731
How to build an ActiveX object in C++ that can be scripted using Javascript
I can use VS08's MFC/ActiveX template to create a C++ ActiveX object that I can load into a HTML page and script with Javascript. But I can't figure out how to create an interface that allows me to call custom methods on my component with Javascript. Could you please tell me how to accomplish that? I have spent over tw...
I'm not extremely familiar with the MFC ActiveX wrapper, but I can answer the question in the general sense: A COM object with an interface which is derived from IDispatch can be called through automation languages (eg: Javascript). The methods must also be "automation-compatible", which means that the parameters are c...
270,917
270,925
Why should I declare a virtual destructor for an abstract class in C++?
I know it is a good practice to declare virtual destructors for base classes in C++, but is it always important to declare virtual destructors even for abstract classes that function as interfaces? Please provide some reasons and examples why.
It's even more important for an interface. Any user of your class will probably hold a pointer to the interface, not a pointer to the concrete implementation. When they come to delete it, if the destructor is non-virtual, they will call the interface's destructor (or the compiler-provided default, if you didn't specify...
270,947
270,957
Can any one provide me a sample of Singleton in c++?
I write a singleton c++ in the follow way: class A { private: static A* m_pA; A(); virtual ~A(); public: static A* GetInstance(); static void FreeInstance(); void WORK1(); void WORK2(); void WORK3(); } } A* A::GetInstance() { if (m_pA ==...
You can avoid needing to delete it by using a static object like this: if(m_pA == 0) { static A static_instance; m_pA = &static_instance; }
270,984
270,995
g++ partial linking instead of archives?
I'm pretty new to the C++ build flow, and I'm thinking of switching to use partial linking for my libraries instead of creating ar archives. I'm hoping to reduce link time in an inevitable final compilation step that I have, and I figure partial linking some libraries once could save me time over linking everything in ...
You lose an important effect of having the object files in an ar archive, which is that only the referenced objects will be linked in. If you have both foo.o with the symbol foo and bar.o with the symbol bar in an ar archive, and only reference the foo symbol, only foo.o would be linked in. If you instead do a partial ...
271,042
271,091
invoking functions while debugging with Visual Studio 2005?
Here's something I know is probably possible but I've never managed to do In VS2005(C++), While debugging, to be able to invoke a function from the code which I'm debugging. This feature is sometimes essential when debugging complex data structures which can't be explored easily using just the normal capabilities of th...
Ok, Here's what I found CXX0040 means that "The C expression evaluator does not support implicit conversions involving constructor calls." CXX0047 means that "Overloaded functions can be called only if there is an exact parameter match or a match that does not require the construction of an object." So combined it mean...
271,076
271,087
What is the difference between an int and a long in C++?
Correct me if I am wrong, int is 4 bytes, with a range of values from -2,147,483,648 to 2,147,483,647 (2^31) long is 4 bytes, with a range of values from -2,147,483,648 to 2,147,483,647 (2^31) What is the difference in C++? Can they be used interchangeably?
It is implementation dependent. For example, under Windows they are the same, but for example on Alpha systems a long was 64 bits whereas an int was 32 bits. This article covers the rules for the Intel C++ compiler on variable platforms. To summarize: OS arch size Windows IA-32 4 ...
271,204
271,445
What do you think is making this C++ code slow? (It loops through an ADODB recordset, converts COM types to strings, and fills an ostringstream)
This loop is slower than I would expect, and I'm not sure where yet. See anything? I'm reading an Accces DB, using client-side cursors. When I have 127,000 rows with 20 columns, this loop takes about 10 seconds. The 20 columns are string, int, and date types. All the types get converted to ANSI strings before th...
Try commenting out the code in the for loop and comparing the time. Once you have a reading, start uncommenting various sections until you hit the bottle-neck.
271,612
271,654
Parse a file using C++, load the value to a structure
I have the following file/line: pc=1 ct=1 av=112 cv=1100 cp=1700 rec=2 p=10001 g=0 a=0 sz=5 cr=200 pc=1 ct=1 av=113 cv=1110 cp=1800 rec=2 p=10001 g=0 a=10 sz=5 cr=200 and so on. I wish to parse this and take the key value pairs and put them in a structure: struct pky { pky() : a_id(0), sz_id(0), ...
You can do something like this: std::string line; std::map<std::string, std::string> props; std::ifstream file("foo.txt"); while(std::getline(file, line)) { std::string token; std::istringstream tokens(line); while(tokens >> token) { std::size_t pos = token.find('='); if(pos != std::string::...
271,833
272,337
Is it possible to start a custom thread in an IIS hosted C++ application?
We host a C++ based WebServices application in IIS and we're finding that when we try to start our own C++ threads IIS has a fit and crashes. The threads are based on boost.thread which clearly dribbles down to the standard Windows threading API underneath. The reason I need to start the thread is to listen for mult...
It sounds like you're creating a persistent thread, which lives longer than the lifetime of the request that initiates it. You don't mention whether it's ASP.NET C++/CLI, Managed C++ or an ISAPI extension or filter, or even CGI. Conceptually, code that is called by IIS is only supposed to "live" for the lifetime of the...
271,845
271,942
MFC: Changing font of a List control
I need to at run time change the font of a List Control so as to used a fixed width font. I have seen some examples which suggest I should trap the NM_CUSTOMDRAW message, but I was wondering if there was a better way of doing it. Thanks.
Create an appropriate CFont object, and set the control's font by calling SetFont(), passing in the CFont, like so: m_font.CreatePointFont(90,"Courier New"); m_listCtrl.SetFont(&m_font); This assumes that you've got a window or dialog object with a "CFont m_font" member, and an "m_listCtrl" member attached to the list...
271,939
271,958
Singleton getInstance in thread worker methods
This question is about using getter methods of a singleton object in worker threads. Here is some pseudo code first: // Singleton class which contains data class MyData { static MyData* sMyData ; int mData1[1024]; int mData2[1024]; int mData3[1024]; MyData* getInstance() { // sMyDat...
Provided that no other thread will try to write to the data in your singleton object, you don't need to protect them: by definition, multiple readers in the absence of a writer is thread-safe. This is a common pattern where the program's initialization code sets up a singleton, which is then only read from by worker th...
271,971
272,024
How can I improve/replace sprintf, which I've measured to be a performance hotspot?
Through profiling I've discovered that the sprintf here takes a long time. Is there a better performing alternative that still handles the leading zeros in the y/m/d h/m/s fields? SYSTEMTIME sysTime; GetLocalTime( &sysTime ); char buf[80]; for (int i = 0; i < 100000; i++) { sprintf(buf, "%4d-%02d-%02d %02d:%02d:%...
If you were writing your own function to do the job, a lookup table of the string values of 0 .. 61 would avoid having to do any arithmetic for everything apart from the year. edit: Note that to cope with leap seconds (and to match strftime()) you should be able to print seconds values of 60 and 61. char LeadingZeroInt...
272,036
272,070
Alternative to GetProcessID for Windows 2000
I've accidentally removed Win2K compatibility from an application by using GetProcessID. I use it like this, to get the main HWND for the launched application. ShellExecuteEx(&info); // Launch application HANDLE han = info.hProcess; // Get process cbinfo.han = han; //Call EnumWindows to enumerate windows.... //with t...
There is an 'sort-of-unsupported' function: ZwQueryInformationProcess(): see http://msdn.microsoft.com/en-us/library/ms687420.aspx This will give you the process id (amongst other things), given the handle. This isn't guaranteed to work with future Windows versions, so I'd suggest having a helper function that tests th...
272,161
272,240
Why can't I use static members, for example static structures, in my classes in VS2008?
When I write code like this in VS 2008: .h struct Patterns { string ptCreate; string ptDelete; string ptDrop; string ptUpdate; string ptInsert; string ptSelect; }; class QueryValidate { string query; string pattern; static Patterns pts; public: f...
You're trying to create a non-static member (ptCreate) of a static member (pts). This won't work like this. You got two options, either use a struct initializer list for the Patterns class. Patterns QueryValidate::pts = {"CREATE", "DELETE"}; // etc. for every string Or, much safer (and better in my opinion), provide a...
272,414
272,485
Boost Graph Library: Is there a neat algorithm built into BGL for community detection?
Anybody out there using BGL for large production servers? How many node does your network consist of? How do you handle community detection Does BGL have any cool ways to detect communities? Sometimes two communities might be linked together by one or two edges, but these edges are not reliable and can fade away....
I've used the BGL for graphs with millions of nodes, but the size of the graph you can use depends on what algorithm you are trying to run. You can quickly compute distances between nodes. There are 4 shortest path algorithms which are most applicable depending on your data: (single pairs of points, for all pairs of ...
272,479
284,499
How to get equivalent of printf_l on Linux?
This function exists on OS X and allows you to pass custom local to the function. setlocale is not thread-safe, and passing locale as parameter is. If there is no equivalent, any way of locale-independent printf, or printf just for doubles (%g) will be ok.
There are locale-independent double to string convertion routines at http://www.netlib.org/fp/. String to double conversion is available too. The API is not very nice, but the code works.
272,523
274,370
Socket Exception: "There are no more endpoints available from the endpoint mapper"
I am using winsock and C++ to set up a server application. The problem I'm having is that the call to listen results in a first chance exception. I guess normally these can be ignored (?) but I've found others having the same issue I am where it causes the application to hang every once in a while. Any help would be...
On a very busy server, you may be running out of Sockets. You may have to adjust some TCPIP parameters. Adjust these two in the registry: HKLM\System\CurrentControlSet\Services\Tcpip\Parameters MaxUserPort REG_DWORD 65534 (decimal) TcpTimedWaitDelay REG_DWORD 60 (decimal) By default, there's a few minutes de...
272,750
272,784
Kill a blocked Boost::Thread
I am writing an application which blocks on input from two istreams. Reading from either istream is a synchronous (blocking) call, so, I decided to create two Boost::threads to do the reading. Either one of these threads can get to the "end" (based on some input received), and once the "end" is reached, both input stre...
I don't think there is a way to do it cross platform, but pthread_cancel should be what you are looking for. With a boost thread you can get the native_handle from a thread, and call pthread_cancel on it. In addition a better way might be to use the boost asio equivalent of a select call on multiple files. That way one...
272,900
272,965
Undefined reference to static class member
Can anyone explain why following code won't compile? At least on g++ 4.2.4. And more interesting, why it will compile when I cast MEMBER to int? #include <vector> class Foo { public: static const int MEMBER = 1; }; int main(){ vector<int> v; v.push_back( Foo::MEMBER ); // undefined referen...
You need to actually define the static member somewhere (after the class definition). Try this: class Foo { /* ... */ }; const int Foo::MEMBER; int main() { /* ... */ } That should get rid of the undefined reference.
272,964
273,032
Will the c++ compiler optimize away unused return value?
If I have a function that returns an object, but this return value is never used by the caller, will the compiler optimize away the copy? (Possibly an always/sometimes/never answer.) Elementary example: ReturnValue MyClass::FunctionThatAltersMembersAndNeverFails() { //Do stuff to members of MyClass that never fails...
If the ReturnValue class has a non-trivial copy constructor, the compiler must not eliminate the call to the copy constructor - it is mandated by the language that it is invoked. If the copy constructor is inline, the compiler might be able to inline the call, which in turn might cause a elimination of much of its code...
273,209
273,287
Are memory leaks ever ok?
Is it ever acceptable to have a memory leak in your C or C++ application? What if you allocate some memory and use it until the very last line of code in your application (for example, a global object's destructor)? As long as the memory consumption doesn't grow over time, is it OK to trust the OS to free your memory f...
No. As professionals, the question we should not be asking ourselves is, "Is it ever OK to do this?" but rather "Is there ever a good reason to do this?" And "hunting down that memory leak is a pain" isn't a good reason. I like to keep things simple. And the simple rule is that my program should have no memory leaks....
273,451
273,462
Which platform should I use : native C++ or C#?
I want to develop a windows application. If I use native C++ and MFC for user interface then the application will be very fast and tiny. But using MFC is very complicated. Also If I use C# then the application will be slower than the native code and It reqiures .NET framework to run. But developing GUI is very easy by ...
"fast" and "slow" are subjective, especially with today's PC's. I'm not saying deliberately make the thing slow, but there isn't nearly as much overhead in writing a managed application as you might think. The JIT etc work very well to make the code execute very fast. And you can also NGEN for extra start-up speed if y...
273,630
273,633
If I use explicit constructor, do I need to put the keyword in both .h and .cpp files?
Actually my question is all in the title. Anyway: I have a class and I use explicit constructor: .h class MyClass { public: explicit MyClass(const string& s): query(s) {} private: string query; } Is it obligatory or not to put explicit keyword in implementation(.cpp) file?
No, it is not. The explicit keyword is only permitted in the header. My gcc says: test.cpp:6: error: only declarations of constructors can be 'explicit' for the following code: class foo { public: explicit foo(int); }; explicit foo::foo(int) {}
273,720
273,748
Singleton Destructors
Should Singleton objects that don't use instance/reference counters be considered memory leaks in C++? Without a counter that calls for explicit deletion of the singleton instance when the count is zero, how does the object get deleted? Is it cleaned up by the OS when the application is terminated? What if that Singl...
You can rely on it being cleaned up by the operating system. That said, if you are in a garbage collected language with finalizers rather than destructors you may want to have a graceful shutdown procedure that can cleanly shutdown your singletons directly so they can free any critical resources in case there are usi...
273,836
288,306
Why Build Fails with CruiseControl.NET but it builds fine manually with same settings?
I have a project that builds fine If I build it manually but it fails with CC.NET. The error that shows up on CC.NET is basically related to an import that's failing because file was not found; one of the projects (C++ dll) tries to import a dll built by another project. Dll should be in the right place since there's a...
Can you change CC to use msbuild instead of devenv? That seems like the optimal solution to me, as it means the build is the same in both situations.
273,869
273,945
Performance implications of &p[0] vs. p.get() in boost::scoped_array
The topic generically says it all. Basically in a situation like this: boost::scoped_array<int> p(new int[10]); Is there any appreciable difference in performance between doing: &p[0] and p.get()? I ask because I prefer the first one, it has a more natural pointer like syntax. In fact, it makes it so you could replace...
OK, I've done some basic tests as per Martin York's suggestions. It seems that g++ (4.3.2) is actually pretty good about this. At both -O2 and -O3 optimization levels, it outputs slightly different but functionally equivalent assembly for both &p[0] and p.get(). At -Os as expected, it took the path of least complexity ...
273,908
8,362,045
c++ integer->std::string conversion. Simple function?
Problem: I have an integer; this integer needs to be converted to a stl::string type. In the past, I've used stringstream to do a conversion, and that's just kind of cumbersome. I know the C way is to do a sprintf, but I'd much rather do a C++ method that is typesafe(er). Is there a better way to do this? Here is the...
Now in c++11 we have #include <string> string s = std::to_string(123); Link to reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string
274,066
830,877
Search entire project for includes in Eclipse CDT
I have a large existing c++ codebase. Typically the users of the codebase edit the source with gvim, but we'd like to start using the nifty IDE features in Eclipse. The codebase has an extensive directory hierarchy, but the source files use include directives without paths due to some voodoo we use in our build proce...
This feature has already been implemented in the current CDT development stream and will be available in CDT 6.0, which will be released along with Eclipse 3.5 in June 2009. Basically if you have an #include and the header file exists somewhere in your project then CDT will be able to find it without the need to manual...
274,375
274,481
Intercepting traffic to memcached for statistics/analysis
I want to setup a statistics monitoring platform to watch a specific service, but I'm not quiet sure how to go about it. Processing the intercepted data isn't my concern, just how to go about it. One idea was to setup a proxy between the client application and the service so that all TCP traffic went first to my prox...
You didn't mention one approach: you could modify memcached or your client to record the statistics you need. This is probably the easiest and cleanest approach. Between the proxy and the libpcap approach, there are a couple of tradeoffs: - If you do the packet capture approach, you have to reassemble the TCP streams...
274,841
275,036
How can I correctly downcast the pointer from void* to TMemo* in C++Builder2009?
I am writing multi-thread socket chat in C++Builder 2009. It is almost complete in accordance with what I need to do but I have a little problem. I need to pass the TMemo* pointer into CreateThread WinAPI function which upcasts it to void*. I tryed this way: HANDLE xxx = MemoChat->Handle; hNetThread = CreateThread(NULL...
Call: TMemo* MemoChat = // You defined that somewhere I assume HANDLE hNetThread = CreateThread(NULL, 0, NetThread, MemoChat, 0, &dwNetThreadId); What is happening here is that any pointer you pass as the third parameter is being auto converted into a void pointer (or in WinTerms LPVOID). That's fine it does...
274,861
274,913
How do I calculate the week number given a date?
If I have a date, how do I calculate the week number for that date within that year? For example, in 2008, January 1st to January 6th are in week 1 and January 7th to the 13th are in week 2, so if my date was January 10th 2008, my week number would be 2. An algorithm would be great to get me started and sample code wou...
Pseudocode: int julian = getDayOfYear(myDate) // Jan 1 = 1, Jan 2 = 2, etc... int dow = getDayOfWeek(myDate) // Sun = 0, Mon = 1, etc... int dowJan1 = getDayOfWeek("1/1/" + thisYear) // find out first of year's day // int badWeekNum = (julian / 7) + 1 // Get our week# (wrong! Don't use this) int weekNum = ((ju...
274,951
275,033
Chaining of ordering predicates (e.g. for std::sort)
You can pass a function pointer, function object (or boost lambda) to std::sort to define a strict weak ordering of the elements of the container you want sorted. However, sometimes (enough that I've hit this several times), you want to be able to chain "primitive" comparisons. A trivial example would be if you were so...
You could build a little chaining system like so: struct Type { string first, last; int age; }; struct CmpFirst { bool operator () (const Type& lhs, const Type& rhs) { return lhs.first < rhs.first; } }; struct CmpLast { bool operator () (const Type& lhs, const Type& rhs) { return lhs.last < rhs.last; } }; st...
275,004
275,231
Timer function to provide time in nano seconds using C++
I wish to calculate the time it took for an API to return a value. The time taken for such an action is in the space of nanoseconds. As the API is a C++ class/function, I am using the timer.h to calculate the same: #include <ctime> #include <iostream> using namespace std; int main(int argc, char** argv) { ...
What others have posted about running the function repeatedly in a loop is correct. For Linux (and BSD) you want to use clock_gettime(). #include <sys/time.h> int main() { timespec ts; // clock_gettime(CLOCK_MONOTONIC, &ts); // Works on FreeBSD clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux } For wind...
275,128
275,149
Parallel assignment in C++
Is there any way of doing parallel assignment in C++? Currently, the below compiles (with warnings) #include <iostream> int main() { int a = 4; int b = 5; a, b = b, a; std::cout << "a: " << a << endl << "b: " << b << endl; return 0; } and prints: a: 4 b: 5 What I'd like it to print ... if it...
That's not possible. Your code example a, b = b, a; is interpreted in the following way: a, (b = b), a It does nothing. The comma operator makes it return the value of a (the right most operand). Because assignment binds tighter, b = b is in parens. The proper way doing this is just std::swap(a, b); Boost includes...
275,214
275,228
Scope and return values in C++
I am starting again with c++ and was thinking about the scope of variables. If I have a variable inside a function and then I return that variable will the variable not be "dead" when it's returned because the scope it was in has ended? I have tried this with a function returning a string and it did work. Can anyone ex...
When the function terminates, the following steps happen: The function’s return value is copied into the placeholder that was put on the stack for this purpose. Everything after the stack frame pointer is popped off. This destroys all local variables and arguments. The return value is popped off the stack...
275,249
275,310
When would I use uncaught_exception?
What is a good use case for uncaught_exception?
Herb Sutter seems to give good advice here. He doesn't know of a good use for it and says that some cases where it appears to be useful don't really work.
275,355
275,405
C++ Reading file Tokens
another request sorry.. Right now I am reading the tokens in one by one and it works, but I want to know when there is a new line.. if my file contains Hey Bob Now should give me Hey Bob [NEW LINE] NOW Is there a way to do this without using getline?
Yes the operator>> when used with string read 'white space' separated words. A 'White space' includes space tab and new line characters. If you want to read a line at a time use std::getline() The line can then be tokenized separately with a string stream. std::string line; while(std::getline(std::cin,line)) { /...
275,375
275,398
Inspecting STL containers in Xcode
From googling around it looks like Xcode (3.1 in my case) should be at least trying to give me a sane debug view of STL containers - or at least vectors. However, whenever I go to look at a vector in the debugger I just see M_impl, with M_start and M_finish members (and a couple of others) - but nothing in-between! (it...
The ability to view the container's items may rely on the complexity of the templated type. For trivial objects like int, bool, etc., and even simple class templates like template <class T> struct S { T m_t; } I normally have no problem viewing vector items in the debugger variable view. I say normally because ther...
275,484
275,494
Align cout format as table's columns
I'm pretty sure this is a simple question in regards to formatting but here's what I want to accomplish: I want to output data onto the screen using cout. I want to output this in the form of a table format. What I mean by this is the columns and rows should be properly aligned. Example: Test 1 Test2...
setw. #include <iostream> #include <iomanip> using namespace std; int main () { cout << setw(21) << left << "Test" << 1 << endl; cout << setw(21) << left << "Test2" << 2 << endl; cout << setw(21) << left << "Iamlongverylongblah" << 2 << endl; cout << setw(21) << left << "Etc" << 1 << endl; retur...
275,853
275,873
acceptable fix for majority of signed/unsigned warnings?
I myself am convinced that in a project I'm working on signed integers are the best choice in the majority of cases, even though the value contained within can never be negative. (Simpler reverse for loops, less chance for bugs, etc., in particular for integers which can only hold values between 0 and, say, 20, anyway....
I made this community wiki... Please edit it. I don't agree with the advice against "int" anymore. I now see it as not bad. Yes, i agree with Richard. You should never use 'int' as the counting variable in a loop like those. The following is how you might want to do various loops using indices (althought there is littl...
275,871
275,886
How to overcome GCC restriction "could not convert template argument '0' to 'Foo*'"?
Suppose I have code like this: template<class T, T initial_t> class Bar { // something } And then try to use it like this: Bar<Foo*, NULL> foo_and_bar_whatever_it_means_; GCC bails out with error (on the above line): could not convert template argument '0' to 'Foo*' I found this thread: http://gcc.gnu.org/ml/gc...
Rethinking your code is probably the best way to get around it. The thread you linked to includes a clear quote from the standard indicating that this isn't allowed.
275,994
276,056
What's the best way to do a backwards loop in C/C#/C++?
I need to move backwards through an array, so I have code like this: for (int i = myArray.Length - 1; i >= 0; i--) { // Do something myArray[i] = 42; } Is there a better way of doing this? Update: I was hoping that maybe C# had some built-in mechanism for this like: foreachbackwards (int i in myArray) { //...
While admittedly a bit obscure, I would say that the most typographically pleasing way of doing this is for (int i = myArray.Length; i --> 0; ) { //do something }
276,010
276,060
std::wcout to console window in Xcode
In an Xcode project, if I use std::cout to write to the console the output is fine. However, if I use std::wcout I get no output. I know that this is a thorny issue in C++, and I've been googling around to try and find a specific solution in the Xcode case. A couple of things I found that it was suggested should work w...
std::wcout should work just like std::cout. The following works fine on my MAC: #include <iostream> int main() { std::cout << "HI" << std::endl; std::wcout << L"PLOP" << std::endl; } Maybe (though some code would have been nice) its because you are not flushing the buffer. Remember that std::cout and std::wco...
276,066
276,068
Better way to implement count_permutations?
I need a function count_permutations() that returns the number of permutations of a given range. Assuming that the range is allowed to be modified, and starts at the first permutation, I could naively implement this as repeated calls to next_permutation() as below: template<class Ret, class Iter> Ret count_permutations...
The number of permutations for a range where all the elements are unique is n! where n is the length of the range. If there are duplicate elements, you can use n!/(n_0!)...(n_m!) where n_0...n_m are the lengths of duplicate ranges. So for example [1,2,3] has 3! = 6 permutations while [1,2,2] has 3!/2! = 3 permutations....
276,102
276,110
Catching all unhandled C++ exceptions?
Is there some way to catch exceptions which are otherwise unhandled (including those thrown outside the catch block)? I'm not really concerned about all the normal cleanup stuff done with exceptions, just that I can catch it, write it to log/notify the user and exit the program, since the exceptions in these casese are...
This can be used to catch unexpected exceptions. catch (...) { std::cout << "OMG! an unexpected exception has been caught" << std::endl; } Without a try catch block, I don't think you can catch exceptions, so structure your program so the exception thowing code is under the control of a try/catch.
276,173
276,570
What are your favorite C++ Coding Style idioms
What are your favorite C++ coding style idioms? I'm asking about style or coding typography such as where you put curly braces, are there spaces after keywords, the size of indents, etc. This is opposed to best-practices or requirements such as always deleting arrays with delete[]. Here is an example of one of my f...
When creating enumerations, put them in a namespace so that you can access them with a meaningful name: namespace EntityType { enum Enum { Ground = 0, Human, Aerial, Total }; } void foo(EntityType::Enum entityType) { if (entityType == EntityType::Ground) { /*code*/ ...
276,543
276,547
How to run a console application with command line parameters in Visual C++ 6.0?
I've got a console application that compiles and executes fine with Visual C++ 6.0, except that it will then only get as far as telling me about missing command line parameters. There doesn't seem to be anywhere obvious to enter these. How do I run or debug it with command line parameters?
I assume you're talking about setting the command line parameters for running in the IDE. Open the Project/Settings property page and go to the Debug tab. There's a "Program arguments" field you can put them into.
276,562
276,584
Using windows DLLs in a portable app
I have built a windows C++ application that I'd like to port to linux. The main reasons to do this is ease of system maintenance for our IT staff. Apart from the one windows machine that runs this application we're a linux only operation. The reason this application was built in-, and runs on- windows is that it uses a...
The most obvious middle ground would be to use Winelib. I do not know if it can link directly to a native DLL, but if not you probably could load it with LoadLibrary(). You could then split your application in two parts: a wrapper which only calls the DLL, and the rest of the code talking to your wrapper. You could hav...
276,761
277,306
Exposing a C++ API to Python
I'm currently working on a project were I had to wrap the C++ classes with Python to be able to script the program. So my specific experience also involved embedding the Python interpreter in our program. The alternatives I tried were: Boost.Python I liked the cleaner API produced by Boost.Python, but the fact that it...
I've used both (for the same project): Boost is better integrated with the STL, and especially C++ exceptions. Also, its memory management mechanism (which tries to bridge C++ memory management and Python GC) is way more flexible than SWIG's. However, SWIG has much better documentation, no external dependencies, and ...
276,769
277,687
How to expose std::vector<int> as a Python list using SWIG?
I'm trying to expose this function to Python using SWIG: std::vector<int> get_match_stats(); And I want SWIG to generate wrapping code for Python so I can see it as a list of integers. Adding this to the .i file: %include "typemaps.i" %include "std_vector.i" namespace std { %template(IntVector) vector<int>; } I'm...
%template(IntVector) vector<int>;
276,847
276,862
Slow performance of AddString in MFC
I've got a dialog with several largeish combo boxes in it (maybe several hundred items apiece). There's a noticeable delay at construction while these are populated (confirmed that it's them by profiling). My initial thought was that sorting was killing it's performance, but disabling sort and using InsertString instea...
You should be using CWnd::SetRedraw around your adds, to prevent the control updating all its internal state after each add. If you're not already doing it, then do this: combo.SetRedraw(FALSE); ... All the adds combo.SetRedraw(TRUE); combo.Invalidate(); You should also consider using the CComboBox::InitStorage fun...
276,884
276,889
Learning C# after C++
In a progression of languages, I have been learning C and C++. Now I would like to learn C#. I know there are some drastic differences between them - such as the removal of pointers and garbage collection. However, I don't know many of the differences between the two. What are the major differences that a C++ progra...
C# for C++ Developers is a great place to start. It is a table that lists the most important comparisons between the two languages. Once you have explored some of these differences, you might choose a self-contained project you have written in the past in C++, and re-write it in C#. In your first pass, you will proba...
277,258
277,362
How do I see a C/C++ source file after preprocessing in Visual Studio?
Let's say I have a source file with many preprocessor directives. Is it possible to see how it looks after the preprocessor is done with it?
cl.exe, the command line interface to Microsoft Visual C++, has three different options for outputting the preprocessed file (hence the inconsistency in the previous responses about Visual C++): /E: preprocess to stdout (similar to GCC's -E option) /P: preprocess to file /EP: preprocess to stdout without #line directi...
277,655
277,684
Why do C++ streams use char instead of unsigned char?
I've always wondered why the C++ Standard library has instantiated basic_[io]stream and all its variants using the char type instead of the unsigned char type. char means (depending on whether it is signed or not) you can have overflow and underflow for operations like get(), which will lead to implementation-defined v...
Possibly I've misunderstood the question, but conversion from unsigned char to char isn't unspecified, it's implementation-dependent (4.7-3 in the C++ standard). The type of a 1-byte character in C++ is "char", not "unsigned char". This gives implementations a bit more freedom to do the best thing on the platform (for ...
277,809
277,816
Call C# methods from C++ without using COM
Is there a way to create C# objects and call methods from unmanaged C++, but without using COM Iterop? I am looking for something like JNI (but for .Net), where you can manually create the VM, create objects, etc.
If you are using C++/CLI then you can interact directly with both the managed world and unmanaged code, so interop is trivial. You can also host the CLR yourself, and whilst the hosting API is COM based, you can then create any managed object. The process isn't a difficult as it sounds as a few API calls encapsulate...
278,025
280,880
Calling an XLL from (unmanaged) C++
I have an XLL Excel addin and now another team wants to use the same functionality in their project (unmanaged C++). Is there a way to interface with this XLL directly from C++?
Is you XLL un managed or unmanaged code? As far as I know, an unmanaged C++ XLL file is in fact a DLL that exports specific methods called by Excel. If your XLL has a .def file, maybe you could add method that would be called by the other team.
278,149
278,197
Programmatically navigating to the Windows Mobile home screen
We have an application that downloads some files in the background. Our application pops up when an Internet connection is made, and after prompting the user to accept the downloads, we'd like to switch back to the home screen while we do our stuff. We can't work out how to do to this. We can emulate pressing "back" a ...
Can you try setting the today screen as the foreground window? HWND hWnd = FindWindow(_T("DesktopExplorerWindow"), _T("Desktop")); SetForegroundWindow(hWnd);
278,260
281,230
How to implement CEditListCtrl
How to implement CEditListCtrl?. List control with edit capabality (Report/Grid view). I have a list view in Report View. It has some values. I need to extend this to edit the values present in the list view. I declared a class which inherits from CListCtrl. And I have handled the two Window messages to start and end t...
Thanks for all answers I have done it easily. I have handled the WM_LBUTTONDOWN. This handler pops up the edit box to get the new value for the field Handled LVN_ENDLABELEDIT to know the end of update. After receiving the above message, updated the values. “One thing I forgotten was to set the flag in the resource ...
278,273
278,353
How to guarantee files that are decrypted during run time are cleaned up?
Using C or C++, After I decrypt a file to disk- how can I guarantee it is deleted if the application crashes or the system powers off and can't clean it up properly? Using C or C++, on Windows and Linux?
Don't write the file decrypted to disk at all. If the system is powerd off the file is still on disk, the disk and therefore the file can be accessed. Exception would be the use of an encrypted file system, but this is out of control of your program.
278,429
280,031
What could cause a dynamic_cast to crash?
I have a piece of code looking like this : TAxis *axis = 0; if (dynamic_cast<MonitorObjectH1C*>(obj)) axis = (dynamic_cast<MonitorObjectH1C*>(obj))->GetXaxis(); Sometimes it crashes : Thread 1 (Thread -1208658240 (LWP 11400)): #0 0x0019e7a2 in _dl_sysinfo_int80 () from /lib/ld-linux.so.2 #1 0x048c67fb in __wait...
Some possible reasons for the crash: obj points to an object with a non-polymorphic type (a class or struct with no virtual methods, or a fundamental type). obj points to an object that has been freed. obj points to unmapped memory, or memory that has been mapped in such a way as to generate an exception when accessed...
278,784
278,830
What is the best compiler to use when you want to experiment with C++0x features?
What is the best compiler to experiment with C++0x features? I have been experimenting with GNU g++ 4.4.
Definitely GCC Trunk. ConceptGCC misses many features GCC trunk has. It is being merged into GCC currently though. It has all these features, including the new auto-typed variables (no new function declaration syntax yet though): http://gcc.gnu.org/projects/cxx0x.html . There is a GCC branch containing partial lambda...
278,870
278,904
Does VS2008 have somewhat C++0x support?
Does VS2008 have somewhat C++0x standard support? DUPLICATE Visual Studio support for new C / C++ standards?
No afaik. I believe VS2010 will have more support: http://www.microsoft.com/downloads/details.aspx?FamilyId=922B4655-93D0-4476-BDA4-94CF5F8D4814&displaylang=en http://blogs.msdn.com/vcblog/archive/2008/10/28/lambdas-auto-and-static-assert-c-0x-features-in-vc10-part-1.aspx
279,358
279,452
Invalid lock sequence error in an OpenSceneGraph application
I have an application that is built against OpenSceneGraph (2.6.1) and therefore indirectly OpenGL. The application initializes and begins to run, but then I get the following exception "attempt was made to execute an invalid lock sequence" in OpenGL32.dll. When I re-run it, I sometimes get this exception, and sometime...
Can you reproduce it with one of the standard examples? Can you create a minimal app that causes this? Do you have a machine with a different brand video card you can test it on (eg Nvidia vs. ATI) there are some issues with openscenegraph and bad OpenGL drivers. Have you tried posting to osg-users@lists.openscenegraph...
279,601
279,689
Boost.Lambda: Insert into a different data structure
I have a vector that I want to insert into a set. This is one of three different calls (the other two are more complex, involving boost::lambda::if_()), but solving this simple case will help me solve the others. std::vector<std::string> s_vector; std::set<std::string> s_set; std::for_each(s_vector.begin(), s_vector.en...
The error is really nasty, but boils down to the fact that it can't figure out which set::insert to use, since there's three overloads. You can work around the ambiguity by giving bind a helpful hand, by specifying a pointer to the function you wish to use: typedef std::set<std::string> s_type; typedef std::pair<s_ty...
279,729
279,761
How to wait until all child processes called by fork() complete?
I am forking a number of processes and I want to measure how long it takes to complete the whole task, that is when all processes forked are completed. Please advise how to make the parent process wait until all child processes are terminated? I want to make sure that I stop the timer at the right moment. Here is as a ...
I'd move everything after the line "else //parent" down, outside the for loop. After the loop of forks, do another for loop with waitpid, then stop the clock and do the rest: for (int i = 0; i < pidCount; ++i) { int status; while (-1 == waitpid(pids[i], &status, 0)); if (!WIFEXITED(status) || WEXITSTATUS(st...
279,854
279,878
How do I sort a vector of pairs based on the second element of the pair?
If I have a vector of pairs: std::vector<std::pair<int, int> > vec; Is there and easy way to sort the list in increasing order based on the second element of the pair? I know I can write a little function object that will do the work, but is there a way to use existing parts of the STL and std::less to do the work dir...
EDIT: using c++14, the best solution is very easy to write thanks to lambdas that can now have parameters of type auto. This is my current favorite solution std::sort(v.begin(), v.end(), [](auto &left, auto &right) { return left.second < right.second; }); ORIGINAL ANSWER: Just use a custom comparator (it's an opt...
279,956
279,984
Is there any way to programmatically set the comment attribute on a file in XP?
Links to point me in the correct direction, or sample code will be appreciated.
You can do it with some unmanaged calls, check the OLE32 function StgOpenPropStg() and StgOpenStorageEx() functions at MSDN: http://msdn.microsoft.com/en-us/library/aa380342(VS.85).aspx There's quite a bit to this but the function name should get you going.
280,069
283,937
GCC: program doesn't work with compilation option -O3
I'm writing a C++ program that doesn't work (I get a segmentation fault) when I compile it with optimizations (options -O1, -O2, -O3, etc.), but it works just fine when I compile it without optimizations. Is there any chance that the error is in my code? or should I assume that this is a bug in GCC? My GCC version is 3...
Now that you posted the code fragment and a working workaround was found (@Windows programmer's answer), I can say that perhaps what you are looking for is -ffloat-store. -ffloat-store Do not store floating point variables in registers, and inhibit other options that might change whether a floating point value is take...
280,143
280,447
Making a custom run Dialog with C or C++?
Well I would like to make a custom run dialog within my program so that the user can test commands without opening it themselves. The only problem is, msdn does not provide any coverage on this. If I cannot make my own custom run dialog and send the data to shell32.dll (where the run dialog is stored) I will settle for...
VBScript's CreateObject() function just creates an instance of a COM object. You can do exactly the same thing in C++, you just need to read a tutorial on how to access COM objects using C++ first.
280,162
280,526
Is there a way to do a C++ style compile-time assertion to determine machine's endianness?
I have some low level serialization code that is templated, and I need to know the system's endianness at compiletime obviously (because the templates specializes based on the system's endianness). Right now I have a header with some platform defines, but I'd rather have someway to make assertions about endianness wi...
If you're using autoconf, you can use the AC_C_BIGENDIAN macro, which is fairly guaranteed to work (setting the WORDS_BIGENDIAN define by default) alternately, you could try something like the following (taken from autoconf) to get a test that will probably be optimized away (GCC, at least, removes the other branch) in...
280,209
280,235
Creating a multithreading application in vc6 with boost library?
Is it possible to create a multithreading application in VC6 with boost library? If it is possible, what are some relevant tutorials.
Yes, I have done this successfully, but with Boost v1.30.0. So if you have trouble with the latest versions of the Boost libraries, you might want to go back a year or five. I recall I started getting all sorts of internal compiler errors, et al., when trying to upgrade Boost -- so I didn't, but rather went on using v1...
280,345
280,364
How do I use PostThreadMessage to close internet explorer from C++
I'm trying to start iexplore.exe let it run for 5 seconds and then close it again. iexplore opens just fine however it doesn't close when I call the PostThreadMessage. Can anyone see what I'm doing wrong? Here is my code: CString IEPath = "C:\\Program Files\\Internet Explorer\\IEXPLORE.EXE";//GetIEPath(); //IEPath += ...
if you can enumerate the windows on the desktop and send a WM_CLOSE to the IE window , it might work .. you can use the spy programme to get the window class of the IE window
280,347
280,443
How to convert Unicode string into a utf-8 or utf-16 string?
How to convert Unicode string into a utf-8 or utf-16 string? My VS2005 project is using Unicode char set, while sqlite in cpp provide int sqlite3_open( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); int sqlite3_open16( const void *filename, /* Dat...
Short answer: No conversion required if you use Unicode strings such as CString or wstring. Use sqlite3_open16(). You will have to make sure you pass a WCHAR pointer (casted to void *. Seems lame! Even if this lib is cross platform, I guess they could have defined a wide char type that depends on the platform and is l...
280,477
280,530
_CRT_DEBUGGER_HOOK throws exception
I'm having a problem converting my program from VS2005 to VS2008. When I run the program in VS2008, the application starts up fine but when start playing around with the application it crashes giving me this error: "Microsoft Visual Studio C Runtime Library has detected a fatal error" And then the debugger points me to...
Make sure all of your dependencies are also compiled with VS2008 debug. I experienced this same issue when compiling a program in VS2008-debug, and some of the dependent DLLs where compiled in VS2003, and also when compiling a program in VS2008-debug and some of the dependencies where compiled as release.
280,624
280,665
Which is faster - C# unsafe code or raw C++
I'm writing an image processing program to perform real time processing of video frames. It's in C# using the Emgu.CV library (C#) that wraps the OpenCV library dll (unmanaged C++). Now I have to write my own special algorithm and it needs to be as fast as possible. Which will be a faster implementation of the algorit...
it needs to be as fast as possible Then you're asking the wrong question. Code it in assembler, with different versions for each significant architecture variant you support. Use as a guide the output from a good C++ compiler with optimisation, because it probably knows some tricks that you don't. But you'll probably b...
280,654
280,657
Why can't I store boost::function in std::list?
I get the following compilation error: error: expected `;' before 'it'" Here's my code: #include <boost/function.hpp> #include <list> template< class T > void example() { std::list< boost::function<T ()> >::iterator it; } Why does this happen? How can I fix it?
You need to put typename in front of that line, since the type you do ::iterator upon is dependant on the template-parameter T. Like this: template< class T > void example() { typename std::list< boost::function<T ()> >::iterator it; } Consider the line std::list< boost::function<T ()> >::iterator * it; which co...