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
4,156,559
4,178,477
boost custom formatter using boost bind to method taking only one paramerter
I'm trying to use boost::regex_replace with a custom formatter. I need to pass a method from an object because some member is needed in the replacing function. The signature of my replacing method is: std::string MyObject::ReplaceStr( boost::match_results<std::string::const_iterator> match) const When calling rege...
You could use boost::function to avoid ambiguity: boost::function<std::string (boost::match_results<std::string::const_iterator>)> function = boost::bind(&MyObject::ReplaceStr, this, _1); std::string replaced = regex_replace(testString, replace_pattern, function);
4,156,584
4,156,628
C++ Pointer to Template Class With (virtual) Inheritance
Currently I'm working on a GUI system, and I've made a GUIButton object which has this inheritance structure: GUIObject | GUIImage | GUIButton Where GUIObject is a base class with some virtual functions (render, update, etc). Anyway, because of the way I want to handle callbacks for the GUI system, GUIButton i...
Define constructor template<class CallbackClass> class GUIButton : public GUIImage { public: // Constructor // GUIButton() : m_callTo(), m_callback() {} // <---- here
4,156,770
4,156,981
Pass contents of stringstream to function taking char* as argument
I have a function for writing ppm files (a picture format) to disk. It takes the filename as a char* array. In my main function, I put together a filename using a stringstream and the << operator. Then, I want to pass the results of this to my ppm function. I've seen this discussed elsewhere, often with very convoluted...
This looks like a typical case of someone not writing const-correct code and it having the knock-on effect. You have several choices: If write_ppm is under your control, or the control of anyone you know, get them to make it const corrct If it is not, and you can guarantee it never changes the filename then const_cast...
4,157,134
4,157,725
istream_iterator: taking extra input
I can't get this blasted thing working right. The problem is, If I want to enter 2 numbers, I actually have to enter 3. What is wrong? namespace MT { template<class IIT, class OIT> OIT copy_n(IIT iitBegin, size_t szCount, OIT oitBegin) { for(size_t szI = 0; (szI < szCount); ++szI) { ...
Change your stream iterator loop to: for(size_t szI = 0; (szI < szCount); ++szI) { *oitBegin = *iitBegin; if (szI < szCount - 1) { ++oitBegin; ++iitBegin; } }
4,157,323
4,157,350
Using CString to Convert int and Send to Console
My console application attempts to write an integer to the console: int i = 170; CString cs; cs.Format( L"%d", i ); wcout << cs << endl; I expect "170" to be written to the console, but what happens is "00E21280". This is the address. I have verified that "170" is saved at that memory location. Any ideas?
You have to cast it to a string, otherwise it treats it as a pointer. wcout << (PCTSTR)cs << endl;
4,157,491
4,157,976
Is there an 'upgrade_to_unique_lock' for boost::interprocess?
I am looking for the best way to effectively share chunks of data between two (or more) processes in a writer-biased reader/writer model. My current tests are with boost::interprocess. I have created some managed_shared_memory and am attempting to lock access to the data chunk by using an interprocess mutex stored in t...
All Boost.Interprocess upgradable locks support upgrade per this. Definition here. Regarding your broader question - I would think that this is precisely what you want. Readers can still work concurrently, and you have to prevent concurrent writes. Unless you can partition the shared memory such that more constrai...
4,157,644
4,157,663
How do I convert a string to a char* in c++?
I have an error in my program: "could not convert from string to char*". How do I perform this conversion?
If you can settle for a const char*, you just need to call the c_str() method on it: const char *mycharp = mystring.c_str(); If you really need a modifiable char*, you will need to make a copy of the string's buffer. A vector is an ideal way of handling this for you: std::vector<char> v(mystring.length() + 1); std::s...
4,157,687
4,157,729
Using char* as a key in std::map
I am trying to figure out why the following code is not working, and I am assuming it is an issue with using char* as the key type, however I am not sure how I can resolve it or why it is occuring. All of the other functions I use (in the HL2 SDK) use char* so using std::string is going to cause a lot of unnecessary co...
You need to give a comparison functor to the map otherwise it's comparing the pointer, not the null-terminated string it points to. In general, this is the case anytime you want your map key to be a pointer. For example: struct cmp_str { bool operator()(char const *a, char const *b) const { return std::str...
4,157,834
4,157,887
Regular Expressions to find C++ elements?
I'm looking for some predefined Regexes for elements of ANSI C++. I would like to create a program which takes a headerfile (with includes, namespaces, classes etc) as input and returns lists with the found classnames, methods, attributes etc. Its hard to google for something like that, I always end up with tutorials o...
You might find the code for ctags handy. It will parse code and break out the symbols for use in emacs and other programs. In fact, it might just do all the work you are trying to do yourself.
4,158,153
4,158,175
Should a class perform bounds checking when you are after performance
Say I have a triangle class, defined something like class Triangle{ vertex3D vertexs[3]; public: vertex* GetVertex(int vertexNumber); } now for most normal applications its fairly obvious that GetVertex should ensure that vertexNumber is a valid index before trying to return the vertex pointer. I would say that normal...
You should definitely check the bounds in a debug build. If you're sure that your code is correct (so, you've had a code review and you've tested it extensively) then it is fine to leave out bounds checks in a release build for the sake of performance. If you are going to test the bounds in a debug build but not in a...
4,158,206
4,158,249
Qt and chm help file format
We want to move to Qt for our widget library. Currently we're using WX and it's compatible with chm. I can't find anything to suggest that Qt is the same. We've invested a bunch in CHM tools for the non-technical people to write help files. Is there a way to view chm with Qt? If not, is there a reasonably easy p...
Plain HTML definitely is. Qt contains a full HTML rendering core (WebKit). Plus Qt has some internal format (packed HTML, similar to chm) https://doc.qt.io/archives/qq/qq28-qthelp.html Oh and: http://web.archive.org/web/20120712115053/http://lists.trolltech.com/qt-interest/2005-03/thread00621-0.html explains how to ope...
4,158,526
5,565,019
Calling C++ library from PHP web app: system() vs SWIG PHP extension?
I have a PHP web application that needs to call a function in a C++ library. This library is provided by a vendor (libfoo.a on a linux machine). My first instinct is to create a C++ executable that links against libfoo.a, and passes command-line parameters to the function. The PHP web application can then do a sys...
Not sure what you did finally but I've done a simple php wrapper extension years ago calling a C++ lib. Like this you will not have overhead of a system call. I'ts not an issue for you, but you'll have finer control over calls to the lib. For example keeping the wrapper loaded in memory as opposed to loading it on each...
4,158,567
4,158,596
Error with strcpy and its second argument
When I try and compile this program, I get errors (included below the code) about strcpy's second argument. I'm honestly stumped on what to do to fix it. And I'm sorry if my code is not efficient or pretty to look at; I'm just a beginning CS student. #include "stdafx.h" #include <iostream> #include <ctime> using names...
DANGER. strcat() AND strcpy() ARE THE LEADING CAUSES OF CODE CANCER. Using them exposes you to all kinds of buffer overflows. Use strncat()/strncpy(), or (even better) just use std::string, since you're using C++! strcat() and strcpy() expect their arguments to be strings. *article[r] is a single char--article[r] is th...
4,158,696
4,158,781
How to eliminate a copy of variable in base class with multiple inheritance?
As title describes, I have 3 classes: #include <iostream> using namespace std; class first { protected : int data; public : first() :data( 1 ) { // empty } }; class second : public first { protected : double x; public : second() :first() { // empty } }; class combine : public first, public sec...
This is what virtual inheritance is for. To keep first from being duplicated, everywhere you (directly) derive a class from first, you need to make the inheritance virtual, so you'd have: class second : public virtual first { // ... class combine : public virtual first, public second { // ...
4,158,727
4,158,791
How to use enable_if to enable member functions based on template parameter of class
In code: template<class T> struct is_builtin { enum {value = 0}; }; template<> struct is_builtin<char> { enum {value = 1}; }; template<> struct is_builtin<int> { enum {value = 1}; }; template<> struct is_builtin<double> { enum {value = 1}; }; template<class T> struct My { typename enable_if<is...
You can't use class template parameters to get SFINAE for member functions. You either need to make the member function a member function template instead and use enable_if on the member function template's template parameters or move the member function f into a policy class and specialize the class template using...
4,158,739
4,176,711
Can cpp_netlib perform asynchronous concurrent requests?
cpp_netlib docs contains example HTTP client, but I see it works only in blocking mode: http_client::response response = client.get(request); -- this (as I guess) will stop program execution while waiting for server's response. Can I perform multiple concurrent requests with cpp_netlib without spawning multiple thread...
It is possible to handle asynchronous connections in non-blocking manner using a typedef with an asynchronous tag: typedef boost::network::http::basic_client< boost::network::http::tags::http_async_8bit_udp_resolve , 1, 0> http_client; But currently there's no ability to implement full-featured concurrent connecti...
4,158,776
4,158,843
Calculating an equation solution in C++
I have a function in C++ with the following signature: float Foo(float time, float min, float curr, float beta) Within the function, I want to determine and return MAX in the following equation: time = beta + (1.0f - beta) * ((MAX - curr) / (MAX - min)) To test the results, you could use the following arguments: Foo(...
time = beta + (1.0f - beta) * ((MAX - curr) / (MAX - min)) let's denote time with t, beta with b, curr with c, min with m, and MAX with x; we have t = b + (1-b)(x-c)/(x-m) (x-c)/(x-m) = (t-b)/(1-b) (x-m)(t-b) = (x-c)(1-b) x(t-b) - x(1-b) = m(t-b) - c(1-b) x(t-1) = m(t-b) - c(1-b) x = (m(t-b) - c(1-b))/(t-1) so your f...
4,158,814
4,158,844
Specializing Template Constructor Of Template Class
My brain has melted due to several weeks of 14-hour days. I have a template class, and I'm trying to write a template convert constructor for this class, and specialize that constructor. The compiler (MSVC9) is quite displeased with me. This is a minimal example of actual code I'm trying to write. The compiler err...
template<> template<typename B> Gizmo<string>::Gizmo(const B& b) Also note that the typename keyword from const typename B& must be removed.
4,158,829
4,159,159
I need timer to show image buffer every 25fps (C++ win32)
I used SetTimer with 40ms and WM_TIMER message to draw an image every 40ms (25 frames per second) but the result is too slow. I found out that WM_TIMER isn't accurate, I tried to use multimedia timer but the callback proceudure didn't work . My question is: How can I draw my images with 25fps? Thanks!
You are indeed correct. WM_TIMER is grossly innacurate. If you try to do something similar with GetTickCount(), WaitForSingleObject(..., timeout) or Sleep(timeout) they won't work either, because they use a similar timing mechanism as WM_TIMER. The simplest mechanism I can think of to accomplish your goal is to use ...
4,158,900
4,158,997
Embedding resources in executable using GCC
I'm looking for a way to easily embed any external binary data in a C/C++ application compiled by GCC. A good example of what I'd like to do is handling shader code - I can just keep it in source files like const char* shader = "source here"; but that's extremely impractical. I'd like the compiler to do it for me: upon...
There are a couple possibilities: use ld's capability to turn any file into an object (Embedding binary blobs using gcc mingw): ld -r -b binary -o binary.o foo.bar # then link in binary.o use a bin2c/bin2h utility to turn any file into an array of bytes (Embed image in code, without using resource section or externa...
4,159,158
4,160,228
Winsock recv() does not block
I have just compiled this code: http://www.win32developer.com/tutorial/winsock/winsock_tutorial_2.shtm I have added some codes so it does recv(), in an infinite loop. My problem, if there is no data to read, it still does not block. Am I totally mistaken if I think recv should block in my case? The code I have added is...
if((nError == SOCKET_ERROR) || (nError == 0)) WSAGetLastError(); else ; // handle success That's how it should look, and not how you did it.
4,159,309
4,159,345
Is there something like Mandatory template argument that is deduced from other template argument?
Suppose I have a template which takes 3 template parameter. I want the third template parameter to be taken by some another template say "CHECK" that may return any integer in case as CHECK fails else "1". In case of "1" class X is specialized. As shown in following code. How can I achieved it, i.e. how can I force ...
IIUC, you want prevent users from supplying that third parameter. Rename your class X to X_impl and supply a new X, with less parameters: template<typename T, typename D, int Int > class X_impl; template<typename T, typename D > class X : public X_impl< T, D, CHECK<T, D>::IS_TRUE > {};
4,159,350
4,159,394
Is protected inheritance transitive?
Lets say I have a listener interface defined as: class Listener { public: virtual void doSomething(void) = 0; } and an abstract class that inherits publicly from my interface: class AbstractBase: public Listener { public: virtual void doSomething(void){ ...do something } } My derived class inherits ...
Access control is based on the static type, not the dynamic type. Therefore, since your Caller uses a pointer to Listener, it can use the interface defined by the Listener class. If it receives a pointer to a Derived, it's still basically treating it as a Listener, so from its viewpoint, doSomething() is public, regard...
4,159,374
4,159,393
Comparing class objects using template max function
I have written a template function like this: template <class T> const T& max1(const T& x, const T& y) { if(y < x) return x; return y; } Now, how can I use this function to compare two objects of class A where class A is like the following? class A { public: A(int x){i=x;} private: friend bool opera...
Defining an overloaded < operator is simple in this case: bool operator<(A const& lhs, A const& rhs) { return lhs.i < rhs.i; } In general, defining overloaded operators is as simple as that (though if you want to access non-public members, you will need to friend the function within the class's definition). Some o...
4,159,383
4,159,415
Strings in C Header Files
My header file is as follows: #include <iostream> #include <string> #include <windows.h> #include <math.h> //using namespace std; std::string StringMultiply(string Str, int Mult) { std::string Return; for (int Index = 0; Index <= Mult; Index++) { Return += Str; } return Return; } Compil...
change std::string StringMultiply(string Str, int Mult) to std::string StringMultiply(std::string Str, int Mult)
4,159,401
4,159,486
Specializing a template class member function for only one type
I have a template class that has lots of functions but is essentially a vector class. I want to add one function to just the bool type. #include <vector> template <typename T> class reflected{ private: T*dev_; T*host_; ar_size size; reflected<T>& operator=(reflected<T>& rhs);//do no...
You can define it in the class template like this template <typename T> struct id { typedef T type; }; template <typename T> class reflected{ private: /* ... */ vector<ar_index> which(id<bool>) { /* ... */ } public: /* ... */ vector<ar_index> which() { return ...
4,159,487
4,159,592
std::bind overload resolution
The following code works fine #include <functional> using namespace std; using namespace std::placeholders; class A { int operator()( int i, int j ) { return i - j; } }; A a; auto aBind = bind( &A::operator(), ref(a), _2, _1 ); This does not #include <functional> using namespace std; using namespace std::placeho...
You need a cast to disambiguate the overloaded function: (int(A::*)(int,int))&A::operator()
4,159,641
4,159,686
Does STL Vector use 'new' and 'delete' for memory allocation by default?
I am working on a plugin for an application, where the memory should be allocated by the Application and keep track of it. Hence, memory handles should be obtained from the host application in the form of buffers and later on give them back to the application. Now, I am planning on using STL Vectors and I am wondering ...
vector uses std::allocator by default, and std::allocator is required to use global operator new (that is, ::operator new(size_t)) to obtain the memory (20.4.1.1). However, it isn't required to call it exactly once per call to allocator::allocate. So yes, if you replace global operator new then vector will use it, alth...
4,159,853
4,159,941
Including parameters when defining a class's member functions is returning an error
I have the following class definition, written in C++, residing in it's own header file (ManageFeed.h) #include <string> #include <fstream> #include <iostream> #include <cstring> class ManageFeed { bool get_feed(); void format_feed(); bool refresh_feed(); int find_start_of_string(string tag, ifstream& ...
John has the right solution. Here is the reasoning. Both string and ifstream live in a namespace called std. When you say string you are telling the compiler to look into the global namespace and find a token called string. There is no such thing. You have to tell the compiler where to find string. To do so you can...
4,159,944
4,297,131
get the function called from a C++ code
for example i have this: static int callFunction(lua_State* L) { int p = lua_gettop(L); if (p == 1 && lua_isfunction(L, -1)) { /* * now i need something like "get the function thats in the first parametre */ } return 0; } now i need to get the function thats in the first parametre of the function in this C...
If you want to store a "pointer" to a Lua function in C++, you could just store the /name/ of the Lua function and then do as DeadMG says and call it with lua_call, as here: http://pgl.yoyo.org/luai/i/lua_call . If you are stuck with the code you have already, it's kind of a sticky problem; I'm not sure you can get the...
4,159,994
4,160,583
c++ performance of returning primitive by value or by (const) reference
Assume the following toy class, and modern compilers (recent gcc for example). template <typename T> class SomeVec { public: ... virtual T get(const int index) = 0; } The application involves a fair amount of number crunching based on values stored in SomeVec subclasses, T being a primitive type, say int. However,...
The reason STL returns references is because templated code doesn't have the luxury of knowing that returned objects are small. While an int is no problem, returning a large struct slows things down for no good reason. In the latter case it only makes sense to use references, and since a reasonable compiler can optimis...
4,160,113
4,160,146
C++ and SDL: Why can't I compile this program?
For some reason I can't compile this program because I'm supposedly missing SDL. It compiles fine on Debug mode, but not Release. I am using Visual C++ 2010. I linked to SDL with VC++ directories. Here is my (little) code. //main.cpp #include "main.h" void logger::log(string logging) { file << logging << "\n"; } ...
Be sure you added your library references to release mode as well as debug mode. I'm not 100% sure about SDL but some 3rd party libraries come with 2 flavors, debug & release. I believe you'll have to setup the release mode of the IDE with the release mode of the library files.
4,160,195
4,160,251
Learning from open-source projects / Browsing already written code
I was wondering how valuable open-source projects are to learn from? I still consider myself "beginner" due moreso to lack of experience than lack of knowledge- I've read many C/C++ tutorials and taken classes and such, but I just really lack experience. Therefore, even though I understand the major data types and codi...
I personally wouldn't recommend the reading of the source code of open-source projects to a beginner, especially if they're mature projects. It may be overwhelming for a beginner since they tend to be rather large projects with thousands of lines of code, most likely of a non-trivial design. If you lack experience, the...
4,160,214
4,160,303
tinyxml and c++ to save data
I am using tinyxml to save data input by the user in a c++ console program. I pass a save function an array of structs that look like the following struct day { string name; string note; }; I have seven of these, and pass all seven to the save function that looks like the following void saveData(day dayAr...
I haven't used TinyXml before but looking at the structure of the code, you need to create the day element inside your for loop and add it to the week element 7 times - once for each day. Your current code only adds the day element to the week element once at the end - this is reflected in your xml output. Taking part ...
4,160,233
4,160,307
How to use valgrind effectively
I've just started learning to use valgrind and the --tool=memcheck But what I am having trouble with is actually finding the problems. e.g. One such problem is this. ==12561== Conditional jump or move depends on uninitialised value(s) ==12561== at 0x425779: Server::HandleReceiveFrom(boost::system::error_code cons...
Basically, each Valgrind error displays a stack trace. The higher portions of the stack trace might not be very useful to you, since they refer to library code. However, ultimately these problems stem from issues in your code. Start by scanning for the first part of the stack trace which refers to a line of code in ...
4,160,321
4,160,404
Qt issue passing arguments to slot
I can't seem to pass an argument to a slot. If I don't pass an argument, the function rolls through fine. If I pass an argument (integer), I get the errors "No such name type" and "No such slot" when I compile. In my header, I declare: private slots: void addButton(int); signals: void clicked(int) in my Main.cpp, I...
Sebastian is correct that you cannot do this in the way you're trying, however Qt does provide a class that gives you the functionality you want. Check out the QSignalMapper. It allows you to associate an integer with an object/signal pair. You then connect to its signals instead of directly to the button.
4,160,375
4,160,477
Profile optimised C++/C code
I have some heavily templated c++ code that I am working with. I can compile and profile with AMD tools and sleepy in debug mode. However without optimisation most of time spent concentrated in the templated code and STL. With optimised compilation, all the profile tools that I know produce garbage information. Does an...
You should focus on the code you wrote because that is what you can change, time spent in STL is irrelevant, just ignore it and focus on the callers of that code. If too much time is spent in STL you probably can call some other STL primitive instead of the current one. Profiling unoptimized code is less interesting, b...
4,160,499
4,160,555
Create 2D vector from input in C++
quick question here. I'm wondering how to create a 2D vector from user input. For a project, I am storing my "board" as a 2D vector, and the user will enter the height and width of it, as well as perhaps the starting configuration. If my board is stored as: vector<vector<int> > myBoard( width, vector<int> (height) );...
I would try to infer the dimensions from the user input. An example session: A board consists of characters ., X or O. An example board: .XO ... X.. Enter the board, end with two Returns: ..... ..XO. .XXX. OOOOO ..... Then you would scan the first row to find the width, check each row for valid characters and the sam...
4,160,651
4,160,784
Iterating over int and string with istream_iterator
I am going through The C++ Programming Language Book and reached "Iterators and I/O" page 61 they give the following example to demonstrate iterating through a string submitted. #include <iostream> #include <iterator> #include <string> using namespace std; int main() { istream_iterator<string>ii(cin); istrea...
When you first create an istream_iterator, it gets the first input and stores the data internally. In order to get more data, you call operator++. So here's what's happening in your code: int main() { istream_iterator<string>ii(cin); // gets the first string "Hello" istream_iterator<int>jj(cin); // tries to...
4,160,945
4,166,592
long long int vs. long int vs. int64_t in C++
I experienced some odd behavior while using C++ type traits and have narrowed my problem down to this quirky little problem for which I will give a ton of explanation since I do not want to leave anything open for misinterpretation. Say you have a program like so: #include <iostream> #include <cstdint> template <typen...
You don't need to go to 64-bit to see something like this. Consider int32_t on common 32-bit platforms. It might be typedef'ed as int or as a long, but obviously only one of the two at a time. int and long are of course distinct types. It's not hard to see that there is no workaround which makes int == int32_t == long ...
4,161,028
4,178,386
Am I the only one who finds std::move a little too difficult to understand?
So I have been reading about std::move, std::forward, rvalues, lvalues ad so on in SO and other places. But I find that I can't grasp it. Even though I sometimes get into fixes, I think I understand basic stuff about pointers, references, etc which were in C++ before all this. Is it me or are these stuff getting too he...
Your question is very general. Maybe I can get you started: Ignore the functions std:move() and std::forward() at the beginning One aspect of RValue References is to save temporaries. In C++03 code, count the temps for Matrix z = a + b + c + d; (with Matrix a,b,c,d;) implement yourself operator+ on Matrix with overlo...
4,161,138
4,161,165
the this pointer set by Object(this) != this
the constructor for my engine constructs audio, video and input objects with a pointer to itself (this). However when I debug, I see all the classes I construct's enginePtr is not the same as the value of this provided by the debugger. When I peek inside, I see for example, the enginePtr of pRender has different values...
It's very unlikely. Your code seems logically fine to me. Instead or relying on debugger, try to print out the value of 'this' and whatever you stored in pRenderer. Sometimes, with optimization flags debuggers do not show the values of variables properly.
4,161,216
4,161,237
C++ equivalent of C# 4.0's "dynamic" keyword?
In C# 4.0, you can use the "dynamic" keyword as a placeholder for a type that is not known until runtime. There are certain corner cases where this is extremely useful behavior. Is it possible to emulate anything like this in C++, possibly using C++0x features or RTTI?
Not really. The closest you can get is a void *, but you still need to cast it to an appropriate type before you can use it. Update: Trying to build a duck-typed DSL that compiles to C++, basically. You can go about this in at least two ways: Union-based variant struct MyType { enum { NUMBER, STRING /* etc */ } typ...
4,161,494
4,161,635
Atomic counter in gcc
I must be just having a moment, because this should be easy but I can't seem to get it working right. Whats the correct way to implement an atomic counter in GCC? i.e. I want a counter that runs from zero to 4 and is thread safe. I was doing this (which is further wrapped in a class, but not here) static volatile int...
Your code isn't atomic (and your second get_count doesn't even increment the counter value)! Say count is 3 at the start and two threads simultaneously call get_count. One of them will get his atomic add done first and increments count to 4. If the second thread is fast enough, it can increment it to 5 before the firs...
4,161,501
4,161,512
Problems with srand(), C++
I'm trying to write a program that generates a pseudorandom numbers using a seed. However, I'm running into problems. I get this error 39 C:\Dev-Cpp\srand_prg.cpp void value not ignored as it ought to be Using this code #include <iostream> #include <iomanip> #include <sstream> #include <limits> #include <stdio.h> ...
srand doesn't return a random number, it just reseeds the random number generator. Call rand afterwards to actually get a number: srand(9); rand_int = rand();
4,161,588
4,162,127
Is a templated, polymorphic callback a good idea?
I'm making a Gui Api for games. The user can always use inheritance on the widget and override, but I want callbacks. I want to use a templated callback system: so if they want to have one for the mouse they inherit from a version of the templated callback base with mouseargs: So the base would look like this: template...
Have a look at boost::function and boost::bind. Accept a function object with a defined parameter list for particular events, and callers can do what they want. This gives callback implementations lots of flexibility and the object generating the events requires even less knowledge of the callback implementation. For e...
4,161,606
4,163,177
C++ and SDL: Problem with showing image?
For some reason SDL refuses to render an image. I don't see why and it's really bogging down my progress on a 2d game i'm developing. Everything is linked properly and such. Here's my code: //main.cpp #include "main.h" void game::createWindow(const int SCREEN_W, const int SCREEN_H, const char* SCREEN_NAME) { buffer =...
I just copied all of your code to use in code::blocks and it works fine. Of course I was using my own .bmp file which I named "zombie.bmp" Are you sure your .bmp file is ok? Be aware that if you originally save it as a .jpeg file or something like that, then simply renamed it to .bmp, it won't work (And it won't throw ...
4,161,712
4,161,898
C++ Best practice pattern of using polymorphic data member
What is the best practice pattern of using polymorphic data member in C++? The simplest one that I know is just using a plain pointer. For example, if the type of data member is not polymorphic: class Fruit { public: int GetWeight() { return 1; } }; class Food { public: Food(Fruit f=Fruit()) : m_fruit(f) ...
In this case, you're better off with separate default and copy constructors. Also, you shouldn't take the address of something passed in by reference; it could be an object on the stack that will go away soon. In the case of your function: void SomeFunction() { Apple a; food1.SetFruit(a); } a (and thus &a as well...
4,161,839
4,258,090
COM functions spawn threads that do not disappear
I am working on a small application that is meant to call some (really diverse) functions which are sadly out of my control and designed in such a way that I have no clue when the proper user action is done. In particular some of these spawn a thread to do their work in, which ends up dying at some point in the future....
I figured out the problem, and it was an obvious case of all the documentation being somewhere but not where you are looking, and a somewhat related subject has had a blog post on this issue which brought me to the missing piece. My app pops up an IContextMenu of a file (hence no ShellExecute in my code), and then allo...
4,162,021
4,162,033
Is it ok to call a function in constructor initializer list?
My gut feeling is it is not. I am in the following situation: class PluginLoader { public: Builder* const p_Builder; Logger* const p_Logger; //Others }; PluginLoader::PluginLoader(Builder* const pBuilder) :p_Builder(pBuilder), p_Logger(pBuilder->GetLogger()) { //Stuff } Or should I change ...
That's perfectly fine and normal. p_Builder was initialized before it.
4,162,400
4,162,419
How to find the calling convention of a third party dll?
Could any one explain me how to get to know the calling convention of a dll without getting and processing method names? Lets say our application is loading a third party dll and in order to handle it, is there any effective ways to get to know the calling convention of a dll? (__stdcall, __cdecl, __fastcall)
If the symbol begins with a _ but has no @, then it's __cdecl. If it begins with _ and has a @ it's __stdcall. If it begins with @ and has another @, it's __fastcall. source
4,162,407
4,164,964
C++ SDK WFP callout functions
Nowadays I am doing some research on WFP (Windows Filtering Platform) functions. But after googling for last 5days I did not find a single example of WFP callout functions. Would anyone please share some codes on it ? Thanks.
A sample is available here. The download link is dead, it got moved here.
4,162,669
4,162,684
How to close FILE* opened by _wfopen?
What's the counter part of _wfopen? I found that there is fclose related to fopen, but it seems there is no _wfclose.
I would say fclose(), since you don't actually need anything "wide" in order to close it.
4,163,049
4,163,136
x86 4byte floats vs. 8byte doubles (vs. long long)?
We have a measurement data processing application and currently all data is held as C++ float which means 32bit/4byte on our x86/Windows platform. (32bit Windows Application). Since precision is becoming an issue, there have been discussions to move to another datatype. The options currently discussed are switching to ...
It depends on what you do. Additions, subtractions and multiplies on double are just as fast as on float on current x86 and POWER architecture processors. Divisions, square roots and transcendental functions (exp, log, sin, cos, etc.) are usually notably slower with double arguments, since their runtime is dependent on...
4,163,126
4,163,223
"dereferencing type-punned pointer will break strict-aliasing rules" warning
I use a code where I cast an enum* to int*. Something like this: enum foo { ... } ... foo foobar; int *pi = reinterpret_cast<int*>(&foobar); When compiling the code (g++ 4.1.2), I get the following warning message: dereferencing type-punned pointer will break strict-aliasing rules I googled this message, and found th...
In order: Yes. GCC will assume that the pointers cannot alias. For instance, if you assign through one then read from the other, GCC may, as an optimisation, reorder the read and write - I have seen this happen in production code, and it is not pleasant to debug. Several. You could use a union to represent the memory ...
4,163,420
4,163,442
How can I create an instance of a type in a template function? (C++)
I need a template function which assigns a default value to the argument passed template <class T> inline T GetDefault() { return ???? # default value } T cand be bool, int, double and string. Thank you.
Default value (even with basic types) should be default "constructor" : template <class T> inline void SetDefault( T& value ) { value = T(); } For example, int-based types will be 0 by default (because explicitely initialized). This will obviously not work with types with no default value, like objects of class th...
4,163,639
4,166,429
Best approach to QT UI testing
I have a QT application with a bunch of menu within another menu. Each menu list item, when selected shows different forms. I would like to create another application that would test this QT application's menu if all the menu item selected are working and are showing the forms they're supposed to show. I'm a beginner ...
You can use OpenHMITester (OHT), that is an open-source GUI Testing tool (also valid to implement RPA automations) following an open architecture that describes a non intrusive capture/replay tool based on GUI Events. It was implemented to be used in Qt; however, it may be adapted to support different windowing systems...
4,163,799
4,163,806
Access outer struct with the same name
Look at my sample code struct A { int member; }; int main() { int A; //Line 1 A b; //Line 2 b.member = int(); //Line 3 } Errors are prog.cpp: In function ‘int main()’: prog.cpp:9: error: expected `;' before ‘b’ prog.cpp:9: warning: statement has no effect prog.cpp:10: error: ‘b’ was not declared in th...
How to remove the error in Line 2? Use Elaborated Type Specifier, i.e instead of writing A b; write struct A b;. 3.4.4 Elaborated type specifiers An elaborated-type-specifier may be used to refer to a previously declared class-name or enum-name even though the name has been hidden by a non-type declaration (3.3.7)....
4,163,932
4,163,982
Introductory material for creating file formats and doing serialization with C++
I am looking for a good short overview about things that are important when serializing data to files. What techniques exist to deal with later changes in data structures? Are there certain header structures that are commonly used? Specifically for C++: What library is appropriate for such tasks? Boost.Serialization? ...
The first part is the choice of format: is it an internal/external file? is it just used as temporary storage, or does it need to be edited/processed? are there any speed or storage space concerns? Once you have the format, you need to think about things like versioning: is backward-only compatibility OK, or do you ...
4,164,015
4,164,025
C++: derived classes and virtual methods
Possible Duplicates: C++ : implications of making a method virtual Why is 'virtual' optional for overridden methods in derived classes? I wonder, what is documented behavior in the following case: You have class A { virtual void A() { cout << "Virtual A"<<endl; } void test_A() { A(); } } class B: publi...
The sub-class member function is implicitly virtual if a virtual base-class member function with the same name and signature exists.
4,164,279
4,164,318
How are C++ array members handled in copy control functions?
This is something I have wondered for a long time. Take the following example: struct matrix { float data[16]; }; I know what the default constructor and destructor do in this specific example (nothing), but what about the copy constructor and the copy assignment operator? struct matrix { float data[16]; ...
This is what the standard says in 12.8 (Copying class objects). Copy construction: Each subobject is copied in the manner appropriate to its type: if the subobject is of class type, the copy constructor for the class is used; if the subobject is an array, each element is copied, in the manner appropriate to the eleme...
4,164,315
4,164,440
How to check if __PRETTY_FUNCTION__ can be used?
...../PluginLoader.h:34: multiple definition of 'Dummy_Func_For_Generating_FUNCTION_NAME_Macro()' The above error is output for the below code. I have include guards in my file. And everything else compiles fine. EDIT: What I was trying to achieve was to check if __PRETTY_FUNCTION__ was defined, and if it was, use it ...
void Dummy_Func_For_Generating_FUNCTION_NAME_Macro() is a function, not a macro. Functions don't create macros. Macros are resolved in preprocessor phase, and functions in compiler phase. Remove the function definition, and leave only #ifndef block. Use compiler identifying macros to figure out which function identifyi...
4,164,326
4,164,383
Finding a value of range less than or greater than from container class
Currently, I have a std::map <DWORD, DWORD> table and I'm looking for a key value matching a specific range. For example: Find a key value from map whose value should be either less than < 50 or greater than > 50 from the searched key value. If the searched key value was 20 then I would want a key value of range from m...
You can use map::lower_bound and map::upper_bound for this, if you know the midrange value upfront. map<int, MyClass>::const_iterator lower = myMap.lower_bound(-30); // or -70 if you prefer map<int, MyClass>::const_iterator upper = myMap.lower_bound(70); Both iterators need to be checked for myMap.end() before ...
4,164,364
4,164,644
Share files with unit tests using autotools
I have a project using autoconf and automake with following structure: / src/ class.h class.cpp test/ class_unittest.cpp In class_unittest.cpp I include class.h in the source file and on compile also the class.cpp file. In automake config for test I add ../src as a new include path in AM_CPPFLAGS = -I../src/ de...
You can use the srcdir variable to refer to the equivalent source directory in a VPATH build. AM_CPPFLAGS = -I$(srcdir)/../src
4,164,386
4,164,804
Fetch value from website and control relay?
I got a quite unusual question today from a client. They provide a mission-critical service where it's important that people are notified when a certain event happens. Currently they have an API that simply writes out TRUE or FALSE, when accessed by a web browser, depending on the state of their alert. They want to tak...
This project consists of two parts: Connect the internet to the PC. For example using Perl. use LWP::Simple 'get'; my $url = 'http://...'; my $value = get($url); if ($value =~ m/TRUE/) { switch_relay(1); } elsif ($value =~ m/FALSE/) { switch_relay(0); } Connect the PC to some hardware, switch_relay in the...
4,164,451
4,164,552
Why are qualifiers of template arguments stripped when deducing the type?
While building a little sample program with Microsoft VisualStudio 2008 I noticed an odd thing about the deduction of types passed to templates. Consider this example: template<class T> void f( T v ) { x; // trigger a compile error (void)v; } template<class T> void g( T v ) { f( v ); } void h() { int i;...
The answer is that although the variable v has type const int &, the expression v is an lvalue expression with type const int. litb provides the text (5/6): "If an expression initially has the type “reference to T” (8.3.2, 8.5.3), the type is adjusted to “T” prior to any further analysis, the expression designates the ...
4,164,809
4,164,899
Sort QMap<QString, int>
I have data struct QMap<QString, int> how can i sort it by int key? Thank you.
1) Create std::map<int, std::string> and push all data to it (or your QString and QMap). or 2) Create std::vector<std::pair<int, std::string>> vec, push all data to it and call std::sort(vec.begin(), vec.end()); or 3) Use boost::bimap
4,164,892
4,164,965
operator += overload, why const?
Possible Duplicate: What is the meaning of a const at end of a member function? Dear all, I was trying to overload the operator += and I was getting some error of "discard qualifiers", only by adding "const" at the end of a method, I was able to get rid of the error. Does anybody could explain me why this is needed?...
The operator+= method receives its argument as a reference-to-constant, so it is not allowed to modify the state of the object it receives. Therefore, through a reference-to-const (or pointer-to-const) you may only: read the accessible fields in that object (not write), call only the methods with the const qualifier (...
4,165,072
4,165,125
No implicit conversion in overloaded operator
d1 + 4 works but 4 + d1 doesn't even though 4 can be converted implicitly to a GMan. Why aren't they equivalent? struct GMan { int a, b; GMan() : a(), b() {} GMan(int _a) : a(_a), b() {} GMan(int _a, int _b) : a(_a), b(_b) {} GMan operator +(const GMan& _b) { GMan d; d.a = th...
A call x + y is translated by the C++ compiler into either of the following two calls (depending on whether x is of class type, and whether such a function exists): Member function x.operator +(y); Free function operator +(x, y); Now C++ has a simple rule: no implicit conversion can happen before a member access op...
4,165,131
4,165,312
C/C++: switch for non-integers
Often I need to choose what to do according to the value of a non-POD constant element, something like this: switch( str ) { case "foo": ... case "bar": ... default: ... } Sadly switch can only be used with integers: error: switch quantity not an integer. The most trivial way to implement such thing is then t...
Using some nasty macro and template magic it's possible to get an unrolled binary search at compiletime with pretty syntax -- but the MATCHES ("case") have to be sorted: fastmatch.h NEWMATCH MATCH("asd") some c++ code MATCH("bqr") ... the buffer for the match is in _buf MATCH("zzz") ... user.YOURSTUFF /*ELSE ...
4,165,260
4,165,280
C++ inheritance problem with namespaces
OK, I have been looking about but can not for the wits of me find a reason to why this should not work: Base class (misc/interface/handler.h) #ifndef __t__MISC_VIRTUAL_HANDLER_H #define __t__MISC_VIRTUAL_HANDLER_H #pragma message("Starting with 'handler.h'") namespace t { namespace misc { namespace interfa...
I can't see any implementation of t::misc::interface::Handler::Handler() in your code - and it is going to be called by the inheriting class's constructor, so it needs an implementation. The linker can't find it, so it complains. Just change: Handler(); virtual ~Handler(); in the abstract class to: Handler() {} virtua...
4,165,388
4,165,985
Inno Setup / ISTool: Detect local computer's IP address(es)
In the [code] section of my ISS script I want to detect the local machine's IP addresses. What is the most elegant way to accomplish this? Is there a Win32 DLL I can import via "external"?
I haven't seen any prepackaged DLLs that you could call but writing one should be too difficult. I found this post on the InnoSetup newsgroup: http://news.jrsoftware.org/news/innosetup.code/msg09240.html that might give you a start.
4,165,439
4,165,734
Generic way to cast int to enum in C++
Is there a generic way to cast int to enum in C++? If int falls in range of an enum it should return an enum value, otherwise throw an exception. Is there a way to write it generically? More than one enum type should be supported. Background: I have an external enum type and no control over the source code. I'd like t...
The obvious thing is to annotate your enum: // generic code #include <algorithm> template <typename T> struct enum_traits {}; template<typename T, size_t N> T *endof(T (&ra)[N]) { return ra + N; } template<typename T, typename ValType> T check(ValType v) { typedef enum_traits<T> traits; const T *first = ...
4,165,577
4,166,018
Segfault on call to boost::ip::tcp::resolver::query
Hopefully I provided the useful info, thanks. Backtrace (gdb) run Starting program: D:\C++\fail/ircserver.exe [New thread 4968.0x2f40] [New thread 4968.0x2cdc] Program received signal SIGSEGV, Segmentation fault. Irc::Client::getIP (this=0xbaadf00d) at D:/Dev-Cpp/include/boost/smart_ptr/shared_ptr.hpp:409 409 ...
0x004063c9 in Irc::Client::getHostName (this=0xbaadf00d) at D:/Dev-Cpp/Bin/../lib/gcc/mingw32/3.4.5/../../../../include/c++/3.4.5/bit On Windows, this=0xbaadf00d means that *this is not properly initialized. In this case, I suspect that's because of the line client(client) in the definition of Irc::User::User, which s...
4,165,631
4,170,562
Converting SNMP OIDs to descriptive names on Win32
Whats the recommended way of converting SNMP OIDs to their equivalent descriptive names? i.e. from 1.3.6.1.2.1.1.9.1.4.7 to SNMPv2-MIB::sysORUpTime.7 I'm coding in C++, platform should be XP and above, and looking for a fairly fast and small footprint way of doing this. I know that libsmi or net-snmp can do this, but i...
Microsoft does not have any Win32 API for such conversion (the closest thing is this Managing Object Identifiers). So libsmi is still the way to go. Or you can call snmptranslate process. If you use netsnmp API, you should use its location to store MIB files. Windows usually hold MIB files in %windir%\system32, but th...
4,165,910
4,165,924
simple string question
If I assign a new value too previously declared string using operator= , is it freed automatically or I have to free it manually? std::string s("value_old"); s = "value_new"; what happens with "value_old" where I can find or where are you always watching to find answer to similar questions? Thanks in advance.
Yes, it is freed automatically. I suggest cplusplus.com for a handy online reference to STL.
4,165,956
4,166,458
Parallel Inheritance between Interface Classes and Implementation Classes in C++
I'm trying to use C++ abstract base class in the way similar with Java interface. Supposed that we have following interface classes with only pure virtual functions: class Shape { virtual double area()=0; }; class Square : public Shape { virtual void setLength(double length)=0; }; class Rectangle : public Square { virt...
What you have here is the case of the Diamond Problem, which can happen in any OO language that allows multiple inheritance. This, by the way, is one reason why the designers of Java decided not to have multiple inheritance, and came up with the notion of an interface. The way C++ deals with the diamond problem is Vir...
4,166,115
4,166,289
COM object lifetime management in an ATL service
I'm trying to get my head around the concept of writing a Windows Service using ATL. I've created a project and understand that I can override CAtlServiceModuleT functions to achieve my needs for the service. What I'd like to do is have the service create a COM object (called Manager) that deals with the scheduling and...
You could use CComClassFactorySingleton to create such an object.
4,166,489
4,167,274
How can i get constituents of a member function from its address?
Is it possible to get the constituents of a member function such as class type or return type just from its address (not from member function type) ? For e.g. given class foo { int bar() { return 5; } }; i like to have is_same< function_types<&foo::bar>::class_type, foo>::value == true; I a...
In C++ pre-0x, you can't do this very easily. In C++0x, you can use a combination of template functions and decltype to do this: template <typename R> struct unary_function_info { typedef R result_type; typedef void class_type; }; template <typename R> unary_function_info get_function_info(R (*)()); template <typename...
4,166,642
4,167,065
How much memory should 'managed_shared_memory' allocate? (boost)
I'm looking for a definitive answer (if indeed one exists) on how much memory should be allocated when creating a static chunks of shared memory via boost::interprocess's managed_shared_memory. Even official examples seem to allocate arbitrarily large chunks of memory. Consider the following structure: // Example: simp...
From this paragraph of the documentation : The memory algorithm is an object that is placed in the first bytes of a shared memory/memory mapped file segment. Layout of the memory segment : ____________ __________ ____________________________________________ | | | ...
4,166,706
4,166,918
Distance UTC - LocalTime on Linux
I am writing a Linux (Ubuntu and Debian Lenny) application in C++. Now I need to know the distance/offset between UTC and the currently set system time at a given day in the past. Since I need to convert recorded data, I the distance need to be calculated with respect to a date in the past (which may have a different D...
Prepare the tm structure with date: struct tm date; memset(&date,0,sizeof(date)); date.tm_year = year - 1900; date.tm_mon = month - 1; date.tm_mday = day; date.tm_hour = hour; date.tm_min = minute; date.tm_sec = second; date.tm_isdst = -1; // VERY IMPORTANT mktime(&date); /// fill rest of fields And then take a look ...
4,166,757
4,167,601
Runtime error with tinyXML element access
yester day was my first attempt. I am trying to catch the variable "time" in the following "new.xml" file <?xml version="1.0" standalone=no> <main> <ToDo time="1"> <Item priority="1"> Go to the <bold>Toy store!</bold></Item> <Item priority="2"> Do bills</Item> </ToDo> <ToDo time="2"> <Item priority="1"> Go to ...
It seems to me that you forgot to load the file. Normally I do something along these lines: TiXmlDocument doc("document.xml"); bool loadOkay = doc.LoadFile(); // Error checking in case file is missing if(loadOkay) { TiXmlElement *pRoot = doc.RootElement(); TiXmlElement *element = pRoot->FirstChildElement(); ...
4,166,775
4,166,952
Where are the DLL's referenced in my .net C++ Dll/Tlb?
I created a .net C++ dll, which I then converted to a tlb file for use in a native C++ application. I referenced other external dll's in my dll. Now, I am trying to deploy, and want to copy over the referenced dll's to the deployment computer. Where do they reside in my .net C++ project?
The default behavior is for the build system to copy any referenced assemblies to your build output directory. So that you can debug the result. This copy won't happen when the reference assembly is in the GAC, like is the case with any .NET framework assembly. In other words, you should find them back in your Releas...
4,166,886
4,166,919
Reverse of a number with leading zeroes
How do we reverse a number with leading zeroes in number ? For ex: If input is 004, output should be 400. I wrote below program but it works only when no leading zeroes in input. int num; cout<<"Enter number "<<endl; cin>>num; int rev = 0; int reminder; while(num != 0) { reminder = num % 10; rev =...
Leading zeroes are not represented by binary numbers (int, double, etc.) So you'll probably have to use std::string. Read the input into the string, then call std::reverse() passing the string as input.
4,166,914
4,167,285
How do I find the dependencies on a dll :: GLUT specifically
I have been learning opengl for about 4-5 months now. I am ready to stop using glut(a helper library that obfuscates many difficult / tedious aspects of opengl programming ) Problem is, I feel I have removed all refrences to glut.h, as well as all function calls within glut, but when I run my application it is still t...
Dependency Walker is your friend for examining the dll dependencies of compiled binaries. The principal problem is of course, you have added glut.lib or glut32.lib to your project someplace. Its probably in the Project Properties > Linker Settings > Additional Libraries, or some source file contains a #pragma something...
4,166,999
4,167,022
How can I push_back data in a vector via a vector::pointer?
I 'd like to use a vector::pointer so as to push_back data in it.. int num; vector<int> v; vector<int>::pointer ptr; ptr = &v[0]; ptr->push_back(num); // fail ptr.push_back(num); // fail ptr.push_back(&num); // fail *ptr.push_back(num); // fail nothing appears to work.. any ideas would be appreciated..
You can't. You need to use the original vector object. If you'd like to have a pointer to a vector, you can do the following: vector<int> v; vector<int> *pointer = &v; v.push_back(4); pointer->push_back(3); As a comment, the type of vector<int>::pointer in your code should be int *.
4,167,150
4,187,849
In the Concurrency Runtime, can I use parallel_invoke or task_group with non-const function objects?
I'm using the Concurrency Runtime with Visual C++ 2010, and am interested in the capabilities of parallel_invoke and task_group (parts of the PPL or Parallel Patterns Library). I'd like to be able to start two parallel actions via function objects (rather than lambda functions or function pointers), but I can't get the...
The functors are required to be immutable because when they are scheduled via parallel_invoke and task_group::run they are copied and the potential for race conditions during state accumulations is high. Particularly with task_group::run the lifetime of the task has the potential to outlive where the task was declared...
4,167,233
4,178,543
How do I pass arrays from Java to C++ using Swig?
I have a method in C++ that takes an array of doubles as an argument. I'm calling this method from Java and need to pass an array of doubles. The C++ routine reads and modifies the values of the array and I need those updated values in Java. How do I do this? For example, take the C++ routine: void myMethod( double ...
Use carrays.i! See Swig docs on carrays %include carrays.i %array_functions( double, double_array ) These two lines create the following code in my module: public static SWIGTYPE_p_double new_double_array(int nelements) { long cPtr = SimulatorModuleJNI.new_double_array(nelements); return (cPtr == 0) ? null : ...
4,167,283
4,167,350
benchmark a piece of code independent of CPU performance?
My Objective is : I want to test a piece of code (or function) performance, just like how I test the correctness of that function in a unit-test, let say that the output of this benchmarking process is a "function performance index" which is "portable" My Problem is : we usually benchmarking a code by using a timer to ...
I think you are in search of the impossible here, because the performance of a modern computer is a complex blend of CPU, cache, memory controller, memory, etc. So one (hypothetical) computer system might reward the use of enormous look-up tables to simplify an algorithm, so that there were very few cpu instructions pr...
4,167,581
4,167,676
Strange test result. My win32 program works slower when I am not using it
I have done some tests with QueryPerformanceCounter and got strange results. It seems that my simple program refreshes slowly (about 40ms) when it doing nothing, but when I put RedrawWindow with RDW_INVALIDATE message it refreshes and works very fast (about 1ms) Please look at the examples: {...} double PCFreq = 0.0; _...
GetMessage does not return unless there is a message in the message queue. By calling RedrawWindow, you are putting a Message in the queue every single iteration of the loop. Use PeekMessage instead of GetMessage: while (true) { if (PeekMessage(&messages, NULL, 0, 0, PM_REMOVE)) { if (messages.message...
4,167,589
4,168,305
My graphic representation and interpretation of socket-based models
http://img600.imageshack.us/img600/3567/graphicrepresentation.png Am I reasoning right way? If so, could anyone please show me, like in scheme above, how would I/O Completion Ports work? Before I'll start to learn about making high-performance servers like ones for MMORPGs, I want to know for sure how does it all work....
With IOCP all your send and recv calls are handled by a pool of threads (a small pool is usually fine) so draw one box with send/recv in it, have 3 red dots above it and 10,000 blue ones below it. With IOCP you issue a series of overlapped requests. Once these requests complete they are placed in a queue (the IOCP) an...
4,167,662
4,167,761
Can I prevent zero initialization of the elements in an array data member in a non-POD class?
Non-POD derived class PayloadMessage contains an array data member (_payload) whose elements appear to be getting zero initialized upon construction. I don't want this to happen for performance/efficiency reasons -- it is a large array. Suggestions? (Placement new maybe?) I'm using an older g++ compiler, 3.4.6. #in...
POD is only explicitly value initialized when using () (8.5 in the C++ standard), otherwise, it is default initialized. Default initialization of POD means it does not do anything to the memory. If operator new is returning zero initialized memory, then the constructor of PayloadMessage isn't doing any extra work. Out ...
4,167,814
4,167,905
Polymorphic operator on a list of boost::any?
Suppose I have a list of type list<boost::any> that has some type in it that is unknown. Now suppose I want to apply some operation to the elements in the list that is polymorphic. In this case, consider the + operator. Suppose that I know that the list will always contain a homogenous set of objects that support opera...
You could use boost::variant instead if you know the range of possible types in the list. I don't see how you can do this without a mesh of operator+ functions to handle every possible combination of contained types, or regular runtime polymorphism. What is the concrete type you wish to see in the final boost::any o...
4,167,904
4,167,952
Confusion in range of enums
How to find the range of enums ? I have got two versions which state it differently when the lowest value is negative.Stroustrup says that for enum e3 { min = -10 , max = 1000000 }; // range -1048576:1048575 but C++ Primer Plus 5th edition says for eg if the smallest enumerator is -6, the next power of two [times a...
I believe both are correct (see below for Primer's definition, though), depending on how compatible you want to are. The formal definition is For an enumeration where e min is the smallest enumerator and e max is the largest, the values of the enumeration are the values of the underlying type in the range b min to b m...
4,167,972
4,168,149
How to record keystrokes on Windows [C++]
I need to record keystrokes (if user pressed 'ABCS', I wand that saved in a string) if the user switches to a certain window which is name is AAA, the windows is not of the current application, but can be of any other one. I guess I know how to get the current window name, its something like that: #include <windows.h> ...
Probably the easiest way is to use the AttachThreadInput function. Use GetWindowThreadProcessId to get a thread id from a window handle.
4,168,245
4,168,270
Create custom #warning flags
I'm building a commercial app, and we are using some GPL code to help us along. How can I add #warning or #error statements so that when the code is built for debug, it warns, but when we build for release it throws errors? I can do: #warning this code is released under a CCL licensing scheme, see Source_Code_License.r...
Use #pragma message instead.
4,168,369
4,168,860
How does a UNICODE environment block look like to start a new process via CreateProcessW() on Windows?
Essentially, I would like to create a new process and define the environment for it from the parent process. I would like to use CreateProcessW and pass a (modified) UNICODE environment into lpEnvironment, but I'm not sure what the content should look like compared to an ANSII environment block. The only documentation ...
I have no idea what you are doing wrong without code. But this works: STARTUPINFO startInfo = {0}; PROCESS_INFORMATION procInfo = {0}; WCHAR env[] = L"key=value\0key2=value2\0\0"; WCHAR cmdline[] = L"calc"; startInfo.cb = sizeof(startInfo); if(!CreateProcessW(NULL, cmdline, NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONME...
4,168,437
4,168,539
Boost Library Format; getting std::string
I want to add some string which I format using the boost library as follows boost::container::vector<std::string> someStringVector; someStringVector.push_back( format("after is x:%f y:%f and before is x:%f y:%f\r\n") % temp.x % temp.y % this->body->GetPosition().x % this->body->GetPosition().y; Th...
You need to wrap the format in a call to boost::str, like so: str( format("after is x:%f y:%f and before is x:%f y:%f\r\n") % temp.x % temp.y % this->body->GetPosition().x % this->body->GetPosition().y)
4,168,718
4,168,830
Need Memory Usage Tool per C++ function on Linux
I'm looking for a runtime memory debugger, capable of showing memory usage (not just leaks) per function or line of C++ code on Linux. I am trying to track down a spike in my program memory usage. I have used Valgrind and Purify and I found that there are are no leaks. I expected that, as after that spike, the memory u...
You can use the massif tool from the valgrind pack of tools.
4,168,748
4,168,780
tchar.h not found on cygwin
I'm running the latest cygwin on windows 7 (32-bit), and trying to build an open-source project, RtAudio (it doesn't currently build on this platform). One of the problems I've worked around is an error on the line #include <tchar.h>. My build line is: g++ -O2 -Wall -Iinclude -DHAVE_GETTIMEOFDAY -D__WINDOWS_DS__ -c R...
tchar.h is a Windows header. The software will have to be ported to libiconv or ICU if it needs more than just the basics.