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
5,232,763
5,232,794
linux - get pid of process
How can I get the PID of a service called abc using C++ on Linux without using a system call? I would appreciate any examples that you care to offer.
Google has this covered :) http://programming-in-linux.blogspot.com/2008/03/get-process-id-by-name-in-c.html Although it does use sysctl, which is a system call! It's C but should work just as well in C++
5,232,912
5,233,170
How to use delay loading with a DLL that exports C++ classes
I have a DLL one.dll that uses a class TwoClass exported from two.dll via class __declspec(dllexport). I'd like one.dll to use /delayload for two.dll, but I get a link error: LINK : fatal error LNK1194: cannot delay-load 'two.dll' due to import of data symbol '"__declspec(dllimport) const TwoClass::`vftable'" (__imp_?...
Have a look here, seems that the person had exactly the same problem and found a workaround I managed to get the delay loading to work in release build by disabling the optimizations on the translation unit that was using SomeClass class - somehow it took away the dependency on exported vtable.
5,233,102
5,233,395
C++ external file read: I know how to find and read a string, findMe. But how do I deal with findMei (finding any number, i, of the string)?
Apologies in advance, because I suspect this may be a silly question. I have written a function for reading in data from an external file. I then use the data to perform calculations using other code I have written. The function works by finding a data label that looks like this: const std::string findMe = "<dat...
you've already got the right answer, so this is just trying to help you with solving such problems in the future: Your core problem here is to convert the integer i into a string s (if you've done this, than you just do findMe = "<datalabel"; findMe += s; findMe += ">";. Googling for c++ convert integer into string wi...
5,233,478
5,233,665
unable to register a dll in windows 7 enterprise x64
trying to register a DLL built with visual c++ 2005 and another DLL built with visual c++ 2008. the system config is windows 7 enterprise 64 bit I tried running regsvr32 from default location and from c:\windows\syswow64 in either case I'm getting the error I have C++ redistributable runtime library installed for 200...
The VITInterface.DLL probably depends on an another DLL. Try Dependency Walker to see what else your DLL needs.
5,233,528
5,233,595
question on class definitions
I saw that the following two class definitions are claimed to be equivalent. Is that true? How? Thanks. class complex{ double re, im; public: complex( ): re(0) , im(0) { } complex (double r): re(r), im(0) { } complex (double r, double i): re(r), im(i) { } }; class complex{ double re, im; public: ...
The first one lists all the possibilities (no parameter, one parameter, two parameters) separately (overloading), the second one only needs one function because of usage of default parameters, which is exactly the same but much shorter. The first one is still useful if initialization of variables is more than just assi...
5,233,568
5,233,689
Casting boost::shared_array<void> to boost::shared_array<int>
I have some legacy code that looks like this: void* getData(DataType dataType) { switch(dataType) { case TYPE_FLOAT: return new float[ rows * clms ]; case TYPE_INT: return new int[ rows * clms ]; case TYPE_DOUBLE: return new double[ rows * clms ]; default: ret...
You can't just convert, because shared_array<void> doesn't know how to delete a void* pointer to an array of int. You could try something like shared_array<void>(new int[rows*clmns], checked_array_deleter<int>()), although I haven't tested that it's right. You probably need to wrap the deleter in something that convert...
5,233,800
5,566,322
Resizing an ActiveX video control on a form causes unwanted flicker in C++, even with doublebuffering
C++. Borland Developer Studio flavour, but not sure if that is relevant here. I have an ActiveX control (From Axis Communications) that displays video from a camera. It works great in normal operation, but I want to do a little adjustment with it that is causing issue. If, programatically, I move the component around t...
This appears to be an issue with Borland and rendering/resizing of ActiveX controls. When I altered the code to use the 'SetWindowPos' API instead of just resizing the component, the issues went away!
5,233,856
5,234,012
c++ struct and container
I am writing a small software which deals with inter-process multicast. For each message, on each process, I have a couple of variables assigned to the message itself: messageID senderID ack1 ack2 ack3 ... I would like to put these elements (which are many) in a container, so that it is later easy to perform operation...
You might want to use std::map or boost::unordered_map (soon to be standard) as you can access it by message id. Next time you'd want to answer such a question alone, take a look at this diagram.
5,233,918
5,233,993
Template partial specialization
template<class T> struct TypeX; template<> struct TypeX<int(...)>//HERE IF WITHOUT ELLIPSIS IT WILL COMPILE { static std::string get_type() { return "int()"; } }; template<> struct TypeX<int> { static std::string get_type() { return "int"; } }; template<class T> struct type_de...
The question is why if I specialize for ellipsis, which suppose to mean any number I'm getting an error, but when I specialize for no arguments it compiles? Because ellipsis doesn't imply any number of parenthesis (as you're trying to use it in main) . ellipsis is used to imply variable number of arguments i...
5,233,963
5,234,101
overloading new and delete C++ for tracking memory allocations
I need help in understanding the code snipped below...allocate is a function that would be called by the overloaded new operator to allocate memory. I am having problems trying to understand the following casts in particular: *static_cast<std::size_t*>(mem) = pAmount; //please explain? return static_cast<char*>(mem) +...
The allocator keeps track of the size of allocations by keeping them along with the blocks it serves to client code. When asked for a block of pAmount bytes, it allocates an extra sizeof(size_t) bytes at the beginning and stores the size there. To get to this size, it interprets the mem pointer it gets from malloc as a...
5,234,121
5,234,195
Data not aligned correctly in Visual Studio if run in debugger
I've been working with SSE for a while now, and I've seen my share of alignment issues. This, however, is beyond my understanding: I get different alignment whether I run the program using F5 (debug) or whether I run it outside the debugger (Ctrl+F5)! Some background info: I'm using a wrapper for a SSE-enabled ...
When running under the debugger, you're using the debug heap, which may affect alignment. Set _NO_DEBUG_HEAP=1 in your environment settings, and see if this helps. See e.g. http://msdn.microsoft.com/en-us/library/aa366705%28v=vs.85%29.aspx However, alignment is not guaranteed when allocating with malloc or new. The "co...
5,234,169
5,234,241
Why do function prototypes include parameter names when they're not required?
I always thought that a function prototype must contain the parameters of the function and their names. However, I just tried this out: int add(int,int); int main() { std::cout << add(3,1) << std::endl; } int add(int x, int y) { return x + y; } And it worked! I even tried compiling with extreme over-caution:...
No, these are not necessary, and are mostly ignored by the compiler. You can even give them different names in different declarations; the following is entirely legal: int foo(int bar); int foo(int biz); int foo(int qux) { ... } (The compiler does check that each name is used only once in the same argument list: i...
5,234,311
5,234,347
include stdafx.h in header or source file?
I have a header file called stdafx.h and this one is precompiled of course. I've read that I should include these files into my .cpp files, but some of these statements are already needed in the header file coming with that. Should I add the stdafx into my header or into my cpp? I thought it was good practise to put it...
stdafx.h should be the first include in EVERY cpp file in your project. Consider that C++ doesn't compile header files, just Cpp files. Therefore if the stdafx is the first include in the cpp file, then the compiler will have everything the header file needs, when it hits the header-file in the Cpp file. e.g. You h...
5,234,382
5,234,450
Questions on member function design for the class Complex
In the book The C++ Programming Language, the author claims that, for the following class design, class complex{ double re, im; public: double real( ) const { return re;} double imag( ) const { return im;} }; Given real() and imag(), we can define all kinds of useful operators without granting them direc...
Since operator== is a free function, which is not even friend of the class, so it cannot acess the private members of the class, but it has access to public member functions of complex, so it can implement operator== with the help of public member functions. That is what meant by the author. This is also a good demonst...
5,234,449
5,234,570
C++ Cross platform libraries
I'm not exactly new to C++ but I've never managed to get my head around Libraries. I would like to split my networking, graphics and input class sets out of my main executable so that I can update them individually rather then sending out a recompiled version of all the code as a single executable. Is this possible and...
As @Armen said in the simplest of terms, one of the requirements here is a library that works as cross-platform as possible/needed. Qt is the obvious choice for this. There are others like wxWidgets that achieve the same thing and the choice is up to you. The second thing is that all the "upgradeable" libraries need to...
5,234,530
5,234,594
hide C++ Gnuplot pipe console output
In C++I'm currently using this bit of code to plot some data using gnuplot. Gnuplot's fit command, however, produces a lot of unwanted output on the command line console (which I use for outputting some other stuff too, throughout the rest of my program). Since this output clutters up my console output, I would like t...
You could just use: FILE *pipe = popen("gnuplot -persist > /dev/null", "w") Or, if gnuplot uses stderr: FILE *pipe = popen("gnuplot -persist > /dev/null 2>&1", "w")
5,234,573
5,235,654
How do you use the batch mode of CUFFT?
I am trying to figure out how to use the batch mode offered in the CUFFT library. I basically have an image that is 5300 pixels wide and 3500 tall. Currently this means I am running 3500 1D FFT's on those 5300 elements using FFTW. Is this a good candidate problem to run the CUFFT library in batch mode? How does the dat...
yes this is a good problem. You should go the following way: create a array with size: sizeof(cufftComplex)*5300*3500 at the gpu(here I assume that you have complex input data) copy your data to the gpu create a plan with cufftPlan1d() execute the plan for example with cufftExecC2C() For more Information you must hav...
5,234,619
5,234,689
How does the following statement evaluate?
I am having problem understanding as to what the following statement means(not the tertiary operator part) - return(((*data)*(tmp_left)<(*data)*(tmp_right))?tmp_left:tmp_right); where data is a pointer and tmp_left is a variable of type int. This line is in relation to a tree structure, if that helps. To be exact I w...
Without knowing the data types, and knowing that it's used in a tree (assuming it's a BST) this looks like a comparison of data values. In essence, when you have a BST you will either insert nodes to the left of the immediate node or the right of the immediate node. It looks like the data value is contained within the ...
5,234,978
5,235,067
Can getters and setters be inlined when definition and declaration are seperated in .h and .cpp files?
I have searched and have been unable to verify how the GCC compiler will handle inlining getters and setters when declaration is in .h file and definition is in .cpp file. Most seem to say that GCC can't see across these source file barriers and won't be able to inline these at all, while others disagree. I have looked...
(What you really meant to ask is about the situation where the definition is in a different .cpp file to the one you're currently compiling, and then linked in later. The compiler doesn't care about .hpp or .cpp, but about translation units.) Anyway, on http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html, scroll do...
5,235,188
5,235,253
C++ Perfect Function Forwarding
This is a followup to this question. A 2002 paper on the function forwarding problem in C++ makes the following observation: This is the method currently employed by Boost.Bind and Boost.Lambda: template<class A1, class A2, class A3> void f(A1 & a1, A2 & a2, A3 & a3) { return g(a1, a2, a3); } Its main deficienc...
Are not the literals 1, 2, 3 const rvalues? No, they are just rvalues of type int. According to the C++ standard, rvalues of primitive types cannot be const-qualified. The call fails because they are rvalues - non-const references cannot be bound to rvalues. The call would be OK if the functions took const A1 &, const...
5,235,246
5,236,231
Transform variadic template parameters to another types
How to transform types from variadic template parameters to another type? For example: template <typename... T> struct single { std::tuple<T...> m_single; }; template <typename... T> struct sequences { single<T...> get(size_t pos) { // I don't know how to convert here return std::make_tuple(std:...
You can do more than just expand a variadic parameter pack as a plain list: you can expand an expression too. You can therefore have m_sequences be a tuple of vectors rather than a tuple of the elements: template <typename... T> struct sequences { std::tuple<std::vector<T>...> m_sequences; }; You can also do nifty ...
5,235,291
5,235,607
boost::transform_iterator and boost::bind
I'd like to use the boost::transform_iterator together with boost::bind to return the result of a member function. e.g. class Foo { public: //... Bar& getBar(); const Bar& getBar() const; }; I've got a unary Function object to select the getBar() function struct getBar: public std::unary_function<Foo&,Bar&> { getBar...
boost::transform_iterator<boost::function<Bar&(Foo&)>,std::vector<Foo>::iterator>
5,235,648
5,235,804
Does the Standard specify how a source file needs to be compiled and would an extra preprocessing step be non-Standard?
The question might be a bit vague, but take as a prime example Qt's moc step. Is it non-standard or allowed by the standard, as everything the compiler sees is still pure and valid C++. Another example would of course be the config.h file, which needs to be generated by the build system just like the moc files are. I w...
I don't have a copy of the standard here (long time ago read some portions of the draft though), but I'm quite sure the standard doesn't even dictate sources have to be present as files. If I remember correctly, a long time back (in the 90s) IBM's Visual Age C++ IDE tried to abandon storing sources in files altogether....
5,236,067
5,236,679
C++ Files and Folders access View and Control
two quick Qs: 1. Is it possible to write a program which keep record of folders and files a User access to? (i.e. browse) 2. and Control his/her access? (deny access to some of folders, programs, file and ...) I know about file system security and stuff but I meant here is at first a monitoring system which keeps recor...
Use a DACL to control access. Use an SACL to monitor access. If you really want to know everything they look at (including things like USB drives that won't have an ACLs assigned) you'll probably need to use a hook on WH_SHELL to get notified about their use of the shell. You could also use something like the Detours l...
5,236,082
5,236,747
vectors: rend() is being invalidated by erase()
According to the C++ specification (23.2.4.3), vector::erase() only invalidates "all the iterators and references after the point of the erase" As such, when using reverse_iterators to pass over all vector members, an erase on the current iterator should not cause the rend() member to be invalidated. This code will run...
Your program invokes Undefined Behavior. Therefore, neither compiler is incorrect. According to the Standard, std::vector<int>::reverse_iterator is a typedef for std::reverse_iterator<std::vector<int>::iterator>. The implementation of std::reverse_iterator<Iter> is specified to have a protected member Iter current;, ...
5,236,232
5,236,270
std::shared_ptr with std containers
I have a container of shared_ptrs and I hand these objects off to a windows API and I get a callback later with the raw ptr. I want to locate the right shared_ptr after the fact. Can this be done with shared_ptr cleanly? (without using shared_from_this()). very basic example: class CFoo { }; typedef std::shared_ptr<CFo...
Why not the obvious way? Iterate through the container, and if(iterator->get() == rawPointer) container.erase(iterator) Edit: To utilize O(logN) lookup you can do what you want (that is, create a shared_ptr with no_op deleter). It may be ugly, but it's not dangerous
5,236,320
5,236,385
how to create custom wm_copydata in mfc c++
How can I create a custom windows message that passes any data to a different program. I am messaging between a GUI-program and a server-program. My background is in *nix programming and I am a bit lost in the windows world. Currently both programs are created by Visual Studio's wizard by chosing "MFC windowed applicat...
WM_COPYDATA does marshalling for you, provided you've correctly initialized the COPYDATASTRUCT that you're passing as the LPARAM (lpData is the pointer, not dwData). Custom messages won't do that, and you don't want to reimplement marshalling by hand. If you need marshalling, use WM_COPYDATA. Is that what you're askin...
5,236,706
5,236,753
What is i+++ increment in c++
can anyone tell me what is the process of i+++ increment in c++.
It is a syntax error. Using the maximum munching rule i+++ is tokenized as: i ++ + The last + is a binary addition operator. But clearly it does not have two operands which results in parser error. EDIT: Question from the comment: Can we have i++++j ? It is tokenized as: i ++ ++ j which again is a syntax error as ++ ...
5,236,842
5,237,004
Keep my process alive - always
Is it possible to stop users (even admin) from killing my program? or in case of killing, it restores itself quickly? UPDATE: to clarify: I'm writing a monitoring program, something like parental control which keeps record of what a user do with PC. you can guess that by viewing my other questions recently. The first n...
First, don't do that. Second, still don't do that. Third, if your program is sooooo awesome that it should never stop running you could always provide the capability to install a service that runs your program and restarts it if it dies. But think long and hard about that because users typically get pretty annoyed abou...
5,236,964
5,237,019
Display image and resources problem
I am using netbeans 6.9 with QT on ubuntu. I want to display an image in my release build , but i got this error when compiling: /usr/bin/rcc: File does not exist 'res.qrc' This is my res.qrc file <RCC> <qresource prefix="image"> <file>icon.gif</file> </qresource> </RCC> In my qt-Release....
You set <qresource prefix="image"> but then note that the image is in my main project folder(where the source files are located) That's one problem. It would need to be in the image folder.
5,237,013
5,238,284
FBO to separate textures
How do I set FBO so it renders depth and color buffer in two separate textures, in one rendering pass ?
Just attach a suitable texture to the FBOs depth attachment point: glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,GL_TEXTURE_2D, textureId, 0); .. and another texture to the color attachment point. See this for more information.
5,237,163
5,237,210
How does the following code work?
#define TYPE_CHECK(T, S) \ while (false) { \ *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \ } I am reading Google v8's code and found the above macro for type check. However, I do not understand why it work...
Yes, but the compiler still performs syntax & semantic checks on the loop contents. So if something is wrong (i.e. the implicit type conversion from S* to T* is illegal, which happens if T is neither S nor a base class of S), compilation fails. Otherwise, the quality of the resulting machine code is not affected since ...
5,237,175
10,918,972
process video stream from memory buffer
I need to parse a video stream (mpeg ts) from proprietary network protocol (which I already know how to do) and then I would like to use OpenCV to process the video stream into frames. I know how to use cv::VideoCapture from a file or from a standard URL, but I would like to setup OpenCV to read from a buffer(s) in me...
I had a similar need recently. I was looking for a way in OpenCV to play a video that was already in memory, but without ever having to write the video file to disk. I found out that the FFMPEG interface already supports this through av_open_input_stream. There is just a little more prep work required compared to th...
5,237,227
5,564,807
A multi-thread implementation of CppUnit?
Could someone point me to a version of CppUnit that would allow to launch the tests in separate threads? The idea is that, because many of our tests are quite CPU heavy (but are not multi-thread and, of course, are independant one from the other), it would allow us to run the tests much more quickly on today's multi-co...
You think five minutes is a long time to wait for tests to complete! Try several hours. I had motivation for the following. Using Boost threads, CppUnit threading is pretty easy. CppUnit already has some hooks for synchronization so the following should make it thread safe: class Mutex : public CPPUNIT_NS::Synchroni...
5,237,542
5,237,595
C++ delegate creation
I was wondering if theres a way to mimic this delegate behaviour (from C#) in C++ new ModifyTargetingStatus("Reversal", "Reverses physical attacks back at the user", -1, new List<CALL_CONDITION>(){CALL_CONDITION.Targetted}, attemptChange: delegate(CharacterMove move, BattleCharacter[] users, ref BattleCharacter[] targe...
These are called anonymous functions (lambdas), and aren't supported in C++. From the wikipedia article: "Anonymous functions were added to the C++ language as of C++0x."
5,237,639
5,237,821
command pattern serialization in c++
I want to do the folloing in C++: create a command object serialize it (send it to another computer) deserialize execute Two cases: sender and receiver are both win 7 computers sender is *nix and receiver is win 7 I found a tutorial for searialization: http://www.functionx.com/cpp/articles/serialization.htm. Is thi...
I would also recommend using a stable library like boost.serialization for serializing data. If you are new to serialization, it means transforming objects into a data representation suitable for transmission or storage and rebuilding them from that data representation. The difficulty is not really big with so-called P...
5,237,754
5,315,748
Strange error when adding #include <string>
I have the following very simple application that compiles and runs fine: EDIT: changed the example to be simpilar to end confusion of the real issue int main() { return 0; } As soon as I add #include <string> (and not even reference std::string), it fails to compile and I get the following error: /usr/include/c++...
The problem appears to be the installed development packages are not correct or incomplete (not to be confused with corrupt). Forcing g++ to use different include versions corrects that: g++ -nostdic++ hello.cc -o hello -I/usr/include/c++/3.4.6 All the alternative directories (4.1.1, 4.1.2 and 4.3.2) are incomplete cau...
5,237,961
5,239,572
Why does does SSE set (_mm_set_ps) reverse the order of arguments
I recently noticed that _m128 m = _mm_set_ps(0,1,2,3); puts the 4 floats into reverse order when cast to a float array: (float*) p = (float*)(&m); // p[0] == 3 // p[1] == 2 // p[2] == 1 // p[3] == 0 The same happens with a union { _m128 m; float[4] a; } also. Why do SSE operations use this ordering? It's not a big d...
It's just a convention; they had to pick some order, and it really doesn't matter what the order is as long as everyone follows it. Intel happens to like little-endianness. As far as accessing by index goes... the best thing is to try to avoid doing it. Nothing kills vector performance like element-wise accesses. If...
5,237,963
5,237,994
Cross platform , C/C++ HTTP library with asynchronous capability
I'm looking for a C/C++ library that will work on Windows and Linux which will allow me to asychronously query multiple webservers (1000's per minute) for page headers and download web pages in much the same way WinHttp library does in a windows environment. So far I've come across libCurl which seems to do what I want...
Try libevent HTTP routines. You create an HTTP connection and provide a callback which is invoked when a response arrives (or timeout event fires). Updated: I built a distributed HTTP connection-throttling proxy and used both th e client and server portions within the same daemon, all on a single thread. It worked grea...
5,238,014
5,238,042
concatenating strings into array of char in c++(by using less strcat)
For example, I have a code like this. char NameTmp[] = "foo.txt"; char Name[] = "bar.txt" char cmd[80] = "./analyzeText "; strcat(cmd, Name); strcat(cmd, " "); strcat(cmd, NameTmp); strcat(cmd, " "); strcat(cmd, "8"); system(cmd); Basically, I am trying to call "./analyzeText bar.tx...
Use some strings: std::string NameTmp = "foo.txt"; std::string Name = "bar.txt"; std::string cmd = "./analyzeText " + Name + " " + NameTemp + " 8"; system(cmd.c_str()); It's slightly less efficient (more strings are created), but it's much simpler.
5,238,025
5,238,354
How to specify whether to take ownership of the marshalled string or not?
suppose I have x.dll in C++ which looks like this MYDLLEXPORT const char* f1() { return "Hello"; } MYDLLEXPORT const char* f2() { char* p = new char[20]; strcpy(p, "Hello"); return p; } Now, suppose I want to use this in C# [DllImport("x.dll")] public static extern string f1(); [DllImport("x.dll")] pu...
If you have any influence at all over the dll implementation, then I strongly suggest you simply don't do it like you showed in your example. Otherwise, please refine the question to mention that constraint. If you have to return a heap allocated string from the dll, then you should also provide a cleanup function (alw...
5,238,123
5,238,173
Why is this map<int, auto> not allowed?
I am trying to implement a heterogeneous map in C++. I know that this has been previously discussed before but I was wondering why the following is not allowed: map<int, auto> myMap; Is there anyway in which I could make insertion into a map simple without having to resort to (void*) pointers? I was thinking about eve...
auto does not mean "this can be any type". It is a special keyword that can only be used to declare variables, and its meaning is "the type of this variable is the same as the type of the expression used to initialize it". The type of an auto variable is as unchangeable as the type of any other declared variable; the o...
5,238,160
5,238,644
Boost python linking
I'm adding boost.python for my Game. I write wrappers for my classes to use them in scripts. The problem is linking that library to my app. I'm using cmake build system. Now I have a simple app with 1 file and makefile for it: PYTHON = /usr/include/python2.7 BOOST_INC = /usr/include BOOST_LIB = /usr/lib TARGET = main...
You are missing your include directory and libs for python in your CMakeList.txt. Use the PythonFindLibs macro or the same find_package strategy you used for Boost find_package(Boost COMPONENTS filesystem system date_time python REQUIRED) message("Include dirs of boost: " ${Boost_INCLUDE_DIRS} ) message("Libs of boost:...
5,238,196
5,238,706
Exposing Quantlib and another library to C# via SWIG
Compiling and linking Quantlib takes some time, as it is not a small project. I am building some additional functionality on top of Quantlib, and I want to keep this additional functionality in a separate project. Is there a way to easily expose two C++ projects into one library via SWIG? Because my project is quite sm...
I don't know Quantlib in particular, but generally, doing this with SWIG should be quite straightforward: the C# module of SWIG supports the dllimport option which allows you to specify the DLL referenced for the P/Invoke methods (refer to the C# section of the SWIG manual for details). Thus, you can just create a sepa...
5,238,319
5,238,747
how can I temporarily pause other threads using boost::thread?
I have a program with 2 threads (A and B). Is it possible to define a block of code in thread B, which once entered pauses thread A until the block has finished executing? I am using C++ and the library boost::thread 1.44 EDIT: The problem I had, which prevented me from just using a mutex was that I did not have access...
Other than the scoped_lock/mutex solution of Grammin you can use a condition variable (perhaps a more common idiom for your problem) or even a barrier.
5,238,437
5,238,990
Can a QPointer be the key to a std::map
According to SGI's doc on associative containers, "Since elements are stored according to their keys, it is essential that the key associated with each element is immutable". I sometimes use a pointer as a key to std::map, since, although the pointed object might be mutable, the pointer itself is constant. QPointer is ...
No, this is not safe, because QPointer<T> may change to NULL when a QObject is destroyed. (QPointer is similar to std::weak_ptr.) So this code would produce Undefined Behavior: class CopyableWidget : public QWidget { Q_OBJECT; public: CopyableWidget(Widget* parent = 0) : QWidget(parent) {} CopyableWidget(const ...
5,238,570
5,239,225
Dumping buffered data when memory limit is near
My application buffers data for likely requests in the background. Currently I limit the size of the buffer based on a command-line parameter, and begin dumping less-used data when we hit this limit. This is not ideal because it relies on the user to specify a performance-critical parameter. Is there a better way to ha...
Your best bet would likely be to monitor your applications working set/resident set size, and try to react when it doesn't grow after your allocations. Some pointers on what to look for: Windows: GetProcessMemoryInfo Linux: /proc/self/statm OS X: task_info() Windows also has GlobalMemoryStatusEx which gives you a nic...
5,238,630
5,238,958
Delay population of a sub menu in Windows and C++
I have an C++ MFC CMenu based context menu object that has several menu items and one menu item is a popup menu (ie has a sub menu). Populating the sub menu is a time intensive process so I don't want to actually populate it until the user clicks on it. How do I detect the display of the sub menu so I can only populate...
You want WM_INITMENUPOPUP.
5,238,682
5,238,724
How to create PNG images with Visual Studio C++ 2010?
IN: Visual Studio 2010 Ultimate, Windows 7 OUT: Some small ish PNG images that I will use as custom markers in Google Maps. Language: C++ (or, if I really have to, C#) Extra: I need to be able to plot the alpha channel (the transparency). I used PNGwriter library on a Linux machine and that didn't offer this feature. E...
Do you mean you want to convert from one file format to PNG using C++? Or that you want to render to an image and save the resulting image out as a PNG? Either way, maybe you should take a look at FreeImage http://freeimage.sourceforge.net/features.html which is an open source image parsing/writing library that support...
5,238,780
5,439,215
gSoap: how to gracefully shutdown the webservice application?
I'm using gSoap to write a webservice. It's running as a console application. In all gSoap examples I see, that requests are dispatched in infinite loop like for(;;;) even in multi-threaded version. But how can I make my webservice to terminate gracefully when, say, user presses space on the console? Preferably: s...
The section 7.2.4 How to Create a Multi-Threaded Stand-Alone Service in the documentation has example code for writing an accept loop. You need to write your own accept loop and add signal handling so it responds to Ctrl-C. stop accepting new connections: Leave the loop so you stop calling accept. Serve existing ones...
5,238,833
5,239,080
Boost library or equivalent implementation of C++0x atomic for Sutter's lock-free queue?
Herb Sutter's article on lock-free and concurrent queues has been mentioned quite a bit here in SO. However, I don't have a C++0x compiler...so I'm wondering if anyone has translated his code to use either some boost library or whatever to provide some "atomic" operation. I wouldn't mind, even, if anyone can provide a...
Intel's Thread Building Blocks has an atomic data structure. The Boost Thread library is also a good place to find various mutexes and condition variables.
5,238,925
5,239,339
Pool memory allocation in a priority queue
I am writing an event based simulator, in which each event calls a processing function (node) that can generate new events, and so on. A timestamp is associated to each events and they need to be processed in the order of increasing time (but the events are not necessarily created in that order). To this end, I use a s...
A quick and dirty example of an object pool EventPool.h #include <stack> class Event; class EventPool { public: explicit EventPool(const unsigned int initSize = 0); ~EventPool(); Event* getEvent(); void returnEvent(Event* e); private: std::stack<Event*> pool_; }; EventPool.cxx #include <Event.h> #inc...
5,238,932
5,239,052
Namespace without a name in C++
Possible Duplicate: Unnamed/anonymous namespaces vs. static functions I came across this code namespace ABC { namespace DEF { namespace { I expected the namespace should be followed by some name, but it's not the case with this code. Is this allowed in C++? What's the advantage for this unnamed namespace?
It's called an unnamed namespace / anonymous namespace. It's use is to make functions/objects/etc accessible only within that file. It's almost the same as static in C.
5,239,252
5,239,697
pstack in a shared library (c/c++). Corrupted shared library
How can I corrupt a shared library? I have a process that attaches to several shared libraries. One action, eg createObject1 works 99% but 1% creates a pstack. The problem is not easy to reproduce, it happens sometimes in real time. The shared library has an array of various Object1. Before writing the new Object1, we...
http://www.valgrind.org/ would be my suggestion.
5,239,570
5,239,945
finding max in bunch of arrays in C
I have couple of questions. I have a text file which contains these information x0,x1,y0,y1 142,310,0,959 299,467,0,959 456,639,0,959 628,796,0,959 First, I want to read the text file using fscanf and get only the numbers into 4 arrays, c1, c2, c3, and c4 by skipping the first line. So the final result will be c[1] =...
Although not satsifying your question directly, I have provided an example of reading points using a struct, std::istream and std::vector. These are preferred over fscanf and arrays. struct Point { unsigned int x; unsigned int y; friend std::istream& operator>>(std::istream& inp, Point& p); }; std::istream& op...
5,239,586
5,239,645
More asynchronous socket questions:
Initial questions here So I've been reading up on asynchronous sockets, and I have a couple more questions. Mostly concrete. 1: I can use a blocking socket with select() without repercussions, correct? 2: When I use FD_SET() I'm appending the current fd_set* not changing it, correct? 3: When using FD_CLR(), I can sim...
Yes Unclear? FD_SET inserts a socket into the set. If the socket is already there, nothing changes. FD_CLR removes a socket from the set, if the socket isn't there nothing's changed You could keep a parallel set<> of sockets, then get the highest value from there. Or you could just set a bool saying "rescan for nfd be...
5,239,681
5,239,816
Incorrect values from operator casting with reference
I'm trying to make a float wrapper (which will also do some magic stuff in the constructor). However I find myself with quite odd errors. class Foo { public: Wrapper(); operator const float& () const { return m_bar; } operator float& () { return m_bar; } const float& Get() const { return m_bar; } float...
As you stated in your comment, you're passing the class to a vararg function (I guess it is vararg by the formating). The vararg passing does not work because it passes the address of the class and not a cast type (it doesn't know what it should cast it to when passing). Using Get or an explicit cast is the only soluti...
5,239,689
5,239,756
Reading data from file into array
I am trying to read specific data from a file into two 2D arrays. The first line of data defines the size of each array so when I fill the first Array i need to skip that line. After skipping the first line, the first array fills with data from the file until the 7th line in the file. The second array is filled with th...
Your while loops iterate until the end of file, you don't need them. while (inFile >> seat) // This reads until the end of the plane. Use instead (without the while): for (int a = 0; a < FC_Row; a++) // Read this amount of rows. for (int b = 0; b < FC_Col; b++) // Read this amount of columns. ...
5,239,882
5,239,897
What is the need to specify "std" prefix?
I'm a beginner in programming and I often see many programs using the prefix std if they are using any std functions like std::cout, std::cin, etc. I was wondering what is it's purpose ? Is it just a way of good programming or is there more to it ? Does it make any difference for the compiler or is it readability or wh...
The STL types and functions are defined in the namespace named std. The std:: prefix is used to use the types without fully including the std namespace. Option 1 (use the prefix) #include <iostream> void Example() { std::cout << "Hello World" << std::endl; } Option #2 (use the namespace) #include <iostream> usi...
5,239,943
5,239,972
C++ cyclical header dependency
I had a question: Supposed I have a header/source file set and a header set as follows" BaseCharacter.h and BaseCharacter.cpp and EventTypes.h BaseCharacter.h makes use of structs and typedefs defined in EventTypes.h, but EventTypes.h has to be aware of the BaseCharacter class defined in BaseCharacter.h. This creates a...
Forward declaration. In EventTypes.h, remove the include and add: class BaseCharacter; Note that you can only use references and pointers to BaseCharacter within EventTypes.h, you cannot e.g. have a struct with a BaseCharacter myChar; member variable.
5,240,162
5,240,194
Safe string copy in C/C++
I wrote this string copy routine for C strings. It is supposed to behave like strlcpy, that is - null terminate the destination if size > 0, and return the length of the source string. However I also want the function to fail if either the source or destination pointer is null, and somehow notify this to the caller. Bu...
In C++, you can throw an exception.
5,240,267
5,240,331
using c++ standard library algorithms with valarray
I'm trying to avoid reimplementing my own clumsy versions of standard algorithms, and thus am playing with the standard library versions. Since I'm no expert in C++, I proceed with caution and full debug options switched on. Specifically, I'm using a binary search on a valarray container. The following code block seem...
You're using an int to index into the valarray. That's valid for the example, but not in general. Use an std::size_t to index into a valarray. (The same goes for std::vector and ordinary arrays.) The difference between two pointers to any type is of an unspecified integer type, likely int or long and always small enou...
5,240,393
5,240,397
Do I need to clean the objects in the deque in the destructor?
my deque contains object, NOT pointer. such as: class MyObject // no pointer inside the object, all simple type/prmitive { string name; string value; } MyObject object1, object2; m_deq.push_back(object1); m_deq.push_back(object2); I know if it's pointer, I have to clean it in desconstructor. My ...
No, you do not have to clear the std::deque if you only stored value objects in there. The std::deque destructor will call the destructor for each object it contains.
5,240,448
5,240,515
How can I compare the first N elements of a std::set?
How can I compare first "n" elements of two sets are equal or not? My following program doesn't work, why? #include <iostream> #include <iterator> #include <set> #include<algorithm> using namespace std; int main () { int n = 2; int myints1[] = {75,23,65,42,13}; int myints2[] = {70,23,65,42,13}; set<int> myset1...
std::set iterators are bidirectional, not random-access. You can't say begin() + n with them. Instead you might want to use std::advance. std::set<int>::iterator it(myset1.begin()); std::advance(it,n); if(std::equal(myset1.begin(),it,myset2.begin())) std::copy(myset1.begin(),it,ostream_iterator<int>(cout," "));
5,240,453
5,240,579
C++ SDL collision if blitted to specific surface
I have a simple game that includes 2 surfaces that I blit sprites onto. One I blit little squares which your character is supposed to jump over, the second is the surface I blit my characters sprite onto. I want to make a collision detection where it only detects objects that are on the surface my character is NOT on i...
One approach that comes to mind is the following: First, seperate the objects per layer, say std::vector<MyObjects*> CharLayerObjects; (std::vector for when you have more objects on that plane, like environment stuff) and std::vector<MyObjects*> CollisionLayerObjects;. Then just test the character against the objects i...
5,240,469
5,240,955
Templated assignment operator question
I want to make sure that *this != &rhs in the assignment operator. But it won't compile. Any suggestions? template <typename T> class A { public: A() { std::cout << "Default Constructor" << std::endl; } A(const T& t) : m_t(t) { std::cout << "Templated Constructor" << std::endl; ...
I personally think the following is the most elegant solution. I am not sure why I didn't get that in the first place - I initially was using the bloodshed c++ compiler and it seemed to fail - but g++ this is cleanest? If people disagree with me, I'll remove my answer and give it to someone else. Note that the A* actu...
5,240,638
5,240,695
Creating C# to C++ bridge: Why do I get a AccessViolationException when calling DLL?
I'm exploring the idea of building a bridge between a DLL plugin for a 3rd party app and a C# app. I'm writing both the plugin DLL and the C# application. The plugin will be loaded into the 3rd party app and then I want to use call the plugin from C# to indirectly get data from the 3rd party app. I am able to success...
From your question it seems that this is the scenario: ProcessA (3rd party App) --> loads X.DLL --> initializes the plugin --> does other stuff. ProcessB (Your C# App) --> loads X.DLL --> calls GetData(); Does X.DLL loaded in ProcessA have any mechanism to talk to X.DLL loaded in ProcessB? if not then this approach i...
5,240,820
7,137,378
How does Visual Studio 2010 hosts MSBuild for C++ projects?
I have a solution with several C++ projects. For some of the projects I need some custom file copy, e.g. to copy some configuration files to the output directory or to copy the output files of one project to a specific folder after build. In some cases I don't want or cannot add these files to the projects directly thr...
See this suggestion on Microsoft Connect. Basically you need to set DisableFastUpToDateCheck property to true to disable the fast-up-to-date check. Just add to your vcxproj or your targets file: <PropertyGroup> <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck> </PropertyGroup>
5,240,827
5,240,921
install RQuantLib on Microsoft Windows
I need to install the R package RQuantLib on a Microsoft Windows machine. There is no binary for this package so I downloaded the tar source. I opened it and it contains the QuantLib C++ libraries. So I need to compile the package. I don't want to install Visual Studio and I use eclipse IDE. Can I use the compiler cyg...
begin shameless plug I wrote about how to build RQuantLib on Windows on my blog. I didn't try it with Cygwin, but you can do it with MinGW. end shameless plug
5,240,958
5,240,977
About a vector defined in a function
Suppose a std::vector is defined in a function (i.e., on stack) and the vector is re-allocated (like by inserting data). Will any part of the vector be in heap? if yes, will it leave any garbage in heap when done executing the function? Thanks.
Will any part of the vector be in heap? Yes: all of the elements in a std::vector are stored in a heap-allocated array. Will it leave any garbage in heap when done executing the function? No. The std::vector container, like all of the Standard Library containers, is responsible for cleaning up any objects that i...
5,240,970
5,241,041
side effects of virtual public class in C++
Virtual Public Class is used for a class to ensure that an object of a class inherits only one subobject. class L { /* ... */ }; // indirect base class class B1 : virtual public L { /* ... */ }; class B2 : virtual public L { /* ... */ }; class D : public B1, public B2 { /* ... */ }; // valid Do we have side effect wh...
It's just as safe to make the parent class virtual "just in case." The standard doesn't specify how virtual inheritance will be implemented, but there will probably be a slight performance hit. Unless you're writing something performance-critical, you shouldn't need to worry about it.
5,240,994
5,241,083
defining operator [ ] for both reading and writing
In the book of "The C++ Programming Language", the author gave the following example along with several statements: Defining an operator, such as [], to be used for both reading and writing is difficult where it is not acceptable simply to return a reference and let the user decide what to do with it. Cref, is to help...
If you don't define a class Cref that solves this issue, then you have to do what std::map does: template class <K,V> class map{ V& operator[](K const & key); } This returns a reference, which must be backed by a valid memory location, and therefore std::map<string,string> m; m["foo"]; assert(m.find("foo") != m.end...
5,240,996
5,241,007
duplicating the same method with const?
In C++, I see this code. public: Ports& GetPorts(); const Ports& GetPorts() const; Why is it necessary to have another method with const? How can a compiler decide which method is called?
If you call x.GetPorts() and x is a non-const object, the first version will be called. If x is a const object, on the other hand, the second version will be called. That kind of code is saying "if the object is modifiable, allow the result of GetPorts() to be modified; if the object is const, don't allow the result ...
5,241,042
5,241,094
Operator Overloading in C++
So I'm in a basic programming II class. We have to create a program that makes 4 different functions that will change the way an operator works. I've looked up multiple examples and sets of text that display how to do this, but I cannot make which way of what any of the code means. To me something like this should work...
All the examples create their own data type since this is one of the rules for operator overloading: An overloaded operator must work on at least one user-defined type. Even if you could overload ++ for integers, the compiler wouldn't know which one to use -- your version or the regular version; it would be ambiguous....
5,241,713
5,245,143
How to call class member functions with non-class function pointer?
So it seems ANTLR3C uses function pointers to allow users to override them if we want to write our own functions. I need to override the error reporting function: Pointer void(*displayRecognitionError)(struct ANTLR3_BASE_RECOGNIZER_struct * recognizer, pANTLR3_UINT8 * tokenNames); Func...
Generally, it is not possible to simply assign address of member non-static function to pointer to non-class function. You can create non-class function which will call the proper member function of the lexerData class. The problem is that this non-class function must be able to reference the lexerData object in some w...
5,241,771
5,318,484
In Gecko 2.0 (Firefox 4) how do you interact with (send windows messages to) a tab that is not currently focused?
Say your automating Firefox, and you want to do crazy things like, emulating a raw keystroke typing 'return' but to a tab window that is not currently in focus/active/ontop. Using ideas in https://developer.mozilla.org/en/Code_snippets/Finding_Window_Handles you can get a hwnd, and then do something like ::PostMessage...
If you want to interact with Firefox out-of-process then the only way I know of that's supported are the accessibility APIs. If you're writing an extension then you can simply create a keypress event with the relevant key or character code and dispatch it to the appropriate element.
5,241,824
5,241,844
C++ -- Get internal pointer to a vector
I use the following method to get an allocated memory space without worrying about how to reclaim the allocated resource. #include <vector> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { vector<int> vecInts; for(int iInd=0; iInd<10; i++) vecInts.push_back(iInd); int* pInt = &vecInts...
Yes, that's fine given the precautions you mention (and other obvious ones, like not using a pointer into a vector that's gone out of scope etc.). The pointer will be valid and invalidated in the exact same way that an iterator into the container would be.
5,241,840
5,242,410
C++ -- Why not return Array1D&?
template<class T> class Array2D { public: class Array1D { public: T& operator[](int index); const T& operator[](int index) const; ... }; Array1D operator[](int index); // why not return Array1D& const Array1D operator[](int index) const; // why not return Array1D& ... }; The above code is used...
At a guess, it looks pretty similar to a 3D matrix class I posted in a previous answer. If so, the Array1D is just a proxy object -- just a temporary holder for a position in the array/matrix to be used by the next level's operator[] to get the location of an element. In this case, 1) the proxy object is lightweight an...
5,242,051
5,242,486
Cython - implementing callbacks
I have been working with Cython in an attempt to interface with a library written in c++. So far things are going pretty good, and I can effectively use MOST functions within the library. My only problem lies within implementing callbacks. The library has 4 function definitions that look a little something like this: t...
If you can modify the library to define: typedef void (*Function1)(const uint16_t *data, unsigned width, unsigned height, void *user_data); void SetCallBack(Function1, void*); instead, I fear you are out of luck. If you have the void*, than you define a function tha...
5,242,161
5,243,038
How to select a file in QTreeView for a QFileSystemModel by path?
I have a tree view displaying a file system model. I want, upon it starting, make a certain file (specifically, current directory) already selected, so that user will not be forced to go all the way down the file system tree to find it. However, neither QTreeView, nor QFileSystemModel don't have any functions to find t...
tree->setCurrentIndex(fsModel->index(QDir::currentPath())); // or any path Depending on the selection mode the item may or may not be selected. Hope this helps
5,242,170
6,247,122
Does Returning Structure with Pointers in Interop Take a lot of Memory Space?
I have the following structure in c++: #define CGAPI_Exports_Attr __declspec(dllimport) extern "C"CGAPI_Exports_Attr struct PointCg { double x; double y; }; extern "C"CGAPI_Exports_Attr struct PolylineCg { int num_points; PointCg *points; }; And the interop method goes like this: e...
I'll answer assuming x64. Theoretically, it doesn't matter. If you return the PolylineCg, the size of the struct is greater than 64-bits. This means the value will not fit in the return register (64-bit RAX register), and it cannot be returned by value. This means enough space needs to be allocated for the return value...
5,242,303
5,242,903
C++ TCP server Class Design
I am developing TCP server in C++(win32/linux) which cater multiple client.The server is for Video Streaming.Client request video to server and Server get it from Gateway connected with camera. I am stuck up in the class Design.I found three classes by Peer Session and ConnectionMgr. So here ConnectionMgr is respons...
Looking at the problem space from scratch: there's some state associated with each client that connects - you seem to split this between Peer and Session and I see no real value in that if they're 1:1 - can omit such trivia from the high-level design stage. "what info Peer and session need to have": socket descriptor...
5,242,398
5,242,504
linux C++ thread in class
Hi i want to do the class with method which will start in separate thread after creating class. That how i do that: class Devemu { int VarInc; void Increm() { for(;;) { if (VarInc > 532) VarInc = 0; else VarInc++; } } public: static void* IncWrapper(void* thisPtr) { ((Devemu*) thisPtr)->In...
Yes, you can put it in the constructor if you like : class Devemu { int VarInc; pthread_t thread_id; void Increm() { for(;;) { if (VarInc > 532) VarInc = 0; else VarInc++; } } public: static void* IncWrapper(void* thisPtr) { ((Devemu*) thisPtr)->Increm(); return NULL; } Devemu() { ...
5,242,465
5,242,662
Is there a way to break this dependency for unit testing?
My class A is dependent to class B. Here is the code //declaration class A { public: A(B *b); ~A(); void m1(); private: B *ptr_b; }; //implementation A::A(B *b) { ptr_b = b; } A::~A() { delete ptr_b; } void A::m1() { ptr_b->m2(); } I want to break this dependency(for unit testing) with t...
First, it is bad design having a delete ptr_b; in the destructor of class A since there is no new B() in the constructor of A. That means every time an instance of A is created, you are transfering ownership of the B object to A, leaving you with the potential risk of a duplicate delete for someone using A who does not...
5,242,589
5,242,702
Would float point format be affected by big-endian and little endian?
I know the integer format would be different between big-endian machine and little-endian machine, is it the same for float point format (IEEE 754)?
The IEEE754 specification for floating point numbers simply doesn't cover the endianness problem. Floating point numbers therefore may use different representations on different machines and, in theory, it's even possible that for two processors integer endianness is the same and floating point is different or vice-ver...
5,242,720
5,244,570
VirtualAlloc C++ , injected dll, asm
I want to reserve space for my codecave in application. I use VirtualAlloc function to reserve this space. I have X questions. What parameters (sllocation type and protection) should I use to allocate memory for code-cave? As return value I get address of my codecave. In other part of the program I want to JMP to that...
Subtracting the address of your jump target from the address of the instruction after the jump will give you the jump offset.
5,242,874
5,242,901
how to show tooltip text as table for TreeView in MFC?
I want to implement a functionality in which when i click F2 on any Treeview item, it should display the Tooltip for that item (This is possible generally).But in Tooltip the text should be in tabular format and also should allow me to edit the value of the item text. Please let me know if anyone has implemented this. ...
Tabular format is easy: tooltips accept html-formatted text. But I don't think you can make it editable.
5,242,925
5,245,149
Allocation in making copy of std::string
Which implementation do you think is better? std::string ToUpper( const std::string& source ) { std::string result; result.resize( source.length() ); std::transform( source.begin(), source.end(), result.begin(), std::ptr_fun<int, int>( std::toupper ) ); return result; } and... std::string ToUp...
A straight-forward loop would be the simplest: std::string toUpper(std::string s) { for(size_t i = 0, j = s.size(); i != j; ++i) s[i] = toupper(s[i]); return s; } No need to use standard algorithms and functors here just for the sake of using them. [Update] You mentioned you can't use boost. I benchmar...
5,243,360
5,243,448
how to free memory for structure variable
typdef struct _structname { int x; string y; } structure_name; structure_name variable; Now I access variable.x and y. After using it how can i deallocate or free the memory used by variable? Actually the memory is getting allocated when i am doing variable.y="sample string".So the = operator allocate...
Memory needs to be deallocated only when it's dynamically allocated. Dynamic allocation is done using either new or malloc, and deallocation is done using delete or free respectively. If your program doesn't use new or malloc anywhere, then you don't need to use delete or malloc either. Note there will be as many numb...
5,243,761
5,243,852
C++ Design question: Passing functions via templates?
Thanks in advance for reading. This is a picky design question in that I have an adequate solution, but question if there isn't a better way via templates, which I'm not very experienced with. I have a series of types of data tables (derived from abstract class DataTable) which I need to store. I wrote a "DataTableIn...
In general, this could be done by using the strategy pattern. This can be implemented using simple composition, so there are no templates needed. However, you will still have to define a special strategy for each of the different table types. This will require subclassing: class LoadTableStrategy { public: virtual ...
5,243,988
5,244,116
about posix ftime in C++
I am looking in to the code about getting utc time. static const long long SECSEPOCHS = 11644473600ll; static const long long SECSto100nanosecs = 10000000ll; static const long long MSECSto100nanosecs = 10000ll; longlong mytime; struct timeb now; ftime(&now); mytime = now.time; mytime += SECSEPOCHS mytime *= SECSto10...
Epoch refers to the reference time that is used to calculate further events. For example if I decide that 1st Jan 2000 is the reference time (EPOCH) so whenever we I say "1 year past". It will mean that it is 1st Jan 2001 as our reference was year 2000. Windows NT time is specified as the number of 100 nanosecond inte...
5,244,147
5,244,244
Regexp: group for every found item (PCRE)
I am using PCRE with C++ (Borland) and want to get all matches of a group. ^(\w+\s)(\w+\s)*(\w+)$ input 1: first second third results in 3 groups (first, second and third) input 2:first second second third results in 3 groups (first, second and third) too, but I need 4 groups. The second word is optinal and occurs 0 -...
I think your best shot is to match : ^(\w+\s)((?:\w+\s)*)(\w+)$ and then match the inside x words by hand, looking for \s with string comparison.
5,244,509
5,244,605
no debugging symbols found when using gdb
GNU gdb Fedora (6.8-37.el5) Kernal 2.6.18-164.el5 I am trying to debug my application. However, everytime I pass the binary to the gdb it says: (no debugging symbols found) Here is the file output of the binary, and as you can see it is not stripped: vid: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), f...
Some Linux distributions don't use the gdb style debugging symbols. (IIRC they prefer dwarf2.) In general, gcc and gdb will be in sync as to what kind of debugging symbols they use, and forcing a particular style will just cause problems; unless you know that you need something else, use just -g.
5,244,532
5,244,594
srand seed consistency between physical machines
I'm not quite sure how to phrase this question, but I couldn't find any others like it. Say I have this code: srand(1); srand(SOME_DEFINED_CONST_INT); If I run this executable on a number of different physical machines, is the sequence of rand() guaranteed to be consistent between them? i.e. if I get 1, 4, 6, 3, 4 on ...
No, the standard guarantees no such thing. However, the logic of generating the random numbers is inside the C standard library. So if you build the application with the same version of the library, the sequence should be the same. The second part of my answer is just a guess, but the standard definitely doesn't give a...
5,245,039
5,245,296
My minidumps are getting too big to be loaded by Visual Studio, how do I solve this?
When my application crashes it generates a minidump to allow post mortem debugging. I use the options MiniDumpWithIndirectlyReferencedMemory and MiniDumpWithPrivateReadWriteMemory. It all worked great until recently when the dumpfiles started getting over 500MB in size. Visual Studio throws the following error at me th...
You could try using WinDbg from the Debugging Tools for Windows package, to see if it does not manage the memory better than Visual Studio. However I would suggest trying 64-bit OS, even though you do not want to do it. In these days and times you should provide your application also as native 64 bit Windows applicatio...
5,245,072
5,245,405
Pass and call a member function (boost::bind / boost::function?)
I have a probably embarassingly simple problem: pass and call a member function in a class. I know I want to use BOOST bind (and or function), but I haven't really grasped the concept to it yet. The following code compiles and executes with problem. But when I want to change the "f3" function to a non-static class func...
boost::function is a template class, that takes a function signature. You can also use function0, function1, etc. boost::function< void(uint32_t) > defines a "callable" that looks like a function, i.e. it takes a single parameter of type uint32_t and returns void. The appropriate numbered template is function1< void, ...
5,245,172
5,245,282
Resolving operator ambiguity
I have the following map type... std::map<D3DXCOLOR, ID3DXMesh*> During compilation, xfunctional complains that it cannot resolve an ambiguity regarding the key type; error C2593: 'operator <' is ambiguous The candidate operators detected by the compiler are as follows; built-in C++ operator<(DWORD, DWORD) built-in ...
You have three options. Supposing for example that you want them compared as colorvalues: 1) Define operator<: bool operator<(const D3DXCOLOR &lhs, const D3DXCOLOR &rhs) { return static_cast<D3DCOLORVALUE>(lhs) < static_cast<D3DCOLORVALUE>(rhs); } 2) Specialize std::less: namespace std { template <> struct...
5,245,204
5,266,997
C/C++ mixed programming: gdb segmentation fault frequently
I always meet gdb crash when I try to print a definitely valid structure/variable. And it often crash if I tried to call another function in gdb. I found this could happen only if the code is C/C++ mixed. For example, %> p anotherFunction() Segmentation fault Here is a small example which is my typical scenario: exam...
Any crash in GDB is a bug in GDB. Please file the bugs in GDB bugzilla. If multiple versions of GDB crash on your example, the problem may be with your compiler (but even then GDB should not crash).
5,245,336
5,272,625
C++ linking to python 3.2 x64 application unable to load
This is I guess a question in a few parts. I'm working through the documentation on embedding the python interpreter. I've got everything compiling and linking wonderfully, only the application crashes when I run it ( to be specific its unable to load, so it hasn't even begun running). I'm running windows 7 profession...
If the python3.dll is definitely 64bit and your application is definitely 32bit, then this will not work. You can't link to 64bit dlls from 32bit applications. Pointers just won't be able to work between the two models.
5,245,374
5,245,424
Why does this code `misbehave`?
#include <iostream> using namespace std; struct X { int i_Val; X(int iVal) :i_Val(iVal) { } X& operator++() { cout << "X::operator++()" << endl; ++i_Val; return *this; } operator int() const { return i_Val; } }; const X operator+(con...
This is not undefined behaviour or a dupe of some i++ = ++i misery, because an overloaded operator is a function call and an implicit sequence point is introduced. However, it's my understanding that the order of evaluation in this context is unspecified and the compiler is free to re-order this however it likes.