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,708,440
4,708,598
How do you set desktop icon to large size in c++?
How to set desktop icon on larg size from c++? Windows 7 professional is os & use dev c++.
You can do this by simulating the control key and mouse wheel combination. You can read more about this method in this article from The Code Project: Programmatically resize Desktop icons to a small list in Windows Vista and Windows 7 Resize the icons to be smaller. We call this repeatedly until we get the desire...
4,708,444
4,708,477
Is there a good way to convert from unsigned char* to char*?
I've been reading a lot those days about reinterpret_cast<> and how on should use it (and avoid it on most cases). While I understand that using reinterpret_cast<> to cast from, say unsigned char* to char* is implementation defined (and thus non-portable) it seems to be no other way for efficiently convert one to the o...
Portable is an in-practice matter. As such, reinterpret_cast for the specific usage of converting between char* and unsigned char* is portable. But still I'd wrap this usage in a pair of functions instead of doing the reinterpret_cast directly each place. Don't go overboard introducing inefficiencies when using a langu...
4,708,480
4,708,506
A cleaner code alternative to polymorphism
Building a GUI system and I have a few classes for different GUI components that derive from a base "GUIcontrol" class. What I want is to have just one function to return any type of component but be able to work with the functions specific to that component type (functions of the derived class). I noticed that the pol...
The base class should only contain methods for functionality common to all controls. If you're going to use functionality that only makes sense for one type of control, you should be checking that the control is of the correct type anyway, and can then cast it to that type.
4,708,482
4,708,502
Start with some C++ framework or python
I am thinking about to learn new language or framework. Now I deal with C# and WPF, WCF, Winforms. I have some free time so I would like get new skills. But I have dilema, start with some C++ framework (such as Platinum, Reason, Evocosm, ACF) or try Python / python framework. I you are on my place which possibility you...
Personally I prefer Python, but profesionally, that is if you want a good job C++ is a better choice.
4,708,538
4,708,816
GDB doesn't return after segmentation fault
I have some code, that I'm currently porting from OS X to Linux (console tool). Somewhere in this code, I get a segmentation fault. The problem is, that if I run the program without GDB, I clearly see the segmentation fault, and the program is killed. But when I'm running GDB it just halts, and GDB never returns to the...
The behaviour you describe is not typical - I suspect the stack may have been trashed. Try sending various signals directly via the 'kill' command. Might be worth you running a test program in gdb with an abort() in it so that you can learn what the expected behaviour is for gdb.
4,708,723
4,822,820
Stringray Grid transparent background
In Stringray grid, there is the ability to use a transparent background which allows the background of the dialog to be shown through the grid. In the documentation it states: But be careful; you should disable scrolling or you have to redraw the grid each time it is scrolled (by overriding DoScroll). I have a scroll...
Yes you have to redraw the grid by overriding DoScroll because it is no longer using ScrollWindow to scroll contents because the background is transparent. However you now have artifacts of the grid over your background. This is because the background behind the grid is not getting redrawn. Do you have clipchildren set...
4,708,729
4,709,083
Calling a custom COM interface from a ATL project
How do I call a COM interface from an ATL project? I was following the example at http://www.codeproject.com/KB/COM/comintro.aspx but they use the IActiveDesktop class which is defined in wininet.h. How do I call a custom component where I do not have the interface definition. How do i generate it? In a MFC project I ...
If you are wanting to call a third-party COM component, you do not need to interface definition file (.idl) for that component. Use the CComPtr ATL class, which encapsulates the typical things that use do with any COM object, such as CoCreateInstance and QueryInterface. there is also a template specialization for IDisp...
4,708,828
4,708,846
C++ Abstract type initialisation
I have a class Interface, that has pure virtual methods. In another class I have a nested type that inherits from Interface and makes it non-abstract. I use Interface as a type and use the function to initialise the type, but I am getting, cannot compile because of abstract type. Interface: struct Interface { virtua...
You use abstract classes as pointer and references, so you'd do class AnotherClass { struct DeriveInterface : public Interface { void something() {} } DeriveInterface m_intf; Interface &interface() const { return m_intf; } } struct Usage : public AnotherClass { void ca...
4,708,896
4,708,911
How to install a mod for a videogame?
I have created a mod for Mafia 3 ( the videogame ). So I need to know where is the folder of this game on the pc that not is always the same. How can I do ?
Have your installer ask the user to specify where the game directory is, pretty common way to solve this problem
4,708,931
4,708,948
Typeid behavior in c++
Can someone explain to me why this code prints Base , Derived but if i omit the f function from Base prints Base , Base ? #include <iostream> #include <cstdio> using namespace std; class Base; void testClassType (Base& b); class Base { virtual void f(){}; }; class Derived :public Base { }; int main () { Base b; ...
By definition of typeid, it returns the dynamic type of the expression for polymorphic types and static type of the expressions for non-polymorphic types. A polymorphic type is a class type that has at least one virtual function. In your case, when you call testClassType(d), expression b inside testClassType function h...
4,709,091
4,709,177
How can I create a window that displays glpoints using freeglut?
My question is quite simple, I need to initialize a window and use it to display pixels moving around and touching each other (I'm doing a DLA application). I need this to be done purely in GLUT as it needs to be cross platform. I'm not going to be displaying any 3D objects btw. Oh also I'm programming it in c++
Both any edition of the Red Book, the Superbible (4th ed. or older), OpenGL-centric textbooks (like Hill, et. al.), and every outdated tutorial (particularly NeHe) will cover all of this, if the GLUT manual is inadequate.
4,709,106
4,709,123
C++: static function member shared between threads, can block all?
I have a class, which has static function defined to work with C-style extern C { static void callback(foo bar) { } }. // static is defined in header. Three objects (each in separate pthread) are instantiated from this class, each of them has own loop (in class constructor), which can receive the callback. The pointer ...
If the callback function exists only once, then any thread attempting to callback will also block. This would give me an undesired bug, circa is interesting to ask: can anything in C++ become acting this way? Maybe, due to extern { } or some pointer usage? No and yes. callback is a simple function. It can be (in prin...
4,709,127
4,709,140
C++: gcc can't find static member when linking
I get the error: file.cpp:20: undefined reference to `MyClass::arr' At this line, I have: #include "MyClass.hpp" extern "C" { void MyClass::func() { arr = 0; } At header: class MyClass { public: static int arr; static void func(); } P.S. gcc (4.x) is called with: -Xlinker -zmuldefs to avoid multiple d...
This makes no sense : #include <MyClass.hpp> extern "C" { void MyClass::func() { arr = 0; } write #include <MyClass.hpp> int MyClass::arr = 0; // needs to be instantiated to satisfy linker. void MyClass::func() { arr = 0; }
4,709,244
5,266,479
Passing char variables to a type string function
I have the user enter a keyword which is broken up and put into a five by five array, then another function called "getletter" which fills up the rest of the spaces in the array in alphabetical order excluding those letters already included in the keyword. When I try to pass the values of the keyword to the getletter f...
I just set a variable that increases by one each time the loop runs through.
4,709,434
4,709,440
Making a multicolored TextBox?
I noticed that Windows's RichTextBox supports making the selected text any color. I'm trying to get a better understanding of how it might be doing this at a low level. Could it be storing each char's color, or might there be a better way (since removal and random insertion must be considered. Thanks
It stores the text in the RTF format.
4,709,453
4,714,836
Using Windows SDK 7.1 inside Qt Creator
I have a personal project I'm working on that requires Microsoft SAPI5 -- text to speech and Speech Recognition. I have already built out a lot of the application, but I've decided to switch and try to learn the Qt Framework, as it will make a lot of things much simpler. The project won't build as it can't find the hea...
After many hours this morning, I've managed to resolve my problem. Rather than using Qt Creator, I've decided to use Visual Studio 2010 + Qt 4.7.1. I've managed to implement this solution successfully, and have my project off the ground and running now. I recommend this approach for anyone trying to use the Windows SDK...
4,709,466
4,709,527
Specify a base classes template parameters while instantiating a derived class?
I have no idea if the title makes any sense but I can't find the right words to descibe my "problem" in one line. Anyway, here is my problem. There is an interface for a search: template <typename InputType, typename ResultType> class Search { public: virtual void search (InputType) = 0; virtual void getResult(...
Is there a better way to accomplish this? Yes, that design is slightly better, since that's using static-dispatching while calling GetValue() (I'm assuming that dynamic_cast is typo, you actually wanted to type static_cast in Base::GetValue()). In that design, Base::GetValue() is not virtual, yet it is able to call ...
4,709,475
4,711,143
question in MFC when drawing
i want to move a picture which was drawed by me and rub the original.how can i do?
The easiest solution for this is to keep the original picture in a memory DC. Draw the image to it, then BitBlt it to the screen. When you want to move it, erase your window and BitBlt it again - now at the new location.
4,709,531
4,709,541
Difference between storing values in character pointer with malloc and without
I have a character pointer like this char *ptr; I can allocate values to it like this *ptr='a'; *(ptr+1)='b'; Now when I can do this, why should I use an malloc? Am I just lucky that this pointer is not referencing an address that is being used by a process? Or are there chances that my data will be corrupted b...
Am I just lucky that this pointer is not referencing an address that is being used by a process? No, you're not lucky. If you were lucky, the program would crash so you know you have a problem. As written, your code is Undefined Behavior. You are writing data through a pointer to unallocated memory. § 6.5.6/8...
4,709,727
4,713,554
Is this code well-defined?
This code is taken from a discussion going on here. someInstance.Fun(++k).Gun(10).Sun(k).Tun(); Is this code well-defined? Is ++k in Fun() evaluated before k in Sun()? What if k is user-defined type, not built-in type? And in what ways the above function calls order is different from this: eat(++k);drink(10);sleep(k);...
This depends on how Sun is defined. The following is well-defined struct A { A &Fun(int); A &Gun(int); A &Sun(int&); A &Tun(); }; void g() { A someInstance; int k = 0; someInstance.Fun(++k).Gun(10).Sun(k).Tun(); } If you change the parameter type of Sun to int, it becomes undefined. Let's draw a tree of...
4,710,037
5,280,573
SWIG, boost shared pointers and inheritance
I'm having trouble with SWIG, shared pointers, and inheritance. I am creating various c++ classes which inherit from one another, using Boost shared pointers to refer to them, and then wrapping these shared pointers with SWIG to create the python classes. My problem is the following: B is a subclass of A sA is a share...
The following change appears to solve the problem. In swig_shared_ptr.i the two lines: %template(base_sptr) boost::shared_ptr<Base>; %template(derived_sptr) boost::shared_ptr<Derived>; are moved so that they are above the line %include <swig_shared_ptr.h> and are then replaced (in SWIG 1.3) by: SWIG_SHARED_PTR(Base, ...
4,710,454
4,710,472
Write the prototype for a function that takes an array of exactly 16 integers
One of the interview questions asked me to "write the prototype for a C function that takes an array of exactly 16 integers" and I was wondering what it could be? Maybe a function declaration like this: void foo(int a[], int len); Or something else? And what about if the language was C++ instead?
In C, this requires a pointer to an array of 16 integers: void special_case(int (*array)[16]); It would be called with: int array[16]; special_case(&array); In C++, you can use a reference to an array, too, as shown in Nawaz's answer. (The question asks for C in the title, and originally only mentioned C++ in the ta...
4,710,478
7,349,449
Application launched using CreateProcess in windows CE doesnt show up in task manager as application
I launch an application in windows CE 3.0 from a C++ dll using the CreateProcess() call. The application that is launched runs as per requirement. But this application is not listed in the task manager as an application. It is only seen when the settings of task manager is changed to show all processes. How can i make...
To appear in the windows CE task manager the application must have a visible window. I use CreateProcess() to launch my C# app and it does appear in the task manager (I'm using windows CE 6.0): STARTUPINFOW siStartupInfo; PROCESS_INFORMATION piProcessInfo; memset(&siStartupInfo, 0, sizeof(siStartupInfo)); ...
4,710,533
4,710,550
Safe C structs serialization for sending over networks? - C++
How would someone go about serializing C-style structs independent of the CPU endianness? I've searched for solutions, but I was hoping for a more general solution to the problem rather than changing the byte-order of each field in the struct.
There's no general solution to this problem within the language (or common system libraries). (There might be scripts/tools that could autogen the read/write code for you, or libraries that could add a sort of "reflection" to your structs, but I don't have references for you.) Bonus info that should be in any good ans...
4,710,618
4,710,715
LOBYTE(nValue) and LOBYTE(LOWORD(nValue)) Difference?
What is the difference between the 2 statements? Here assume nValue is an integer of 4 bytes. My belief is that both are the same.
I would say they both produce exactly the same result. BYTE and WORD are both unsigned (assuming standard Windows definitions). So if nValue is signed or unsigned, it shouldn't make any difference. In all cases, you should end up with the lowest 8 bits of nValue.
4,710,824
4,710,846
[Word Game]Quiddler Solver Algorithm
Quiddler Solver I have a card game called Quiddler that I'm trying to write an algorithm to solve, but when I try and solve it linearly its very slow and inefficient. The Game (Step by step): Each player is dealt a number of cards between 3 and 10, each card has either one or two letters on it. The player then tries t...
You can try storing the word list as a directed acyclic word graph (DAWG) or a trie for fast lookups. Place the first letter and use the DAWG/trie to find out all the possibilities for the second letter, and so on. Use backtracking when no more letters can be placed, or when a solution has been found and you want the n...
4,710,839
4,710,903
piping standard output into QLabel in Qt 4.7
I am trying to wrap a colleges c++ code in a Qt widget. However, his programs std output necessarily needs to be viewed. As of now I am assuming I will build a GUI and open a QProccess that will run his program (then send commands over that pipe). So my question is there anyway to read the standard output of that prog...
As the process runs, the QProcess object will emit the readyReadStandardOutput() signal as soon as there are data available on the standard output. You can subscribe to the signal, call readAllStandardOutput() from the connected slot and append (not replace) the data to your widget. If you don't need the data to be dis...
4,710,848
4,710,855
pthread library not found when building executable?
I'm trying to build a simple test program for a ThreadManager class I created. As you can see in the output below, my ThreadManager and main code seems to compile into object files just fine, but then when creating the executable, it can't seem to find proper references to any of the functions from the pthread class. W...
Link to the pthread library; g++ -c -o ThreadManager.o ThreadManager.cpp g++ -c -o main.o main.cpp g++ -o tm_test -lm -lpthread
4,711,098
4,711,230
Passing End of Transmission (Ctrl + D) character in Eclipse CDT console
I have a C++ application, to which i need to send an End of Transmission signal. I can do a Ctrl+D on the console, but when I try that within Eclipse, it doesn't work. I am using Eclipse Galileo with CDT.
It seems to be a not yet resolved bug: bug 159803 (resolved in September 2015, for CDT 9.0) Since Eclipse 3.1 it is possible to signal EOF (using CTRL + D/Z - bindable in key preferences) in console view, and I tested this successfully with Eclipse 3.2.1 using a simple Java app. CDT on the other hand will not recogn...
4,711,238
4,711,287
Using ifstream as fscanf
Assume that I have an input as follows: N (X_1,Y_1) (X_2,Y_2) .... (X_N, Y_N) where N, X_i and Y_i are integers. An example: 2 (55,1) (521,7) To read this, I can do something like this(assume all variables are defined, etc.): fscanf(fin,"%d ",&N); for (int i = 0; i < N; i++) fscanf(fin,"(%d,%d) ", &X[i], &Y[i]); ...
int n, x, y; char c; if (is >> n) for (int i = 0; i < n; ++i) if (is >> c && c == '(' && is >> x && is >> c && c == ',' && is >> y && is >> c && c == ')') { X[i] = x; Y[i] = y; } else throw std::runti...
4,711,397
4,711,930
C++ LINUX get all machine connected domain names
Possible Duplicate: Can I get the names of all the domains a Linux computer is connected to in C++? Hi My Linux machine is connected (by external NICs) to 2 external domains. I want to discover in my linux c++ application all the names of domains my machine is connected to. how can I get all these names? BTW: if get...
You can get a list of domains the DNS resolver is going to search from /etc/resolv.conf $ cat /etc/resolv.conf # Generated by NetworkManager search anon.local int.anon.co.uk nameserver 10.201.13.10 nameserver 10.213.13.10 nameserver 8.8.8.8 In the above there is search directive with a list of domains to search. So, ...
4,711,436
4,711,773
Interfacing existing C++ code with flex
I have existing video streaming application which is based client server technlogy. Existing system is as follows There is data center, client application and gateway. camera is connected with gateway and gateway is connected with data center.client request video to data center and datacenter get it from gateway. Now w...
Hey, Yes this is pretty much possible with flex 4,(ie. only if you are using a desktop application).From a web based swf, running in a browser you cannot start running a C++ code. I am assuming that you are developing a desktop app.To call a c++ code , you would need to do the things mentioned in the following example...
4,711,449
4,711,475
What does the symbol \0 mean in a string-literal?
Consider following code: char str[] = "Hello\0"; What is the length of str array, and with how much 0s it is ending?
sizeof str is 7 - five bytes for the "Hello" text, plus the explicit NUL terminator, plus the implicit NUL terminator. strlen(str) is 5 - the five "Hello" bytes only. The key here is that the implicit nul terminator is always added - even if the string literal just happens to end with \0. Of course, strlen just stops a...
4,711,478
4,711,674
Getting confused with C++ template
I am looking at some c++ code and do not understand the purpose of the template declaration in this situation: template<> void operator>>(const ClassA& s, const ClassB d) {...} What is the semantic of template<>?
This is, indeed, template specialization, as others before mentioned. There must be some previously declared function template, such as: template<typename T, typename U> void operator>>(const T& s, const U d) {...} However, it is quite misguided. It is much better to remove the template<> altogether, so operator>> wou...
4,711,549
4,718,609
Stop boost::depth_first_search along a particular depth if certain criteria is met
I'm using BGL to store my DAG. Vertices have states. Given a change in state in one of the vertices i want to update dependent vertices. This i'm able to do using boost::depth_first_search and a custom visitor. Now the logic is that i dont want to update a searched vertex and its dependent if the vertex is in a particu...
It seems that boost::depth_first_search does not support this, but the underlying boost::depth_first_visit does, through its 2nd overload allowing for a "terminator function" (TerminatorFunc). So you could copy the implementation of boost::depth_first_search and substitute the detail::nontruth2() parameter passed to bo...
4,711,676
4,837,716
can I set the AppUserModelID of an arbitrary process launched through a jumplist?
I have a simple console application written in C++ that acts as a stub for launching another application through it's jumplist. Purpose is to add jumplist abilities to applications that do not support this. Call it stub.exe. When running stub.exe it creates a custom jumplist using these steps (taken right form the MS s...
not much reactions here ;] In the meantime I managed to solve the main problem myself; it's not quite a straightforward solution but it fullfills the requirements: a program runs in the backround and installs a CBT hook. Each time an application creates a window (HookProc code = HCBT_CREATEWND), the hook checks the app...
4,711,686
4,711,847
How to make a class capable of calling array of other classes functions?
What we need is a class with 2 methods add() and call(). When we create a class we can add using add() function a function we want to be called when call() will be called with params like (pseudocode) new A; new B; A.add(B.function(int)) // B takes int as an argument A.call(); // and call() would look like {int i; send...
Try this (I had to rename do, it's a keyword in C++): #include <iostream> #include <vector> using namespace std ; typedef void FuncInt (int) ; class A { public: void add (FuncInt* f) ; void call() ; private: vector<FuncInt*> FuncVec ; } ; void A::add (FuncInt* f) { FuncVec.push_back (f) ; } void A::call(...
4,711,743
4,713,747
Boost Date_Time problem compiling a simple program
I'm writing a very stupid program using Boost Date_Time library. int main(int srgc, char** argv) { using namespace boost::posix_time; date d(2002,Feb,1); //an arbitrary date ptime t1(d, hours(5)+nanosec(100)); //date + time of day offset ptime t2 = t1 - minutes(4)+seconds(2); ptime now = second_clock:...
Though I can't figure out what's ss in your code, qualifying date and Feb as the following will make your code valid. boost::gregorian::date boost::date_time::Feb Hope this helps.
4,711,836
4,711,871
GNU General Public License ERROR?
I have developed a program which makes use of serial programming to read and write from serial port and put the values in databases in Ubuntu environment. Lately, I have added few functionality using boost lib to filter the read function etc. But when I run the program , say after 15-20 mins , I got segmentation fault...
Easy answer. Your program segfaulted. That means its is no longer working and it can behave badly. In this case it started to print out a string (probably not properly terminated) and it was continuing to print out the program memory. And you have probably included the GNU GPL license text which is long. The possibilit...
4,711,935
4,712,422
Scope in a lambda expression
#include "stdafx.h" #include <iostream> using namespace std; template<class Type> struct X { void run()const {//Why on earth this doesn't work? [&]() { Type::alloc(); }; } void run_1()const {//if this does Type::alloc(); } }; struct T { static v...
You'll have to pass it in to the lambda: void run()const {//Why on earth this doesn't work? auto alloc = Type::alloc; [&]() { alloc(); }; }
4,711,999
4,739,128
How to debug a DYLIB in XCode?
I am an experienced Visual Studio developer who has recently taken on an OSX 10.6 project (a C++ server project with no UI). I have been successfully debugging the application using the XCode debugger (setting breakpoints, etc.) for months, including debugging the source code for various static libraries that are linke...
Update - This problem is resolved. It was my lack of experience with OSX that caused me to fail to see this. Despite the fact that my DYLIB project was part of the same XCode project as the executable that calls it, and despite the fact that the DYLIB was built in the same directory as the executable, at runtime the ...
4,712,102
4,712,254
Linking object files built using different versions of GCC
I have some compatibility concerns around the building of a C++ library with a modern version of GCC 4.4.x/4.5.x whereby clients on an older version, say 3.4.x/4.1.x. One solution which has been suggested is to compile the object files and distribute these. Clients can then link using any version of GCC and the relevan...
The safest would be to give them a .so and its corresponding header with the stable binary API. To be binary stable that API should not accept or return any std:: types like std::string or std::vector<> because the binary layout of std:: types may change from version to version. And it should be linked statically with ...
4,712,109
4,713,283
Call function by pointer and set parametrs in memory block
I've little problem : I'm solving problem with calling function by pointer and passing to it parameters in continuous memory block. My goal is to have function named e.g CallFunc(void * func,void *params, unsigned int param_length); that I'll send function pointer, pointer to function's parameters and eventually p...
Ok, another try :) Again I'm not sure this is what you need + I believe that you need to change your code style(because from your question I'm filling that you are doing something vary strange). And here is my solution: #include <iostream> #include <boost/function.hpp> using namespace std; template <typename Ret> void...
4,712,192
4,712,415
How to append to a file with fstream fstream::app flag seems not to work
i simply want to write (append) to a logfile. I looked it up here: http://www.cplusplus.com/reference/iostream/fstream/open/ so this is what i did #include <fstream> fstream outfile; //outfile.open("/tmp/debug.txt" ); // works, simply for writing outfile.open("/tmp/debug.txt", fstream::app ); // does nothing out...
fstream::app|fstream::out instead of fstream::app. app doesn't make sense without specifying out (one could think it should have implied out, but it doesn't).
4,712,315
4,712,394
performance of unsigned vs signed integers
Is there any performance gain/loss by using unsigned integers over signed integers? If so, does this goes for short and long as well?
Division by powers of 2 is faster with unsigned int, because it can be optimized into a single shift instruction. With signed int, it usually requires more machine instructions, because division rounds towards zero, but shifting to the right rounds down. Example: int foo(int x, unsigned y) { x /= 8; y /= 8; ...
4,712,739
4,712,855
Is select function internaly call tcp connect?
Code Sinnpet: int CreateaTCPSocket() { int iSockID = ACE_OS::socket(......); ACE_OS::set_flags(iSockID,O_NONBLOCK); ACE_OS::bind(); if (ACE_OS::connect(iSockID ,....) < 0) { if (ACE_OS::select(.....,timeout) <= 0) { return INVALID_HANDLE; } } return iSock...
For both blocking and non-blocking sockets you only need to call connect() once. When the socket is non-blocking and connect() returns EINPROGRESS it needs to wait till the socket becomes ready for write using select(). When select() reports that socket is ready for write it can be either that connect() succeeded or fa...
4,712,824
4,712,844
What does "class :" mean in C++?
I've never seen it before. I thought it was a typo for "::sample", but when I saw it actually compiles I was very confused. Can anyone help me find out please? I don't think it's a goto label. void f() { class: sample { // there were some members declared here } x; }
It is an unnamed class, and the colon means it inherits privately from sample. See it like class Foo : private sample { // ... }; Foo x;
4,712,895
4,712,984
unlocking threads only on new data (threads calling order)
so i have a class like: class mySafeData { public: void Set(int i) { boost::mutex::scoped_lock lock(myMutex); myData = i; } void Get( int& i) { boost::mutex::scoped_lock lock(myMutex); i = myData; } private: int myData; boost::mutex myMutex; }; I have some t...
You need a condition variable. Note that even when your reader thread acquires the mutex associated with condition variable, it needs to check the condition has been met. Perhaps let the setter set a flag when it has set something and the reader can reset it when it has read it. This needs refinement but will do the jo...
4,712,958
4,712,985
C++: Pointer as a key in a hashtable
Are there any problems using pointers as hashtable keys during program run? (no need to store to disk and use it later as that causes obvious problems) There are many circumstances where I need to quickly know whether an object belongs to some object manager. A quick way to check it is to store every object in an objec...
No, there are no problems. It's just like storing an int. A pointer has got a value that doesn't change and that uniquely identify a resource. There of course be problems if you don't use well your pointers, but this is another, uncorrelated thing.
4,712,992
4,712,997
How to define sealed class in C++?
How to stop the class to be inherited by other class.
C++11 solution In C++11, you can seal a class by using final keyword in the definition as: class A final //note final keyword is used after the class name { //... }; class B : public A //error - because class A is marked final (sealed). { // so A cannot be derived from. //... }; To kn...
4,713,140
4,713,248
How can I use a queue with QProcess?
I have a slot that is called passing some arguments used in a QProcess. I execute a external program with some of this arguments. The problem is that I want to have a queue for these processes, waiting until the previous process is finished to launch the next. What do you think is the best/easiest way? Here my method/...
You can use a QString queue to queue up your commands and store them. Then, start from the top of the queue, start a new process and connect its finished() signal to a slot. When that process finishes, start a new process if the queue is not empty and so forth.
4,713,214
4,713,972
Getting the number of leading 1 bits
Given an unsigned number, what is a good (preferably fast) way of getting the number of leading 1-bits? I need this to calculate the CIDR number from a quad-dotted IPv4 netmask. Note: I have seen getting-the-number-of-trailing-1-bits, so I can do the table-based lookup. Note 2: Even though I added a couple of language ...
Unless you are specifically looking for theoretical improvements in number of steps (i.e. O(lg(n)) in number of bits), I don't think you will practically do much better than table lookup and still have an algorithm that's portable. I'd expect to comfortably scan over 100 million IPv4 netmasks for leading ones per secon...
4,713,343
4,713,667
How to manipulate/return data with dynamically loaded functions (dlopen)?
I've spent days reading and re-reading every tutorials I've found on the subject, and spent hours (and even days) browsing related questions here at SO, but I still can't get the following to work. Accept my apologies if this is a duplicate: chances are that I've seen and re-read many times the duplicate questions but ...
The signature of a function is generated from its name and argument types (return value type doesn't matter). When you declare function with extern "C", C symbol naming scheme is used which apparently can't handle C++ types like std::string. That's why passing std::string as an arguments doesn't work. I can't explain w...
4,713,357
4,713,790
Would such class be readable only once a Set by multiple threads?
So having a class like: class mySafeData { public: mySafeData() : myData(0), changed( false ) { } void Set(int i) { boost::mutex::scoped_lock lock(myMutex); myData = i; // set the data changed = true; // mark as changed myCondvar.notify_one(); // notify so a reader can process it } void...
Actually, It's an odd approach to call notify_one() in the reader (Get)! If you want your readers to wait till something has been set, then you need something like this: void Set(int i) { boost::mutex::scoped_lock lock(myMutex); myData = i; // set the data ++stateCounter; // some int to track state cha...
4,713,482
4,713,519
How to declare a variable that spans multiple lines
I'm attempting to initialise a string variable in C++, and the value is so long that it's going to exceed the 80 character per line limit I'm working to, so I'd like to split it to the next line, but I'm not sure how to do that. I know that when splitting the contents of a stream across multiple lines, the syntax goes ...
You can simply break the line like this: string longText("This is a " "very very very " "long text"); In the C family, whitespaces are insignificant, so you can freely use character literals spanning multiple lines this way.
4,713,548
4,713,655
Qt - Using QEasingCurve's output for something other than an Animation
I wonder could anyone be of help. If for example I wanted to use the output of the QEasingcurve for another purpose other than driving a QAnimation, is this possible? For example, if I had a numerical read out on my GUI that I wanted to grow, overshoot and bounce back into place could I use the QEasingcurve for this p...
I am not sure I understand correctly what you want to display, but from what I understand, using QPropertyAnimation is probably the way to go. However, to answer your question, you can of course use QEasingCurve in a standalone manner, you just need to use the valueForProgress(qreal progress) member function.
4,713,658
4,713,699
suitable data structure for set (graph) partition
I need to store data grouping nodes of a graph partition, something like: [node1, node2] [node3] [node4, node5, node6] My first idea was to have just a simple vector or array of ints, where the position in the array denoted the node_id and it's value is some kind of group_id The problem is many partition algorithms rel...
Depending on what exactly you want to do with the sets, you could try a disjoint set data structure. In this structure, each element has a method find that returns the "representative" of the set it belongs to. A C++ implementation is available in Boost.
4,713,697
4,802,682
Any good C++ refactoring tools that could handle this scenario
I have a large C++ code base that contains a couple of functions for error logging that I'm planning to rewrite, defined as follows; void LogError(ErrorLevel elvl,LPCTSTR Format,...); // Literal version void LogError(ErrorLevel elvl,UINT ResourceID,...); // Resource version I'm planning to rewrite these as a single f...
Searching around for something light weight that met my needs drew a blank, and learning SED while worthwhile would have been a fair amount of work for something that did not quite solve my problem. I ended up writing my own tool to carry out the refactor needed on a seperate copy of the code base until I was happy th...
4,713,713
4,713,834
`#include <iostream>` with `-std=c++0x` is broken
If I specify -std=c++0x to g++, then I can't #include <iostream>. I get the following error messages (g++ 4.4.0 under mingw): In file included from c:\qt\2010.05\mingw\bin\../lib/gcc/mingw32/4.4.0/include/c++/bits/postypes.h:42, from c:\qt\2010.05\mingw\bin\../lib/gcc/mingw32/4.4.0/include/c++/iosfwd:4...
It seems to be a bug. There is a thread with a simple patch (in the very end).
4,714,011
4,714,448
Check if a textbox control is empty C++ Win32
i have this code that put the value of a textbox field in the variable. The textbox is a Ip Address Control. How can i check if when the user press the OK button the field is empty or not? Thank you char *myVar = new char[16]; *myVar = NULL; GetDlgItemTextA(hDlg, IDC_MYVAR, myVar, 16); delete [] myVar;
You probably have to use the IPM_ISBLANK message (i am not an expert on winapi, so i may be mistaken).
4,714,078
4,715,444
Capturing keyboard input and the consequences of hooks
I am writing a VoIP program and one of the standard features is press-to-talk, meaning while holding down a key you record and send audio. The key will react no matter if you are in a videogame or has focus on another window. My questions; do all VoIP programs explicitly use keyboard hooks to achieve this? For example...
Is there a way to reduce the cost, and how big is the performance hit? The performance hit and cost are directly proportional to the amount of work your handler code does. If you read the documentation it says that these are some of the reasons to do so (emphasis mine): Monitor messages for debugging purposes Provid...
4,714,089
4,714,104
Free Memory Occupied by Std List, Vector, Map etc
Coming from a C# background, I have only vaguest idea on memory management on C++-- all I know is that I would have to free the memory manually. As a result my C++ code is written in such a way that objects of the type std::vector, std::list, std::map are freely instantiated, used, but not freed. I didn't realize this ...
No: if objects are not allocated with new, they need not be freed/deleted explicitly. When they go out of scope, they are deallocated automatically. When that happens, the destructor is called, which should deallocate all objects that they refer to. (This is called Resource Acquisition Is Initialization, or RAII, and s...
4,714,289
4,716,251
Boost libraries - build only what I need
I downloaded the Boost libraries and now I want to build only a few of the libraries. What would be the right command for this? Apparently the build-type=complete option gives me too much. I am using Windows XP and want to use Bjam to compile Boost and MinGW to finally use it. At the moment I think I need the libraries...
In step 5.2.4 of Getting Started you can instruct b2 which libraries to build: ./b2 --with-program_options --with-filesystem --with-system Alternatively, use ./b2 --show-libraries to see a list of all libraries that are not header-only. Following is an excerpt from the page: In particular, to limit the amount of tim...
4,714,349
4,719,448
gflags full heap enabling with dlls doesn't work
I'm trying to enable full page heap with the dlls option using the debugging gflags tool. This to enable full page heap with an application but only with the specified dlls. When I do not use the dlls option it work fine. I am able to get an exception on any attempt to write over an allocated memory block. But when I ...
/dlls affects the DLL that calls the Win32 API HeapAlloc. Since you allocate with new[] the DLL you need to specify is actually the C Runtime (e.g. msvcrt90.dll).
4,714,494
4,714,811
Which string classes to use in C++?
we have a multi-threaded desktop application in C++ (MFC). Currently developers use either CString or std::string, probably depending on their mood. So we'd like to choose a single implementation (probably something other than those two). MFC's CString is based on copy-on-write (COW) idiom, and some people would claim...
I would use std::string. Promote decoupling from MFC Better interaction with existing C++ libraries The "return by value" issue is mostly a non-issue. Compilers are very good at performing Return Value Optimization (RVO) which actually eliminates the copy in most cases when returning by value. If it doesn't, you can ...
4,714,505
4,714,563
Convert QString to a Xerces string
I want to convert a QString to an XMLCh const * to be used by Xerces-C++. The former can be "transformed" to a NUL-terminated const ushort * in host byte-order in (I think) O(1) time. The latter is also a UTF-16 string, but I'm not sure in which byte-order. Has anyone tackled this problem before? I don't feel like doin...
Perhaps: const XMLCh* QtoX(const QString& s) { return (s.utf16()); } QString XtoQ(const XMLCh* x) { return QString::fromUtf16(x); } from here? I have no personal experience with this.
4,714,515
4,714,559
switch namespace by if condtion
in my C++ program I have several namespaces that contain several pointers with identical names. I then want a function to choose a namespace according to a parameter. I.e. something like: #include <iostream> namespace ns1{ double x[5]={1,2,3,4,5}; } namespace ns2{ double x[5]={6,7,8,9,10}; } int main(){ int b=1; ...
Namespaces are a compile-time feature in C++, you can't manipulate them dynamically in runtime. The best advice I could give you is try a different approach - namespaces are probably not meant to do what you want to do. So ask SO what you really want to do and you'll likely get a good answer without bending the system....
4,714,564
4,714,846
C++ compile error with iostream
I am using fstream and got some error. Here is what I have: class CLog { void printOn(std::ostream& dbg) const; } void operator>>(const CLog& s, std::ofstream& dbg) { s.printOn(dbg); } But when I compile I got the following error: error C2664: 'printOn' : cannot convert parameter 1 from 'class std::basic_ofs...
Make printOn public and include fstream header :). #include <fstream> class CLog { public: void printOn(std::ostream& dbg) const { } }; std::ofstream & operator<<( std::ofstream& dbg, const CLog& s) { s.printOn(dbg); }
4,714,679
4,714,738
fopen - can't write more than 16K?
I'm currently using fopen to write/read binary files. With small files all is fines. But in some cases, when "exactly" the content is > 16K the remainder of the file is invalid !!! The code is simple, fopen ... fread/fwrite ... fflush ... fclose ! I have try with C++. But now I got a problem during the "read" in Binary...
fopen is only used to open a file stream, not to read or write. fread and fwrite are used to do that. fwrite and fread don't ensure you to write all the elements you pass them: they return the number of elements written, which can be lesser than the number of elements you passed it. Just check the returned value, and k...
4,714,698
4,714,727
Mixing Objective C ,(*.m , *.mm & .c /.cpp ) files
In my project Core libraries are part of C/C++ files, while UI needs to be developed in Objective C, I am able to access/Call C++ functions from Objective C/.mm files but reverse no luck so far, i.e. i am not able to call Objective C functions from C++ Files, when i tried to include Objective C header even system he...
If you have a .cpp file with C++ code that needs to use Objective-C as well, either rename that .cpp file to .mm or pass -x objective-c++ to the compiler.
4,714,814
4,715,134
How to assign / convert pointers?
Please give some advice on pointers and conversion and assignment of values. I have this fix class definition: (generated by gsoap) class LibClass { public: std::string *email; // pointer int landId; // no pointer // (....) much more } In a seperate function I assign data from a database...
First of all, LibClass should not have a pointer to a std::string unless there is a good reason. std::string internally handles all of the allocation for you. class LibClass { public: std::string email; // shouldn't be a pointer int landId; // no pointer // (....) much more } And t...
4,714,958
4,714,995
c / c++ compile-time "compatibility" check
Firstly, I recognize that this may not be possible, as macros are only expanded once. However, I'm hoping there is some standard way of getting similar behavior, or suggestions for other methods to pursue. I'm looking for a way to do a compile-time check on our build that would raise an error in the event of incompati...
boost static assert? As this is tagged C and C++, boost is perhaps not an option but refer to : BOOST_STATIC_ASSERT without boost for alternative.
4,715,142
4,715,321
If I've overloaded the + and = operators, do I have to overload +=?
More generally, what operators should I be overloading? I know that an overloaded += is a good thing because the expansion to a = a + b creates a temporary object, whereas an overloaded += can avoid that. Will a += that is not overloaded effectively use my overloaded operators?
The best way to implement operator+, favoring code reuse, is class Foo { Foo(Foo const&); // Implemented Foo& operator+=(Foo const& rhs) { // Implement all the addition-specific code here return *this; } }; and then Foo operator+(Foo x, Foo const& y) { x += y; return x; } If you h...
4,715,161
4,715,185
check for remaining space in RAM on Windows?
I am creating a program that will allocate a huge amount of data in the RAM. Now, if RAM runs out of space, the program will be put on to virtual memory and paging swap will occur. This is very slow. Is it possible to check for remaining space of RAM? And is it possible to check whether the system is now using virtual ...
You can use GlobalMemoryStatusEx function to get the amount of free RAM. To get a notification when you are running out of RAM you can use QueryMemoryResourceNotification method.
4,715,254
4,715,338
Qt popup grabMouse for all children
I'm trying to create a popup menu like control that contains custom widgets. I need to capture the mouse, but I need to have the children in the widget still get their mouse messages. It appears the grabMouse sends events only to the widget that grabbed the mouse, not its children. The popup is simply a series of butto...
It appears that simply specifying attribute Qt::Popup is enough to get the fundamental behaviour required. Installing an event filter on all children is also necessary. All mouse events, enter/leave/hover events must be captured. QT has a defect with grabMouse so that won't work -- the filter must be used to get expect...
4,715,273
4,736,602
Qt-Frameless window and OS button
Hello, I have a frameless application in which i have reimplemented my menu bar. I want to get the default close, minimize and maximize button for the os (Max, Windows ...). Can somebody give me a sort of guideline or tips to do so ? I've tried using : maxPix = style()->standardPixmap(QStyle::SP_TitleBarMaxButton); bu...
Try playing around with CustomizeWindowHint and setting Qt::WindowMinimizeButtonHint after you set Qt::FramelessWindowHint. http://doc.trolltech.com/4.6/qt.html Search for CustomizeWindowHint flag.
4,715,403
4,715,420
How to make a process aware of other processes of the same program
I must write a program that must be aware of another instance of itself running on that machine, and communicate with it, then die. I want to know if there is a canonical way of doing that in Linux. My first thought was to write a file containing the PID of the process somewere, and look for that file every time the pr...
Putting the pid in a file is a common way of achieving this. For daemons ("system programs"), the common place to put such a file is /var/run/PROGRAM.pid. For user programs, put the pid file hidden in the user's homedir (if the program also has configuration files, then put both config files and the pid file in a subdi...
4,715,740
4,715,888
Why is a c++ reference considered safer than a pointer?
When the c++ compiler generates very similar assembler code for a reference and pointer, why is using references preferred (and considered safer) compared to pointers? I did see Difference between pointer variable and reference variable in C++ which discusses the differences between them. EDIT-1: I was looking at th...
It's considered safer because a lot of people have "heard" that it's safer and then told others, who now have also "heard" that it's safer. Not a single person who understands references will tell you that they're any safer than pointers, they have the same flaws and potential to become invalid. e.g. #include <vector> ...
4,715,807
4,715,941
Casting chars from input to string
fgetc() for proccessing entered chars - char by char. The function returns integer value of entered char. I need to check these: Each town shouldn't exceed 30 characters There exists a "-"(dash) character on each line (splitting the whole line to two cities) I've defined 31-int-array and one integer for counting char...
You have both technical errors (invalid C++) and logic errors. A main cause of that is complexity of doing char-by-char input. You may find it easier to use C++ level i/o: declare a std::string variable to hold a complete line of input, read it by using std::getline. Cheers & hth.,
4,715,831
4,715,856
Why is #define bad and what is the proper substitute?
#define dItemName L"CellPhone"
Define it as a constant variable. It is a good programming practice. const wchar_t *dItemName = L"CellPhone"; In case you need to know the lenght of your string somewhere later, then define it as an array: const wchar_t dItemName[] = L"CellPhone"; Also, why #define is bad: It transforms all places where you use word ...
4,715,890
4,742,076
What mutation-testing frameworks exist for C/C++?
Mutation testing has been out there for a while now, and it seems there are at least one or two commercial mutation testing frameworks for C/C++. Have you used them? What are your experiences? Are there any open source alternatives?
A brief search resulted in: PlexTest: http://www.itregister.com.au/products/plextest_detail.htm Insure++: http://www.parasoft.com/jsp/products/insure.jsp;jsessionid=baacpvbaDywLID?itemId=63 MILU (may be only for C): http://www.dcs.kcl.ac.uk/pg/jiayue/milu/ With that said, you need to realize that mutation testing isn...
4,715,963
4,716,020
BlackJack cards vector c++/random numbers
I followed some of the answers here on the site but I still have a problem: after I generate my vector of cards when I run the program the card numbers are totally off: first card:100 second card:22 third:0 fourth:0 fifth:28 etc. This is my code: enum numar {AS=11 ,DOI=2, TREI=3, PATRU=4, CINCI=5, SASE=6, SAPTE=7, ...
So...replacing enums with values: int k = 0; for (int r = 11; r <= 10; ++r) for (int s = 0; s <= 3; ++s { } See the problem?
4,715,984
4,717,976
Qt QAbstractButton setDown interferes with grabMouse
I have some weird behaviour in Qt that seems like a defect. I'd like to know if anybody has a good workaround. I have a popup widget that contains many buttons in it. The user activates the popup by pressing the mouse button down. The popup widget calls grabMouse when shown. It gets all the mouse events. As it rolls ov...
I've entered the defect at the Nokia DB. I'm giving it about a 95% chance that they close it as "works as intended". For those of you that need a solution nonetheless you'll have to use event filters and create your own grabbing. Basically install an event filter for every child widget and propagate the mouse events to...
4,716,098
4,716,157
Regular expressions in c++ STL
Is there any native library in STL which is tested and works without any extra compiler options? I tried to use <regex>, but the compiler outputs this: In file included from /usr/include/c++/4.3/regex:40, from main.cpp:5: /usr/include/c++/4.3/c++0x_warning.h:36:2: error: #error This file requires compiler and library s...
G++ 4.3 (and presumably later versions as well) is just being careful about the header files for maximum standards conformance. If you're programming in C++98 (the current standard that's been around for a while), then regular expression support was added in tech report 1, and the and the header files are in a special ...
4,716,223
7,358,518
JNI: How to pass "unsigned char* " from C++ to java
I have a 'unsigned char *' and I want to pass it on to the Java code using JNI I have tried it in the following way jstring test1; std::string str(reinterpret_cast<const char*>(ucptest)); test1 = env->NewStringUTF(str.c_str()); where 'ucptest' is 'unsigned char *' and has ascii values in it. this code works and I ...
I found the solution, and thought I would share the same, so that others could use it. Initially I was converting char* to C++ String and then passing it to Java String. This was working just fine, until we had "0" in the string I was trying to convert. This was causing a crash. Finally, I used a byte array to pass o...
4,716,374
4,716,417
tr/regex c++ library - definition of regex pattern
How should i define the regex pattern, when i use the tr1/regex library? #include <tr1/regex> const regex pattern("[^-]-[^-]"); is not working... When compiling i get error: ‘regex’ does not name a type
regex is in the tr1 namespace so you either need to declare that you are using tr1 or specify that regex is in the tr1 namespace: using namespace tr1; or const tr1::regex pattern("[^-]-[^-]");
4,716,386
7,351,844
Library for managing paths/URLs
Is there any library in C or C++ that helps with managing paths or URLs? Or maybe functions from standard library from one of these languages Example: Imagine following API: class Path { public: Path(std::string &path); std::string getPath(); void cd(std::string &path); } What I need is that this li...
The Boost Fileystem library has a path class which supports much of what you're looking for. Instead of a cd command, it overloads operator=/ for descending directories and has a parent_path() method for ascending. It's very portable and easy to learn. It is, however, unable to deal (AFAIK) with URL paths.
4,716,426
4,716,476
What exactly was the rationale behind introducing references in c++?
From the discussion that has happened in my recent question (Why is a c++ reference considered safer than a pointer?), it raises another question in my mind: What exactly was the rationale behind introducing references in c++?
Section 3.7 of Stroustrup's Design and Evolution of C++ describes the introduction of references into the language. If you're interested in the rationale behind any feature of C++, I highly recommend this book. References were introduced primarily to support operator overloading. Doug McIlroy recalls that once I was e...
4,716,546
4,716,565
deleting a vector of pointers vs. object in c++
I have a vector of pointers to an object (I have them as pointers because I will be swamping the positions around a lot, and I would imagine it would be a lot faster to just swap the pointer, rather than swapping around the whole object. Anyway, I will ultimately need to delete the vector, but the objects that it point...
Calling a destructor on a pointer value does nothing. (On the other hand, calling delete on a pointer value runs the destructor for the pointed-to object, and frees the memory.) In the case of an array of pointers to objects, you must free the objects manually if that's what you want.
4,716,576
4,717,122
Regular expressions matching
I have one function for checking, whether entered line is "OK". #include <tr1/regex> bool lineIsValid(string line) { const tr1::regex pattern("[^-]{1,30} - [^-]{1,30}"); return tr1::regex_match(line, pattern); } lineIsValid("test - test"); the function returns false. Why?
Perhaps the syntax is ok, but depends on the implementation. Check this post. Or this: After further investigation, I (we) have determined that the TR1 framework supplied by Microsoft with Visual Studio 2008 [and some very early versions of Visual Studio 2010] is buggy, which makes me wonder why the other regex...
4,716,629
4,716,656
C++ error - returning a char array
Consider the following code: char CeaserCrypt(char str[256],int key) { char encrypted[256],encryptedChar; int currentAsci; encrypted[0] = '\0'; for(int i = 0; i < strlen(str); i++) { currentAsci = (int)str[i]; encryptedChar = (char)(currentAsci+key); encrypted[i] = encryp...
The return type should be char * but this'll only add another problem. encrypted is "allocated" on the stack of CeaserCrypt and might not be valid when the function returns. Since encrypted would have the same length as the input, do: int len = strlen(str); char *encrypted = (char *) malloc(len+1); encrypted[len] = '\...
4,716,688
4,717,073
Why does my program that creates a stack using std::vector crash?
I am creating my own stack for my data structures class. For our assignment we are using the assignment to convert a real-time infix equation into a postfix equation. I thought my program: took input determines if it was digit or number(operand) prints it out determines if input...
I'll expand on Rup's answer to answer the question you didn't ask, but is more important: How can I find out where my program is crashing? One way is to put std::cout or printf statements throughout your program. Put a statement at the beginning of every function saying, "function x enter" and at the end saying, "fun...
4,716,702
4,716,759
Digital Mars - unable to open input file 'iostream'
I'm using "Digital Mars" to compile the following program: #include <iostream> using namespace std; int main() { cout <<"My name is Abder-Rahman"; return 0; } And, this is what I get: C:\Users\Software Engineer\Desktop\C++\dm852c\dm\bin>dmc print1 Fatal error: unable to open input file 'iostream' --- errorlevel...
Check VernonDozier answer about this problem: The code is fine. Your compiler installation is probably broken. You have a bad include path, permissions problems, or you have files missing. Your compiler is probably misconfigured. I recommend you to read this post.
4,716,994
4,717,008
What's wrong with the "new" keyword in C++?
I know that this might sound like a stupid question, but why do I get an error which says something like " cannot convert Object* to Object " when I try to instantiate a new Object by using the statement " Object obj = new Object(); "? Am I to understand that the "new" keyword is reserved for pointers? Or is it som...
Object* obj = new Object(); new always return pointer to object. if you write just Object obj it means that obj will hold the object itself. If it is declared this way inside function then memory will be allocated on stack and will be wiped once you leave that function. new allocates memory on heap, so the pointer can...
4,717,089
4,717,170
xerces-c: Xml parsing multiple files
I'm atempting to learn xerces-c and was following this tutorial online. http://www.yolinux.com/TUTORIALS/XML-Xerces-C.html I was able to get the tutorial to compile and run through a memory checker (valgrind) with no problems however when I made alterations to the program slightly, the memory checker returned some pot...
Looks like the example code has some shortcomings for your use case. It contains this code: m_OptionA = XMLString::transcode(xmlch_OptionA); From the documentation we can see that transcode requires its caller to deallocate the returned (C-style) string with XMLString::release(). We can see that this is done in the ...
4,717,204
4,718,547
gdbserver follow child
I'm trying to debug a forking process on remote host, but getting the gdbserver process end on me every time with child exit. Tried to setting "set follow-fork-mode child" in .gdbinit, didn't help. Is there a good solution for this one? Thanks.
Does the forking process fork more than once? If not, you can use the --attach option to attach to the child.
4,717,289
4,717,312
Checking if a function with a given signature exists in c++
So I was looking for ways to check whether a function with a particular argument exists. I have a templated method which relies on an external function (external from the class) to do the job: template <class Moo> void exportDataTo(Moo& ret){ extended_solid_loader(ret, *this); } At multiple points in the pr...
You can just provide a function template for extended_solid_loader providing a default implementation, and users who want to use something other than the default implementation just specialize that. template<class T> void extended_solid_loader(T & ret, SomeClass & obj) { // default implementation here } template<>...
4,717,537
4,717,584
c++ class operator self-typecast
How can I create an operator function within a class that serves to typecast other types as an object of that class? e.g. class MyClass { // ... // operator ?? // ... } int main() { MyClass obj; int Somevar; obj=(MyClass)Somevar; // class typecast } In general, is there an operator that allows this kind...
Just add a constructor that takes one argument: class MyClass { explicit MyClass(int x) { … } }; called as: MyClass x = static_cast<MyClass>(10); // or MyClass y = MyClass(10); // or even MyClass z(10); This allows an explicit cast as in your example. (The C-style cast syntax is also supported but I won’t show it...
4,717,656
4,717,798
Is memory allocated for an object automatically deleted if an exception is thrown in a constructor?
Suppose there is this code: class CFoo { public: CFoo() { iBar = new CBar(); } private: CBar* iBar; }; .... CFoo* foo = new CFoo(); When the above line is executed, first memory will be allocated to hold the CFoo object. But then if the line new CBar() throws an exception (due to lack of memor...
Yes, the memory allocated for the CFoo object will be freed in this case. Because the exception due to the failed allocation causes the CFoo constructor to fail to complete successfully the new-expression is guaranteed to free the memory allocated for that CFoo object. This guarantee is specified in 5.3.4 [expr.new] / ...
4,717,892
4,728,892
Crash if I try to copy uncompressed filtering_istream to stringstream
I want to uncompress a file and write its content into a stringstream. This is the code I tried: string readGZipLog () { try { using namespace boost::iostreams; ifstream file(currentFile.c_str(), std::ios_base::in | std::ios_base::binary); boost::iostreams::filtering_istream in; in.push(gzip_d...
after a lot of research and trying I finally found a way how to handle (de)compression correctly. This is the code that works for me without any problems (with gzip and bzip2): string readGZipLog () { using namespace boost::iostreams; using namespace std; try { ifstream file(currentFile.c_str(), ios_ba...