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
3,669,461
3,669,540
singleton pattern with global variable
Consider the following code parts: this is Timing.h: class Timing { public: //creates a single instance of timing. A sinlgeton design pattern Timing *CreateInstance(); private: /** private constructor and a static instance of Timing for a singleton pattern. */ Timing(); static Timing *_singleInstan...
You don't need to create the instance. Change the name of CreateInstance() to GetInstance(). Then, when you want to access your timing object, call GetInstance. The singleton will be created the first time you access it. You won't be implementing the first option if you do this because you won't keep hold of the return...
3,669,611
3,709,195
Bounding box using OpenCV
I want to get the bounding box of a filled black circle on a white background using opencv BoundingRect. I used the sample code from http://cgi.cse.unsw.edu.au/~cs4411/wiki/index.php?title=OpenCV_Guide#Finding_bounding_boxes_around_regions_of_a_binary_image but failed to get the properties of the bounding box and draw ...
I made my own code for calculating the bounding box: int* get_boundingbox( IplImage* img_input){ int width = img_input->width; int height = img_input->height; int* Output = NULL; Output = new int[4]; //----- Top boundary ----- for(int ii = 0 ; ii < height ; ii++ ){ int value; for(int jj = 0...
3,669,833
3,669,886
C++11 scope exit guard, a good idea?
I've written a small utility class for C++11 which I use as a scope guard for easier handling of exception safety and similar things. Seems somewhat like a hack. But I'm suprised I haven't seen it somewhere else using C++11 features. I think boost has something similar for C++98. But is it a good idea? Or are there pot...
But is it a good idea? Sure. A related topic is the RAII paradigm. Or are there potential problems I have missed? You don't handle exceptions. Is there already a similar solution (with C++0x features) in boost or similar? Alexandrescu came up with ScopeGuard a long time back. Both Boost and std::tr1 has a...
3,669,940
3,670,012
What if I don't join thread on "destruction" in release builds?
In many cases I have classes that act like active objects (have a thread). And to avoid access violations I always have to wait for join in the destructor. Which is usually not a problem. However imagine a release build with some bug (deadlock, livelock etc.) that causes join() not to return on time or at all, this wo...
It would be better, if feasible, to activate some kind of structure analysis to find the cycle and break the deadlock. It might miss some deadlocks on destruction, but then again it might also be applicable to catch deadlocks outside that context.
3,670,031
3,670,077
static string constants in class vs namespace for constants [c++]
I want to declare string constants that will be used across various classes in the project. I am considering two alternatives Option 1: #header file class constants{ static const string const1; }; #cpp file const string constants::const1="blah"; Option 2: #header file namespace constants{ static const str...
Update 2 years later: Every global accessible by more than one source file should be wrapped in an inline function so the linker shares the object between the files, and the program initializes it properly. inline std::string const &const1() { static std::string ret = "hello, world!"; return ret; } The inline ...
3,670,178
3,670,275
How to understand the call stack of Visual Studio?
VCamD.ax!CFactoryTemplate::CreateInstance() + 0x3f bytes > VCamD.ax!CClassFactory::CreateInstance() + 0x7f bytes What's 0x7f and 0x3f?
You got .pdb files that were stripped. Their source code file and line number info was removed. Typical for example for .pdb files you can get from the Microsoft symbol server. Which is okay, you can't get the source code anyway. Without the line number info, the debugger falls back to using the 'closest' symbol who...
3,670,183
3,670,250
Using stringstream and an int variable in C++ to verify that input is an int
void get_english_input() { string input = " "; stringstream my_string(input); int ft; double in; while(true) { cout << "Enter an integer value of feet." << endl; getline(cin, input); my_string << input; if(my_string >> ft) break; cout << "Inva...
You could reset the error state of my_string: my_string.clear(); my_string.ignore( /* big number of choice */ ); But I think it would be easier here just to reinitialize it every time: while(true) { cout << "Enter an integer value of feet." << endl; getline(cin, input); stringstream my_string(input);
3,670,308
3,670,404
call by reference with array
What I want to do is something like this: void dosth(bool& a) { a[2] = false; } int main() { bool a[10]; dosth(a); return 0; } I want to call by reference, with an array as argument. How to realize this? Thx
Like this: typedef bool array_type[10]; void dosth(array_type& a) { a[2] = false; } int main() { array_type a; dosth(a); } Or without the typedef: void dosth(bool (&a)[10]) { a[2] = false; } int main() { bool a[10]; dosth(a); } Or more generally: template <size_t Size> void dosth(bool (&a)[...
3,670,601
3,670,725
How to create analog for such C# StreamProxyApplication function in C++ using Boost library?
I haven't done work in C/C++ for a little bit and was just wondering if any one can help me with porting this .Net C# code into C++ using Boost library (Boost.Asio) So I have one function: private const int bufferSize = 8192; /// <summary> /// The entry point of the application. /// </summary> /// <param name="args">...
I don't think this is going to be simple at all to port to C++. What takes one line in C# requires a whole bunch of infrastructure in C++, because you have the entire .Net framework at your fingertips in the CLR. I believe boost::asio is a lower-level interface than you need for this. If you do have to do this in C+...
3,670,928
3,671,445
Problem starting debug build on Windows Server 2008R2
I have a Windows service that is written in C++ using VS2008. I now want to debug that service remotely on my Windows Server 2008R2. But when I start the service I get an application error saying: Faulting application name: MyService.exe, version: 1.99.96.0, time stamp: 0x4c87cf49 Faulting module name: MSVCR90.dll, ...
// MessageText: // // An invalid parameter was passed to a C runtime function. // #define STATUS_INVALID_CRUNTIME_PARAMETER ((NTSTATUS)0xC0000417L) This has nothing to do with the CRT deployment, although it is mysterious that you got the debug build deployed. The code is simply crashing on a runtime error, raised by...
3,670,984
3,671,015
GetTokenInformation() first call. What for?
Looking at MSDN documentaion for GetTokenInformation() and the Getting the Logon SID example, GetTokenInformation() needs to be called twice. The first call is to get the buffer size. So, buffer size of what? Just say I use TokenUser as its second parameter, I see that the dwReturnLength returned by first call is not t...
The TOKEN_USER structure contains pointers (in particular, a pointer to a SID that itself has variable length). Those pointers have to point somewhere. The API function will expect a buffer big enough to hold not only the the TOKEN_USER structure, but also all the things that structure points to. The function tells you...
3,671,008
3,671,411
Crop function BitBlt(...)
I want to create a crop function in an existing engine. This is what I already have: bool Bitmap::Crop(RECT cropArea) { BITMAP bm; GetObject(m_Handle, sizeof(bm), &bm); HDC hSrc = CreateCompatibleDC(NULL); SelectObject(hSrc, m_Handle); HDC hNew = CreateCompatibleDC(NULL); HBITMAP hBmp = CreateCompatibleBitmap(hNew, b...
Never create a compatible bitmap from a 'fresh' memory DC. Unless that is you WANT to create a 1bpp bitmap - the default bitmap selected in a new memory DC is a 1x1 1bpp bitmap - so any compatible bitmap you create will match that. Which does tend to result in all black output. Your color bitmap in in hSrc, so use that...
3,671,125
3,671,146
MFC CFindFile::FindNextFile usage
The documentation for CFindFile states that Nonzero if there are more files; zero if the file found is the last one in the directory or if an error occurred. To get extended error information, call the Win32 function GetLastError. If the file found is the last file in the directory, or if no matching files...
If there are no files, your call to CFileFind::FindFile will return false. You need to call this before you can call FindNextFile.
3,671,145
3,671,323
Passing variadic class template's sub-classes to function that only accepts the base class (via parameter pack deduction/inference)
**I've gotten a few suggestions to make my function pure generic, which would work, but I'd prefer limiting the function to only accept Base and its children. Having trouble making a function that can accept arguments of a variadic template class base type, while the function will actually be called with classes that d...
Edit: If you need both parameter packs, you can just put both in the template specification: template<typename... ArgsA, typename... ArgsB> string moosh_together(const Base<ArgsA...>& A, const Base<ArgsB...>& B) { return get<0>(A.data) + get<1>(B.data); } This works because the parameter packs are inferred from ar...
3,671,234
3,671,304
What is the purpose of the second parameter to std::allocator<T>::deallocate?
In here is declaration of deallocate mem. of allocator class. My question is what for is second argument in this declaration? If this function calls operator delete(_Ptr) this argument is unused so what's for is it there? Thanks. Excerpt from MSDN: Frees a specified number of objects from storage beginning at a specifi...
When you call deallocate, you must give it a pointer that you previously obtained from calling allocate and the size that you passed to allocate when you initially allocated the memory. For example, #include <memory> std::allocator<int> a; int* p = a.allocate(42); a.deallocate(p, 42); // the size must match the ...
3,671,584
3,671,658
Errors when using map() in C++
I wrote a piece of code and used map and vector but it shows me something I can't get. I'll be thankful if someone help me in this way and correct my code or give me some hints. The code is: // For each node in N, calculate the reachability, i.e., the // number of nodes in N2 which are not yet covered by at...
You declared the position object as followed : std::map<Vector, std::vector<const NeighborTuple *> > position; And you are trying to push NeighborTuple * inside... Try using const NeighborTuple *
3,671,935
3,672,985
Help with FFT(Fast Fourier Transforms) and/or DSP
Im trying to do a screen-flashing application, that flashes the screen according to the music(which will be frequencies, such as healing frequencies, etc...). I already made the player and know how will I make the screen flash, but I need to make the screen flash super fast according to the music, for example if the mu...
This is a difficult problem, requiring more than an FFT. I'll briefly describe how I implemented beat detection when I was writing software for professional DJ equipment. First of all, you'll need to cut down the amount of data you're dealing with, since there are only two or three beats per second, but tens of thousan...
3,672,088
3,672,117
undefined reference error due to use of static variables
I asked a question earlier today about singletons, and I'm having some difficulties understanding some errors I encountered. I have the following code: Timing.h class Timing { public: static Timing *GetInstance(); private: Timing(); static Timing *_singleInstance; }; Timing.cpp #include "Timing.h" stat...
1: static means "local linkage" when used for a function declaration/definition outside a class-declaration. Local linkage means that the particular function can only be referenced from code inside this particular file, and that doesn't make much sense with a method in a class. 2: Since your class declaration can be i...
3,672,116
3,749,578
How can I optimize my screencasting utility?
I'm developing a screencasting utility in C++. It basically captures desktop frames and creates an AVI file. The algorithm is as follows: Create a thread: this->m_hThread=CreateThread(NULL,0,thScreenCapture,this,0,NULL); Capture desktop in thScreenCapture n times per second (like 5 fps). obj->Capture(); In Capture(),...
Are you writing the AVI file yourself? A noble effort, but there are APIs to help with this task. If you're working on the windows platform, I'd suggest considering using the DirectShow or Media Foundation APIs to mux the audio and video to disk. DirectShow is the API for A/V capture, streaming and muxing on the wind...
3,672,234
3,672,390
C++ function to count all the words in a string
I was asked this during an interview and apparently it's an easy question but it wasn't and still isn't obvious to me. Given a string, count all the words in it. Doesn't matter if they are repeated. Just the total count like in a text files word count. Words are anything separated by a space and punctuation doesn't mat...
A less clever, more obvious-to-all-of-the-programmers-on-your-team method of doing it. #include <cctype> int CountWords(const char* str) { if (str == NULL) return error_condition; // let the requirements define this... bool inSpaces = true; int numWords = 0; while (*str != '\0') { if (std...
3,672,315
3,672,347
C++ - boost::any serialization
As far as I understand, there is no serialization (boost::serialization, actually) support for boost::any placeholder. Does someone know if there is a way to serialize a custom boost::any entity? The problem here is obvious: boost::any uses template-based placeholders to store objects and typeid to check if boost::any_...
It is not possible at all, at least for arbitrary types. Note that maybe you could serialize using some tricky code (like finding the size of the elements contained in the any), but the any code relies on the compiler statically putting the any type_code and the proper types inside the placeholder. You surely cannot do...
3,672,533
3,673,050
c++ get other windows messages
im learning to make things to other windows like resize the ie or any type of window. the only problem i don't know how i can get or give messages to other windows. so like i pressed a key in ie i would like to get that message to my program too! any idea
To get the messages that are sent to windows programs you have to install a hook in order to listen to the messages you want. You do this via the SetWindowsHookEx function. However, I believe that you should read a book about this kind of behaviour, since there are certain rules you have to apply. For instance, before ...
3,672,563
3,672,617
C and C++ difference in sizeof('x')
Possible Duplicate: Why are C character literals ints instead of chars? Why when using C does sizeof('x') return 4 but sizeof('x') in C++ returns 1? C++ normally strives to be nothing more than a superset of C so why do the two results diverge? Edit Just some further clarification. This seems like a deliberate move...
To quote the C++ standard ISO 14882:2003, annex C.1.1 clause 2.13.2 Change: Type of character literal is changed from int to char Rationale: This is needed for improved overloaded function argument type matching. For example: int function( int i ); int function( char c ); function( ’x’ ); It is preferable that this c...
3,672,591
3,672,969
c++ create program runs in the background
i wanna make a program runs in the background and shows an icon in notification area of taskbar. I'm using win32. What api should i use? Do you know any good tutorials?
To make a program run in the background, you either add it as a service or make it "unavailable" to shutdown (for instance, hide the window for the program). To add an icon in the toolbar you use winapi. Call Shell_NotifyIcon and pass in a NOTIFYICONDATA structure This should be defined somewhere enum TrayIcon { ID...
3,672,597
3,672,642
how to get type of variable?
example: template<typename T> struct type_of { typedef boost::mpl::if_<boost::is_pointer<T>, typename boost::remove_pointer<T>::type, T >::type type; }; int main() { int* ip; type_of<ip>::type iv = 3; // error: 'ip' cannot appear in a constant-expression } Thanks!
You cannot. Either use compiler-specific extensions or Boost's Typeof (which hides the compiler-specific behavior behind a consistent interface). In C++0x, you may use decltype: decltype(ip) iv = 3; If your compiler supports this aspect of C++0x, you're in luck.
3,672,708
3,676,270
How do Boost Bind, Boost Function, Boost Signals and C++ function pointers all relate to each other?
As the title might convey, I'm having problems seeing how Boost Bind, Boost Function, Boost Signals and C++ function pointers all play together. From my understanding, Boost Bind and Boost Function in conjunction work like Signals while Signals is an abstraction above Bind and Function. Also, compared to standard C++ ...
See here a discussion on the different concepts of c-function-pointers, boost function and boost signal. Imho the main difference between the two boost function objects and c-function-pointers is the ability to add default parameters. This makes it easy to use methods (functions with a invisible first parameter -> the...
3,672,753
3,672,791
How to pass variable number of arguments from one function to another?
Is there any way to directly pass a variable number of arguments from one function to another? I'd like to achieve a minimal solution like the following: int func1(string param1, ...){ int status = STATUS_1; func2(status, param1, ...); } I know I can do this using something like the following, but this code is goi...
No, you have to pass the varargs using a va_list as per your second example. It's just 3 lines extra code, if you want to avoid duplicating those lines, and func2 is always the same, or atleast takes the same parameters, make a macro out of it. #define CALL_MY_VA_FUNC(func,param) do {\ va_list args; \ v...
3,672,841
3,791,297
C++0x and Friend functions and boost::make_shared
If I have a class with a private construction, using boost::make_shared() to construct a shared_ptr of that class from within a member function of that class will issue a compiler error using gcc 4.6. #include "boost/shared_ptr.hpp" #include "boost/make_shared.hpp" class Foo { private: Foo(int a){}; public: st...
Unfortunately, it is not specified which function actually calls the constructor in make_shared, so you cannot make that function a friend. If you have a class with a private constructor like this then you thus cannot construct an instance with make_shared. However, what you can do is create a derived class with a publ...
3,673,126
3,673,162
Is there a inbuilt mechanism so that bytes writen to the pipe can overwrite earlier bytes if buffer is not enough?
Pretty much like a queue,when the queue is full an new member wants to come in,just remove the first member at the head of the queue. Is there such a default mechanism in windows? If yes how can I do that in c/c++?
No. Once written, bytes have to be read on the far end before bytes written later on the sending side can be read. It would not be much of a pipe otherwise. Any discard would have to be implemented on the receiving side. Or implement a write queue on the send side and discard as needed if you find yourself blocked ...
3,673,165
3,673,198
Bullet algorithm having trouble with rotation on the X
Here is what I'm trying to do. I'm trying to make a bullet out of the center of the screen. I have an x and y rotation angle. The problem is the Y (which is modified by rotation on the x) is really not working as intended. Here is what I have. float yrotrad, xrotrad; yrotrad = (Camera.roty / 180.0f * 3.141592654f...
You need to scale X and Z by cos(xradrot). (In other words, multiply by cos(xradrot)). Imagine you're pointing straight down the Z axis but looking straight up. You don't want the bullet to shoot down the Z axis at all, this is why you need to scale it. (It's basically the same thing that you're doing between X and ...
3,673,267
3,673,284
Why is C++ a mid-level language?
Why is C++ a mid-level language? It can almost do everything and the worlds most widely used operating system is written in it. [Note: SO C++ Info page quotes Wikipedia citing C++ The Complete Reference Third Edition, by Herbert Schildt, It is regarded as a "middle-level" language, as it comprises a combination of bot...
"mid language" is not English, so one has to guess at what you mean. If you mean, "a language of intermediate level of abstraction", that's a fair assessment, although you are correct that, compared with most other language, it stretches to cover an uncomfortably wide range of abstraction levels. Languages that provid...
3,673,353
3,673,368
Anonymous Namespace Ambiguity
Consider the following snippet: void Foo() // 1 { } namespace { void Foo() // 2 { } } int main() { Foo(); // Ambiguous. ::Foo(); // Calls the Foo in the global namespace (Foo #1). // I'm trying to call the `Foo` that's defined in the anonymous namespace (Foo #2). } How can I refer to something inside an...
You can't. The standard contains the following section (§7.3.1.1, C++03): An unnamed-namespace-definition behaves as if it were replaced by namespace unique { /* empty body */ } using namespace unique; namespace unique { namespace-body } where all occurrences of unique in a translation unit are replaced by ...
3,673,546
3,673,672
Dynamic menu using mfc
I would like to add a menu item to my main menu and then populate it with items at run time. How would I do this? And besides adding items how would I have a message map entry for them since I do not know the id?
You can create a CMenu object dynamically like this: CMenu *menu = new CMenu; menu->CreatePopupMenu(); // Add items to the menu menu->AppendMenu(MF_STRING, menuItemID, "Text"); ... Then add this sub-menu to your main menu: wnd->GetMenu()->AppendMenu(MF_POPUP, (UINT_PTR)menu->m_hMenu, "Menu Name"); As for the message ...
3,673,587
3,673,781
How do you get info for an arbitrary time zone in Linux / POSIX?
Ideally, what I'd like to be able to do is take the name of a time zone and call a function to ask for its corresponding time zone info (offset from UTC, DST offset, dates for DST switch, etc.) in Linux. However, I can't find any way to do this. The information exists in /usr/share/zoneinfo/ in the various binary files...
The tzcode package (found along with the data at ftp://ftp.iana.org/tz/releases) contains a description of the tzfile format along with a header file tzfile.h for working directly with that data.
3,673,684
3,673,705
Peeking the next element in STL container
Is it possible to peek next element in a container which the iterator currently points to without changing the iterator? For example in std::set, int myArray[]= {1,2,3,4}; set <int> mySet(myArray, myArray+4); set <int>::iterator iter = mySet.begin(); //peek the next element in set without changing iterator. mySet.era...
Not with iterators in general. An iterator isn't guaranteed to be able to operate non-destructively. The classic example is an Input Iterator that actually represents an underlying input stream. There's something that works for this kind of iterator, though. A Forward Iterator doesn't invalidate previous copies of itse...
3,673,720
3,676,273
C++ template metaprogramming to create a boost::variant from a shared_ptr and a boost::static_visitor
As a personal exercise, I want to implement the visitor pattern using shared_ptr. I am familiar with Robert Martin's acyclic visitor paper but find the intrusive nature of the virtual accept() and necessary creation of an {X}Visitor class for each {X} class unpleasant. I like the boost::static_visitor class as it enc...
I may be misunderstanding the question, but if you want to use the same variant_visitor for a variant containing shared pointers instead of plain pointers, perhaps this can be achieved with another visitor that obtains the pointer from the shared_ptr and passes it on to the other visitor. #include <algorithm> #include ...
3,673,831
3,674,370
Need for out of class definition of static variable?
My question: What exactly is the out of class definition of k doing under the hood to make sure it's address is available? #include <iostream> using namespace std; class A { public: static const float k = 7.7; }; //const float A::k; --> without this line compiler error int main() { cout << &A::k; }
Other answers have already given the how to fix it -- I'll go more into the why. When you do this: #include <iostream> using namespace std; class A { public: static const float k = 7.7; }; int main() { cout << A::k; } The compiler is probably in reality generating this: #include <iostream> using namespace st...
3,674,247
3,674,759
Is std::array<T, S> guaranteed to be POD if T is POD?
I'm currently writing a C++ memory editing library and for the read/write APIs I use type traits (std::is_pod, std::is_same) and boost::enable_if to provide 3 overloads: POD types. e.g. MyMem.Read(SomeAddress); String types. e.g. MyMem.Read>(SomeAddress); (This doesn't actually read out a C++ string, it reads out a C-...
§23.3.1: An array is an aggregate (8.5.1) that can be initialized with the syntax array a<T, N> = { initializer-list }; where initializer-list is a comma separated list of up to N elements whose types are convertible to T. In C++03, POD was defined in terms of aggregate: a class where every subobject is native or a...
3,674,456
3,674,505
Why this is causing C2102: '&' requires l-value
I was wondering, why the following way of code (Already commented out) will cause C2102: '&' requires l-value Is there a better way to avoid using tmp variable? class a { private: int *dummy; public: int* get_dummy() const { return dummy; } }; int main() { a aa; // error C2102: '&' require...
Because a::get_dummy() returns a unnamed temporary object (int pointer). Object returned by function sit ontop of the stack frame and it is meaningless to get its address since it might be invalid after expression ends.
3,674,648
3,674,795
Converting a lambda to a std::tr1::function
Using visual studio 2008 with the tr1 service pack and Intel C++ Compiler 11.1.071 [IA-32], this is related to my other question I'm attempting to write a functional map for c++ which would work somewhat like the ruby version strings = [2,4].map { |e| e.to_s } So i've defined the following function in the VlcFunction...
The problem is that a lambda is not a std::function even if it can be converted. When deducing type arguments, the compiler is not allowed to perform conversions on the actual provided arguments. I would look for a way to have the compiler detect the type U and let the second argument free for the compiler to deduce: t...
3,674,876
3,674,955
Why would the conversion between derived* to base* fails with private inheritance?
Here is my code - #include<iostream> using namespace std; class base { public: void sid() { } }; class derived : private base { public: void sid() { } }; int main() { base * ptr; ptr = new derived; // error: 'base' is an inaccessible base of 'derived' ptr->sid(); return 0; }...
$11.2/4 states- A base class B of N is accessible at R, if an invented public member of B would be a public member of N, or R occurs in a member or friend of class N, and an invented public member of B would be a private or protected member of N, or R occurs in a member or friend of a class P derived from N, and ...
3,674,929
3,674,978
C++ v-table: Part of the language or compiler dependent?
Is the v-table (virtual method table) a part of the C++ specification, or is it up to the compiler to solve the virtual method lookups? In case it's part of the spec: Why? I'd guess that it's compiler dependent, but someone said to me that it's part of the spec. References are very welcome!
1.7 The C++ memory model 3 [...] Various features of the language, such as references and virtual functions, might involve additional memory locations that are not accessible to programs but are managed by the implementation. [...] There you have it. It is up to the implementation.
3,675,017
3,675,553
nested STL structure
I am wondering about the performance of nested STL structure related to compile and run time. So if want to implement something a nested structure e.g. that way vector<vector<map<int, vector<> > > > How could the access to each container effect on the whole execution time? Thanks for any help. Giving some specific lin...
How could the access to each container effects on the whole execution time? It's not much to say, even less to reference - except for the STL. std::vector provides O(1) access performance to the elements (the random access), std::map provides O(log(n)) access performance to the elements. IOW: vector<vector<map<int, v...
3,675,041
3,682,399
QT Plugin , VTK QT Widget , Multi-thread and Linking question?
Greetings all, This is going to be a long question,skip the [Background] if its not that neccasary ;) [Background] I am developing a modular QT based application.Application is extentible via QT based plugins. As shown in the figure, there are mainly 3 parts .(numbers in red) 1) libAppCore - the core of the applicati...
Finally I found the solution.. I had compiled VTK libraries for Release version.But all other components I build Debug version. Since there are two QT libraries are linked(Release and Debug version), QT create two threads for each version. Finally I build all with Release build option and everything works fine.
3,675,059
3,677,129
How could I sensibly overload placement operator new?
C++ allows overloading operator new - both global and per-class - usual operator new, operator new[] used with new[] statement and placement operator new separately. The former two of those three are usually overloaded for using customized allocators and adding tracing. But placement operator new seems pretty straightf...
The correct answer is you cannot replace operator placement new. §18.4.​1.3 Placement forms These functions are reserved, a C++ program may not define functions that displace the versions in the Standard C++ library. The rationale: The only purpose of the allocation and deallocation operators is to allocate and dea...
3,675,309
3,675,580
WinAPI File In-/Output with std::strings instead of char arrays?
due to performance reasons I didn't feel like using fstream for just one time. Seems like a very bad idea to use WinAPI functions with a std::string instead of a plain char array. All in all I would like you to tell me why the following snippet just won't work (empty stBuffer stays empty) and what I'd need to do to get...
Because a std::string can contain embedded '\0' characters, it has to keep track of its own length in a separate way. Your problem is that std::string::reserve() does not change the length of the string. It just pre-allocates some memory for the string to grow into. The solution is to use std::string::resize() and let ...
3,675,450
3,676,685
170 MB Hello World -> Deploying apps with Qt
I'm new to Qt but no problem in the C++. I used Qt Creator and made a simple program with a button (like a hello world) then I built the project. I was not able to run the executable file in windows itself (outside the creator) because it needed these DLL files: libgcc_s_dw2-1.dll mingwm10.dll QtGuid4.dll QtCored4.dll ...
Why don't you do a release build and use the release dlls instead of the debug dlls which are much larger. Since this is regarding size: Debug libraries QtCored4.dll = ~37MB QtGui4d.dll = ~157MB Release libraries QtCore.dll = ~2.3Mb QtGui4.dll = ~9MB (from looking at the sizes in my Qt\version\bin directory)
3,675,536
3,675,794
Undefined reference while using g++ for compilation
I am getting following error p.c uses some of the function implemented in md4.c. p.c , when compiled with gcc works but it does not work with g++, gives undefined method error. Am I missing something obivious ? [prafulla@ps7374 sample] $g++ -c -o md4.o md4.c [prafulla@ps7374 sample] $gcc -c -o md4.o md4.c [prafulla@ps...
Because C++ supports function overloading, the C++ compiler must ensure that the linker sees two different names for void foo(int) and void foo(float). The most common way to do that is to encode information about the parameters into the names presented to the linker. As C does not have overloading, there is also no ne...
3,675,586
3,675,684
Can I use global operator new for a class having operator new overloaded?
Suppose I have a class with overloaded operator new. class Class { public: void* operator new( size_t ); void operator delete( void* ); }; Will objects of that class always be allocated with the overloaded operator new when I use new Class() or is it possible that the default operator new is used when new Class(...
The overloaded operator new and operator delete will always be used unless you explicitly do something like this: // Allocate using global new. MyClass* my_object = ::new MyClass(); // Use object normally. my_object->my_method(); // Deallocate using global delete. ::delete my_object; Or, as a somewhat extreme illust...
3,675,658
3,683,035
How to get __FILE__ as absolute path on Intel C++ compiler
I've tried using the /Fc flag which works with visual studio but get a message that it isn't recognized by the intel compiler. I'm trying to write a test which uses data from a directory relative to the cpp test file, however the executable will be deployed elsewhere so it's hard to get it relative to the exe... hence...
This is apparently a bug in the Intel Compiler, it silently accepts and then ignores the /FC flag which should trigger absolute paths. The best work around I can find came from this thread that I started over at Intel forums: To get __FILE__ to generate an absolute path it has to be in a header file which has been inc...
3,675,829
3,675,881
Ambiguous call to templated function due to ADL
I've been bitten by this problem a couple of times and so have my colleagues. When compiling #include <deque> #include <boost/algorithm/string/find.hpp> #include <boost/operators.hpp> template< class Rng, class T > typename boost::range_iterator<Rng>::type find( Rng& rng, T const& t ) { return std::find( boo...
ADL isn't a fallback mechanism to use when "normal" overload resolution fails, functions found by ADL are just as viable as functions found by normal lookup. If ADL was a fallback solution then you might easily fall into the trap were a function was used even when there was another function that was a better match but ...
3,675,833
3,675,846
How to find out which Win API functions are called from a compiled c/c++ dll
I have a compiled C/C++ Dll. I would like to know which external API function is called by this Dll. Do you know any tools which can provide these informations. Thanks.
You can use Dependency Walker to see API imports of a DLL. Of course that doesn't tell you if the DLL does dynamic loading, or COM usage. Next to that you could use the much heavier logexts extension to windbg, which will dump all API calls at runtime.
3,676,074
3,676,077
How to delete IE addressbar history on Vista/Win7?
I asked same question on stackoverflow. First, here is a picture of what I see http://img713.imageshack.us/img713/4797/iedrop.png I need an solution to clear addressbar dropdawn, but not using ClearMyTracksByProcess or IE dialogs. I need to delete only a specific URL and all his traces. I deleted manually all traces of...
Finally I found solution. HRESULT CreateCatalogManager(ISearchCatalogManager **ppSearchCatalogManager) { *ppSearchCatalogManager = NULL; ISearchManager *pSearchManager; HRESULT hr = CoCreateInstance(CLSID_CSearchManager, NULL, CLSCTX_SERVER, IID_PPV_ARGS(&pSearchManager)); if (SUCCEEDED(hr)) { ...
3,676,221
3,676,271
When abort() is preferred over exit()?
I know the differences between the two. One notable thing is that abort() sends SIGABRT signal, so it may be relevant when your software relies on them. But for a typical application exit() seems to be more safe version of abort()...? Are there any other concerns to use abort() instead of exit()?
Using abort will dump core, if the user has core dumps enabled. So as a rule of thumb, I'd use abort if you're so unsure about what's gone wrong that the only way to get useful information about it is by analysing a core dump. If you can safely exit from any given point, and don't need the core dump, then exit is a nic...
3,676,401
3,676,530
Typical problem on Inheritance
Possible Duplicate: Why is this not allowed in C++? Why is this not allowed in C++...?? class base { private: public: void func() { cout<<"base"; } }; class derived : private base { private: public: void func() { cout<<"derived"...
You can't let the base pointer point to the derived object when there is private inheritance. Public inheritance expresses an isa relationship. Private inheritance on the other hand expresses a implemented in terms of relationship Ther compile error refers to the line: ptr = new derived;
3,676,638
3,676,669
template method pattern and long parameter lists in c++
After the helpful answers to my last question I started using the template method pattern for a class with a lot of different options. Without having implemented them all, my current declarations for objects of that class now look like this: pc < prg, tc, 9, 0, 4, 4, test, true, true, true, true, false, true, true, 10,...
Yes, use enums (not defines) instead of true/false. That way, if you get the parameters out of order, then the compiler will complain. Also, it's much clearer to readers. As for dealing with with long parameter lists in general --- hide them behind a typedef, or a generator that fixes some of the template parameters, a...
3,676,664
3,676,680
Unit testing of private methods
I am in the process of writing some unit tests. In particular I want to test some private methods. So far the I have come up with using. #define private public But I am not happy with this as it will destroy all encapsulation from the point of view of the unit test. What methods do you use to unit-test private methods...
If the methods are complex enough to warrant testing in isolation, then refactor them into their own class(es) and test via their public interface(s). Then use them privately in the original class.
3,677,300
3,677,625
Is _write in io.h a blocking call?
I've inherited some code which, to initialise some hardware, writes a few bytes and then waits for a return. To do this it calls the _write function from io.h. From my testing, it looks like it's locking up at that point. So my questions are as follows: Is that function a blocking function? Is there a way of setting a...
If you want to do async I/O on Windows then either use the Win32 APIs directly (look at docs for WriteFileEx/ReadFileEx, which contain pointers to general background on async I/O vs sync) or consider boost::asio.
3,678,197
3,678,284
Virtual function implemented in base class not being found by compiler
I've got a situation where it seems like the compiler isn't finding the base class definition/implementation of a virtual function with the same name as another member function. struct One {}; struct Two {}; struct Base { virtual void func( One & ); virtual void func( Two & ) = 0; }; struct Derived : public ...
You are hiding the method in the derived class. The simplest solution is to add a using declaration to the derived class. struct Derived : public Base { using Base::func; virtual void func( Two & ); }; The issue is that when the compiler tries to lookup the func identifier in the call d.func(one) it has to do ...
3,678,217
3,678,261
C++ superclass Array yet access subclass methods?
i have an accounts class from that i have 3 types of accounts savings, credit, and homeloan. i created a binary search tree to hold all the accounts as type account how do i now access the methods of the subclasses depending on the type of object? have resolved all errors with syntax and codeing but this. been racking ...
The simple answer is, if you need to access the derived class functionality from a base class pointer, you have a design problem. In principle, you shouldn't need to know. If you do, something is wrong. You're supposed (in a pure sense) to call virtual functions from the base class interface, and have the derived clas...
3,678,235
3,678,323
deleting an array of pointer to struct
i have the following struct: struct Message { Agent *_agent; double _val; }; and the following Ptrs array: typedef Message* MessageP; MessageP *_msgArr; _msgArr = new MessageP[MAX_MESSAGES]; this is the method that inserts a Message to the array: void Timing::AddMessage(Agent * const agentPtr, double val) { ...
The delete [] will call the destructors on the struct pointers, which doesn't dispose of the structs or the _agent members, which itself points to memory. You could call delete _msgArr[i]._agent and then delete _msgArr[i] in a loop, which will dispose of the Agent and then the Message. First, though, you need to know...
3,678,270
3,678,404
Why are async callback socket methods usually static?
Why are async callback socket methods usually static? (assume I understand static class, method and data objects). Would there be a fundamental design/logic error if one were to write a class using these as instance methods? Is there anything special that one should be careful to avoid?
There is no specific reason that they should be static. It all depends on your design. If the callback needs to access members in the class then it can be declared as a instance member. However, you will need to make sure that you correctly syncronize the access to the instance members because the callback can be invok...
3,678,393
4,915,470
Why does Win32 API function CredEnumerate() return ERROR_NOT_FOUND if I'm impersonated?
I've written some sample code which when I call from the windows command prompt under the context of a normal user account, dump's all the user's saved credentials using CredEnumerate(). However, I really want to be able to do this from SYSTEM user context so I've tested my program from a SYSTEM cmd prompt. When I ru...
I guess I aught to answer this question myself since I've now spent ages working out how to do this and I'm not sure it's widely known. CredEnumerate/CredRead will never provide password information for domain passwords no matter what process context you're in or what token you have despite what it seems to hint at on...
3,678,396
4,827,982
Xerces-C: Migration from v2.x to v3.x?
I would like to migrate a project (legacy code which I am not quite familiar with) from Xerces-C v2.x to v3.x. It turns out that Xerces-C v3 dropped the DOMBuilder class. The migration archive tells me this: ...a number of DOM interfaces (DOMBuilder, DOMWriter, DOMInputSource, etc.) were replaced as part of the the fi...
Replacements for removed APIs: Use XercesDOMParser or DOMLSParser instead of DOMBuilder (more info): xercesDOMParser->setCreateCommentNodes(true); Use DOMLSSerializer instead of DOMWriter: DOMLSSerializer* writer = ((DOMImplementationLS*)impl)->createLSSerializer(); DOMConfiguration* dc = writer->getDomConfig();...
3,678,419
3,678,437
Need to Write C code from C++ Code?
I need to write my 4-5 .cpp and .h file to c code. In C++ code we have defined a class, constructor, destructor, function. How to convert them in C code? Can somebody give me example of it so that i can implement it or provide link so that I can better explore it to my C code? How to implement all the functionality i m...
convert all classes to data structures (typedefs) replace constructors and destructors with functions that use malloc/calloc and free and return/take pointers to your typedef'd structures eliminate polymorphism; if this is not possible then implement a message-dispatching function for each typedef (a big switch stat...
3,678,450
3,678,545
Convertion from extended ascii to utf8
How do you convert an std::string encoded in extended ascii to utf8 using microsoft visual studio 2005? I'm using google protocol buffer and it's complaining about non utf8 characters in my string if I give it without conversion, which is true...
Use MultiByteToWideChar to convert your string to UTF-16, then use WideCharToMultiByte to convert it to UTF-8.
3,678,484
3,982,023
Help on using boost relaxed heap
I'm implementing a few graph algorithms at the moment and am wanting a container with the complexity of a fibonacci heap or a relaxed heap (specifically I want at least O(logN) for push and pop and O(1) for reduce_key). I'm not keen on implementing this myself if at all possible (development and testing overhead and ti...
Alex, if you checkout/download/browse boost library, there's a libs/graph/test directory. One of the tests is relaxed_heap_test.cpp which seems to have coverage of the update member function. -s-
3,678,691
3,678,828
Color console boxes in linux terminal
So I have noticed that things (for lack of a better word) like this and are just done in the console using special characters and changing their color. I know how to accomplish this on windows but how would I go about doing this in linux (I am using ubuntu if that matters)? Are there any predefined classes out ...
If you just want to create simple standard widgets you may try dialog library, but if you need something more powerful then ncurses is your choice.
3,678,884
3,679,090
Virtual member functions and std::tr1::function: How does this work?
Here is a sample piece of code. Note that B is a subclass of A and both provide a unique print routine. Also notice in main that both bind calls are to &A::print, though in the latter case a reference to B is passed. #include <iostream> #include <tr1/functional> struct A { virtual void print() { std::c...
This works in the same manner as it would have worked with plain member function pointers. The following produces the same output: int main () { A a; B b; typedef void (A::*fp)(); fp p = &A::print; (a.*p)(); // prints A (b.*p)(); // prints B } It would have been surprising if boost/tr1/std::fun...
3,679,435
3,679,499
How do I disable tailcall optimizations in gcc
I wonder if anyone knows the flag for gcc to disable tailcall optimizations. Basically in a tailcall optimization, gcc will replace a stack frame when the return value from a called function is passed through (via return) or nothing else happens in the function. That is, in void main() { foo(); } void foo() {...
GCC manual: -foptimize-sibling-calls Optimize sibling and tail recursive calls. Enabled at levels -O2, -O3, -Os. So either compile with -O0/-O1, or use -fno-optimize-sibling-calls.
3,679,464
3,680,769
embedded webserver for status reporting in c++?
I'm writing a large system in C++ and want to include an embedded webserver for management and reporting. Can anyone make some recommendations?
Take a look at Mongoose. It is free, open-source, cross-platform embedded web server written in C. We are using this in a number of projects and are very happy.
3,679,522
3,679,566
Execution at main method
Hii , We generally see that the program execution begins in the main method for the languages like C , C++ , Java (i am familiar with these). I want to know how the compiler knows the presence of MAIN method in the program . What does the main method signify besides that it is the entry point for program execution ......
Generally, the code that is executed at the beginning of every C or C++ program (included usually by default by compilers/linkers) does some initialization and then calls a function called main. If this function is not present, it will lead to an unresolved name when linking a program (in which all the names have to be...
3,679,549
3,679,731
How to use boost::unit_test?
I'm trying to learn how to test programs so I tried Boost. I've started reading it and here I've met this line: Now I can compile it and link with the unit test framework. From where and how am I suppose to get unit test framework? And what it is? I just do not know what to eat it with. Could someone please provide ...
Just a fast comment. The problem with this library is that it has at least three different ways of implementing and running the tests. Depending on what #defines you add to your code before including the boost unit test header, it can automatically generate a main function for you (and then build a complete program tha...
3,679,801
3,679,915
Overloading functions not compiling
I am following the book C++ Cookbook from O'Reilly and I try one of the examples, here is the code: #include <string> #include <iostream> #include <cctype> #include <cwctype> using namespace std; template<typename T, typename F> void rtrimws(basic_string<T>& s, F f){ if(s.empty()) return; typename ba...
isspace is also a template in C++ which accepts a templated character and also a locale with which it uses the facet std::ctype<T> to classify the given character (so it can't make up its mind what version to take, and as such ignores the template). Try specifying that you mean the C compatibility version: static_cast...
3,679,967
3,680,024
Calling a Visual Basic DLL in C++
I have acquired a DLL that was created in Visual Basic from a third party vendor(Sensor DLL.dll). This DLL contains functions for talking to a sensor, and I need to call these functions from a Visual C++ program I am writing. The vendor will not provide a header file, and I do not know Visual Basic. If I had a heade...
A VB6 DLL is normally a COM server. You do in fact have the equivalent of a .h file, it has a type library embedded in it. Start this off with Project + Properties, Common Properties, Framework and References. Add New Reference button, Browse tab, select the DLL. Next, View + Object Browser. You should see the gene...
3,680,197
3,680,227
cin and buffer problem
Hi I have question regarding cin and buffer. I want to make a simple io program which takes integers. Anyway I stumbled to a problem with buffer. Using MinGW in windows7 the following code will print out all four integers that I input. But when I switch to SunOS and compile it with G++ it will only print out the first ...
The code should print out the first number on pretty any system. cout << " "; versus cout << " " << i; Therefore many guidelines state to do only one operation per line. The cin just optically clutters the reading. Actually you never output i excepted the first time.
3,680,226
3,680,237
How to read and extract information from a file that is being continuously updated?
This is how I am planning to build my utilities for a project : logdump dumps log results to file log. The results are appended to the existing results if the file is already there (like if a new file is created every month, the results are appended to the same file for that month). extract reads the log result file t...
tail -f will read from a file and monitor it for updates when it reaches EOF instead of quitting outright. It's an easy way to read a log file "live". Could be as simple as: tail -f log.file | extract Or maybe tail -n 0 -f so it only prints new lines, not existing lines. Or tail -n +0 -f to display the entire file, an...
3,680,312
3,680,326
Linker Error LNK2019
I have been playing around with Template functions, and made a little logger program. I have been trying to split this into header / source file, but I keep getting linker errors. I know this is simple, but I cant figure it out. Also I have some convince vars in the logger header, where would be the "proper" place for ...
You'll want to read the C++ FAQ Lite question, "Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?" Effectively, you need to define your function and class templates in the header file, not in the .cpp file.
3,680,508
3,680,560
Good start for .Net and c++ to Java transition?
I know the .Net framework very well and know where to find things ie: StreamReader, StreamWriter, Graphics, etc, and I know Java has similar things. The syntax is different but quite similar to c++ which I have a lot of native c++ experience. Therefore, what would you recomend as a good starting point for tutorials and...
In my new job, I quickly found myself working on a common library in C++, C# and Java. I had no Java knowledge and yet found it pretty intuitive to make simple mods to the Java code - the general C# principle that there is a framework class/namespace for most things you want to do, appear to hold in Java. The thing t...
3,680,601
3,680,642
Boost: Function Output Iterator, reinventing the wheel
Normally someone would just go and grab Boost's Function Output Iterator but I'm not allowed to use Boost at work. That said, I just want to use the copy function to traverse a collection, call a function on each item, take the output of that function, and finally push_back it onto another collection. I've written so...
You can use transform instead: transform(src.begin(), src.end(), back_inserter(container), func); Note that const applied on a reference type is a no-op. So if argument_type is T&, then saying const argument_type does not yield back const T& but T& again. So if your source items are constant you would try to bind the...
3,680,647
3,681,009
C++ standard library vs mortal made code + where can I find the sources?
Two, maybe trivial questions: 1. Why can not I beat the STD functions? Really. I spent the last three days implementing something faster than std::sort, just for the sake of doing it. It is supposed to be an introsort, and I suspect it uses the single pivot version quicksort inside. Epic fail. Mine was at least twice ...
The short answer is "if it was possible to write faster code which did the same thing, then the standard library would have done it already". The standard library is designed by clever people, and the reason it was made part of C++ is that other clever people recognized it as being clever. And since then, 15 years have...
3,680,667
3,680,753
lual_newstate outside of main function
I'm embedding Lua in a C++ application using Lua5.1 and I'm having an odd issue with luaL_newstate(). This works: lua_State *L = NULL; int main() { L = luaL_newstate(); return 0; } I recently restructured my code and chose to create an init function like this: lua_State *L = NULL; void init_lua(lua_State *L) { ...
In the second example, this function: void init_lua(lua_State *L) { L = luaL_newstate(); } You are setting L to the return of luaL_newstate(). L is a pointer to a lua_state. However, you are only changing the parameter version of L. In you third example: void init_lua(lua_State **L) { *L = luaL_nwstate(); } You a...
3,680,730
3,680,817
C++ FileIO Copy -VS- System("cp file1.x file2.x)
Would it be quicker/efficient to write a file copy routine or should I just execute a System call to cp? (The file system could differ [nfs, local, reiser, etc], however it would always be on a CentOS linux system)
Invoking a shell by using system () function is not efficient and not very secure. The most efficient way to copy a file in Linux is to use sendfile () system call. On Windows, CopyFile () API function or one of its related variants should be used. Example using sendfile: #include <fcntl.h> #include <stdlib.h> #include...
3,680,950
3,686,442
Implementing for(auto item : container) in VC2010
I wanted to create a little macro to simulate for(auto item : container) in VC2010 which I can then replace with the real construct when it's released. There is BOOST_FOREACH, however I would like auto support. I've tried creating a macro. However it fails when the dereferenced iterator is a constant type. #define _LIB...
There is BOOST_FOREACH, however I would like auto support. BOOST_FOREACH appears to support the C++0x auto keyword alright. As your macro is, boost's one is superior. It also works for arrays (and probably zero-terminated char arrays) and lets you use references for the loop variable, rather than making it appear f...
3,681,026
3,681,099
How to Link to a .lib file in Visual C++ 2010? Without referencing the project?
I just have a problem that I have been trying to fix for the longest time. I have a static library project in visual c++, and I want another project to be able to link to it. Up until now, I have simply been adding a reference to the static library project, which automatically links the library. I want to be able to li...
Make sure that you are exporting the functions, classes, and variables in your library that you want exposed to other applications (i.e. your dll or exe). By default they are not exposed. The ground work to do this is typically layed out when you create the project for your library. #ifdef TESTLIB_EXPORTS #define TES...
3,681,084
3,681,095
Is it necessary to call delete[] vs delete for char arrays?
I'm utilizing a library written by a collegue and discovered that valgrind was spewing out errors related to the delete. The problem was that there were allocations of char arrays like char* s = new char[n]; followed up later with delete s instead of delete[] s He tells me that the difference is really that delete[] s...
If you allocate an array using new[], you have to destroy it using delete[]. In general, the functions operator delete(void*) and operator delete[](void*) aren't guaranteed to be the same. Refer here
3,681,140
3,681,144
How do I avoid both global variables and magic numbers?
I know and understand that global variables and magic numbers are things to avoid when programming, particularly as the amount of code in your project grows. I however can't think of a good way to go about avoiding both. Say I have a pre-determined variable representing the screen width, and the value is needed in mult...
In your second example, SCREEN_WIDTH isn't really a variable1, it's a named constant. There is nothing wrong with using a named constant at all. In C, you might want to use an enum if it's an integer constant because a const object isn't a constant. In C++, the use of a const object like you have in the original ques...
3,681,188
3,681,190
Why does a function declaration with a const argument allow calling of a function with a non-const argument?
Take note of the following C++ code: #include <iostream> using std::cout; int foo (const int); int main () { cout << foo(3); } int foo (int a) { a++; return a; } Notice that the prototype of foo() takes a const int and that the definition takes an int. This compile without any errors... Why are there no co...
Because it doesn't matter to the caller of the foo function whether foo modifies its copy of the variable or not. Specifically in the C++03 standard, the following 2 snippets explain exactly why: C++03 Section: 13.2-1 Two function declarations of the same name refer to the same function if they are in the same scope ...
3,681,265
3,681,282
Default copy assignment with array members
I've got a class definition similar to the following: class UUID { public: // Using implicit copy assignment operator private: unsigned char buffer[16]; }; I've just had a unit test fail on me that was verifying that copy assignment worked properly. To my surprise, one byte in the middle of the buffer[] ...
My understanding is that the default copy assignment operator performs memberwise copy, and that for array members (not pointer-to-array members) that entailed elementwise copy of the array. Yes. This is correct. Your problem is not with the copy assignment operator (unless you have found some unusual compiler bug, ...
3,681,455
3,681,471
What is the philosophy of managing memory in C++?
What is the design factor in managing memory in C++? For example: why is there a memory leak when a program does not release a memory object before it exits? Isn't a good programming language design supposed to maintain a "foo-table" that takes care of this situation ? I know I am being a bit naive, but what is the de...
What is the core driving design of memory management ? In almost all cases, you should use automatic resource management. Basically: Wherever it is practical to do so, prefer creating objects with automatic storage duration (that is, on the stack, or function-local) Whenever you must use dynamic allocation, use Sco...
3,681,574
3,681,682
How to implement this pluggable mechanism in C# and java?
Let's say I have three object A, B, C. B is the implementation of following interface: interface D { event EventHandler<OrderEventArgs> OrderCreated; event EventHandler<OrderEventArgs> OrderShipped; } I would add two functions in B which will raise the events in the interface. class B { RaiseOrderCreated()...
So you'd have an EventListener called C, some object called A which has a field of type B that is some kid of implementation of D. Typically in Java you design D differently: interface D { static final String ORDER_PROPERTY="ORDER"; void setOrder(Order order); Order getOrder(); } class B implements D { // ...
3,681,624
3,681,634
using unix system calls in cpp
I am new to cpp, I have a small problem, I have a cpp file and it contains open(), read() & close() & some other methods as public members. Now I wanted to use the 'read' unix system call in one of the methods But if I do so (in some method) its pointing to class member variable 'read()' and gives compilation error. So...
If you are in a class that has a method read(), and you want to access a function read() in the global namespace, use ::read().
3,681,999
3,682,009
designing a game c++
ok im gonna be using directx maybe 9. I have designed two other games they were too simple im asking how game is designed like they make one file that includes menu codes and the all level codes......... thanks
You can try checking out the Official Microsoft site: http://msdn.microsoft.com/en-us/aa937791.aspx Or, you can check out this site, designed for beginners: http://www.gamedev.net/reference/start_here/
3,682,152
3,682,193
Problem with istream::tellg()?
I'm reading data.txt: ////////////////////////////////////////////////// data.txt: ////////////////////////////////////////////////// MissionImpossible3 3 TomCruise MaggieQ JeffChase Here's code: #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream fin("data.txt"); ...
It says it consumed 24 characters after the first line, then failed to get a number. However, MissionImpossible3 only has 18 characters. I suspect you have a line encoding incompatiblity. Your file is saved with \n endings, while Windows iostreams expects \r\n. The 3 in the input gets thrown away as the system expects ...
3,682,260
3,682,354
C++ Linked List Runtime Error: Unhandled Exception - Writing Location Violation
I am trying to build my own implementation of a linked list in C++. My code is compiling but apparently there is some issue with my pointers referring to invalid memory addresses. Here is my implementation: #include <iostream> #include <string> using namespace std; class Node { private: string _car; ...
You need to relook at your code. headNode = node1; This assignment should be done before accesing any member function of the instance headNode. Intially you have assigned NULL to this pointer. After creating node1 you are setting to headNode that is invalid instance. This is the cause of crash. Be ensure with your obj...
3,682,294
3,682,660
Implementing Exception class in C++
So, I am try to write a simple base Exception class for C++, based on the Java Exception class. I'm sure there are great libraries out there already, but I am doing this for practice, not production code, and I'm curious and always looking to learn. One of the things the Java's Exception does, which I would like to als...
The exception - when allocated on the stack (I would strongly recomend this) - is freed after the catch clause. So you need to create a copy of the "inner" exception in the newly created exception. If you catch a base class of your exception it will loose it's correct type unless you give your exception a clone method....
3,682,501
3,684,137
How to specify user defined type parameters in COM interface definition?
One of my COM interface methods needs a parameter of user defined type as below: [uuid(58ADDA77-274B-4B2D-B8A6-CAB5A3907AE7), object] //Interface interface IRadio : IUnknown { ... HRESULT test_method2(someUDT* p2p_UDT); ... }; How could fit the definition of the someUDT in the *.idl file? The s...
Perhaps this helps you - it's german but the most interesting part is the code. This is how a Struct is defined there: [ uuid(62D33614-1860-11d3-9954-10C0D6000000), version(1.0) ] typedef struct TPerson { BSTR bstrFirstname; BSTR bstrLastname; long lAge; TDepartment Dep; } TPerson; /...
3,682,773
3,682,853
Pass an absolute path as preprocessor directive on compiler command line
I'd like to pass a MSVC++ 2008 macro into my program via a /D define like so /D__HOME__="\"$(InputDir)\"" then in my program I could do this cout << "__HOME__ => " << __HOME__ << endl; which should print something like __HOME__ => c:\mySource\Directory but it doesn't like the back slashes so I actually get: __HOME_...
You can convert your macro to a string by prefixing it with the stringizing operator #. However, this only works in macros. You actually need a double-macro to make it work properly, otherwise it just prints __HOME__. #define STRINGIZE2(x) #x #define STRINGIZE(x) STRINGIZE2(x) cout<< "__HOME__ => " << STRINGIZE(__HOME_...
3,682,982
3,683,019
Microsoft ATL equivalent to Borland OleCheck function
Borland C++ Builder provides the function OleCheck(HRESULT Result);. Its description in the documentation is this: OleCheck is used to wrap many COM routines, so that if that routine fails, users will have an opportunity to handle it in the resulting exception that is raised. If ECode is a value less than zero, OleC...
There's no such ready thing in ATL. The closest thing is AtlThrow() which throws an exception (unconditionally), but the check is still up to you - you can look into how AtlThrow() is used in ATL itself. So IMO your best bet is to craft your own function - it will accept HRESULT and call AtlThrow() or some other except...
3,682,994
3,683,022
C++ [] mapping, possibly through templates
I have a little problem in C++ I don't know how to solve. The first part of the problem is to access an element in a struct via [], or better, to map [] to a subelement. My struct looks like this: struct e { std::string content; std::string name; std::map<std::string, std::vector<e> > elements; }; If I wan...
You need to overload operator[]. Typically, you want to implement two versions of that operator, but since std::map only overloads the non-const version, that might be enough for you. Something like the following should do: struct e { std::string content; std::string name; std::map<std::string, std::vecto...