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,265,022
4,267,074
Emacs indent template class/functions
Does anybody know how to inhibit emacs from indenting the name of functions or classes after a template clause? Currenty the result is: template <typename T> class A { /* ... */ }; where I would like to have: template <typename T> class A { /* ... */ }; Thank you very much for your help. EDIT 1 I'm using ...
Go to the class line and hit TAB to perform the (unsolicited) indentation. Then press Control-CControl-Oto display the indent mode fortopmost-intro-cont` Press ENTER, then you can change the indent number (3 to 0 for instance). At the end of your .emacs you can set permanently that instruction: (c-set-offset 'topmost...
4,265,046
4,269,146
Removing Qpixmap from QGraphicsScene
I enconutered a problem, when dealing with QGraphicsScene and QPixmap. I am sequentially displaying frames, captured by the camera. QTimer object is calling updateSingleView() function every 100ms. That is my inner function: void CCIGui::updateSingleView() { unsigned char *const img = PGRSystem->SnapShot(); ...
As suggested you need to delete the item after removeItem line. i.e QPointer _item = scenes.at(0)->items().at(0); scenes.at(0)->removeItem( _item ); delete _item; scenes.at(0)->addPixmap(QPixmap::fromImage(Img)); .....
4,265,132
4,265,157
Small is beautiful, but is it also fast?
I had an argument with a co-worker about implementation of simple string parser. One is "small", 10 lines of code, using c++ and streams, the other is 70 lines of code, using switch cases and iterating string char by char. We tested it over 1 million of iterations, and measured speed using time command. It appears that...
Less lines of code you have; the better. Don't add 60 lines more if you really don't need to. If it's slow, profile. Then optimize. Don't optimize before you need it. If it runs fine, leave it as it is. Adding more code will add more bugs. You don't want that. Keep it short. Really. Read this wiki post. "Premature opt...
4,265,167
4,265,192
Is a C++ compiler allowed to emit random code once it encounters a construct that is classified as undefined behavior?
Possible Duplicate: Undefined, unspecified and implementation-defined behavior I'm trying to deepen my understanding of undefined behavior in C++. Suppose a C++ compiler will intentionally detect some cases of undefined behavior - for example, modifying the variable twice between two sequence points: x++ = 2; Once ...
Yes. The standard imposes no requirements, so it can do whatever it wants: undefined behavior behavior, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements. Just as a note, that is undefined behavior, but it's not ne...
4,265,310
4,265,343
How to sleep a C++ Boost Thread
Seems impossible to sleep a thread using boost::thread. Method sleep requires a system_time but how can I build it? Looking inside libraries doesn't really help much... Basically I have a thread inside the function that I pass to this thread as entry point, I would like to call something like boost::this_thread::slee...
Depending on your version of Boost: Either... #include <boost/chrono.hpp> #include <boost/thread/thread.hpp> boost::this_thread::sleep_for(boost::chrono::milliseconds(100)); Or... #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/thread/thread.hpp> boost::this_thread::sleep(boost::posix_time::mi...
4,265,543
4,268,894
interprocess map versus map/unordered_map
There are a lot of discussions about the differences between std::map and boost::unordered_map. But what about boost::interprocess::map ? Did somebody perform perfomance tests between boost::interprocess::map and std::map ? I haven't used interprocess::map so much but i have the feeling that above 1M elements, it beco...
Boost interprocess containers are standard containers with custom allocators. Reason: when two processes share memory, the memory is mapped to different addresses in the two processes. To be able to use pointers to shared memory objects, one must not use absolute addresses but relative offsets (which are identical in b...
4,265,556
4,265,740
Finished Study, Any tips?
Hi finished doing 3 IT diplomas, I have customer service experience, have just started an open source project and will be joining some others already going... Had anybody got any other hot tips on how to get my foot in the door with a programming job? Anything, be creative with your answer... or don't be... anything wi...
firstly question yourself, why do you want to get into programming? what is it about programming that motivates you? then ask yourself if you were given a choice between a programming job and a job doing something other than programming, how much would you want to do the programming job? once you know the answers to t...
4,265,561
4,265,715
QTcpServer retrieve more than one address
I use QTcpServer from the Qt-Framework with C++. I started it with ret = tcpServer->listen(QHostAddress::Any, 9871) With QHostAddress serverAddress () const I retrieve the Address from it. Which is 0.0.0.0. In my opinion it should listen on more than one address (like 127.0.0.1 and the LAN Address). Is there a way t...
I'm not sure what your question is exactly, but... Usually, a 0.0.0.0 means that the socket listen to all interfaces that are both up and configured with a valid IPv4 address. If you want to get all the available IP addresses on the system, you should enumerate the network interface then query their respective IPv4 add...
4,265,639
4,267,961
Is it possible to use a gcc compiled library with MSVC?
I have a project that relies on libiconv for several operations. I was using precompiled binaries for iconv.lib for Visual Studio 2008 but now I had to move on to Visual Studio 2010 and no more precompiled binaries were available. I decided to compile it myself but as the libiconv documentation states, there is no offi...
Yes, this is possible because if you compile strictly as a C interface, iconv will link to msvcrt.lib, which is the Windows C runtime (strictly C, analogous to glibc used by GCC). If you built it with GCC's normal C++ compiler, it would link to libstdc++ and also name mangle differently compared to VC++, which links to...
4,265,693
4,266,672
In MPI_Send / MPI_Recv pairs, can data be lost if it isn't synchronised correctly?
Let me explain. Consider 4 slave nodes 1, 2, 3, 4 and a master node 0. Now, 1, 2, 3, 4, need to send data to 0. 0 receives this data in the following format. for(int proc = 1;proc<procCount;proc++) // for each processor cpu (procCount = 5) { for(int p = 0;p<50;p++) { std::cout<<proc<<"\tA\t"<<p<<std::endl;...
Firstly, do you really mean to receive an MPI_CHAR into chunkP - an int - shouldn't you receive an MPI_INT? The messages from ranks 1:4 will not get lost - they will get queued until rank 0 chooses to receive them. This behaviour is mandated by the MPI standard. If the messages are large enough, ranks 1:4 may block un...
4,265,899
4,265,980
Is there a way to restore/recover nohup to see the output in the console?
I know chances are extremely low, but is there a way to see what a nohup-ed process has been outputting recently? I still have this process open but I've run it with redirecting all output to /dev/null. So is there a way to recover such process back to console, or is it hopeless :( Cheers
There is a way but it isn't straight forward, the trick is to use dup2 and depends on the fact that your program is linked against libc (which all c/c++ applications would be, but a java application wouldn't be for example) attach to your process using gdb run the following at the gdb prompt to redirect stdout to /tmp...
4,265,912
4,266,040
What does Visual Studio use vc90.pdb for?
According to http://msdn.microsoft.com/en-us/library/yd4f8bd1.aspx there's 2 .pdb files for a project. project.pdb I use to allow loading minidumps later on, but what exactly is vcx0.pdb used for? If it's missing, it's not a problem, and I don't need to store it for anything. I'm trying to share a PCH amongst differen...
VCx0.PDB is generated by the compiler and has type information. It is input to the linker. The linker outputs $(TargetName).PDB
4,266,078
4,266,162
How to schedule a task in C++
I have a C++ windows service which should call a function every 15 minutes. I am new to c++ and have no idea how to do this.Can anybody tell me how to achieve this? Thanks, Subrat
Call SetTimer(). Alternately, use the Task Scheduler API, which can execute a regular .exe or COM handler on a predefined schedule. If you do that, you may not even need a service.
4,266,310
4,267,826
Socket change in LSP
Is it possible to change the destination socket (IP and port) of the outgoing packets using LSP (Layered Service Provider) in Windows? For example, I want to redirect all HTTP packets to a proxy server (given IP/port). This way I can create "system-wide" proxy for Windows. I tried to include a call to WSPSendTo inside ...
You can't change the destination of a TCP socket once it has been connected, which is why calling WSPSendTo (with non NULL lpTo) has no effect. You should look at WSPConnect instead.
4,266,316
4,266,365
OpenCV: How to draw a line with colors that are inversed relatively to the surface it should be drawn on?
So we have an image. We want to draw a line that must definitely be seen. So how to draw a lines with colors that are inverted relatively to the surface it should be drawn on in each point?
Use a LineIterator and XOR the colour values of each pixel manually.
4,266,354
4,266,465
How to tell if glibc is used
I am trying to implement backtrace functionality for a large framework, which is used for different platforms and OS'es. In some of them, it is linked against glibc, while in the other, something different (eg. uclibc) is used. backtrace() function exists only in the former. Is there any way to tell whether glibc is us...
There are the #defines __GNU_LIBRARY__, __GLIBC__ and __GLIBC_MINOR__ (6, 2 and 11 on my system with glibc-2.11) in features.h.
4,266,662
4,266,744
Ignore values from stringstream (like %*f in sscanf)
I'm trying to get rid of old unsafe C functions, including sscanf(). Right now I'm using #include <sstream> std::string str = "111 222.2 333 444.4 555"; std::stringstream sstr(str); int i, j, k; float dummy1, dummy2; sstr >> i >> dummy1 >> j >> dummy2 >> k; I just need the integers from that. Is there any way to av...
sstr.ignore(128,' '); Ignore until next space, or until 128 characters were read.
4,266,687
4,267,067
Pattern to update UI state without triggering an event
Most GUI apps have multiple autoprocessing options, say editbox triggers autocomplete, listbox changes icons and product description, radiobutton triggers text updates and so on. Unfortunately, quite often it's needed to change the state of some of those controls programmatically, at the same time blocking the autotrig...
You could just disable the desired control (lets say IDC_YOURCONTROL) by using the following: GetDlgItem(IDC_YOURCONTROL)->EnableWindow(false); Using this the related triggers for yor control will not be triggered. After your done you can enable your control.
4,266,689
4,266,716
Vector of pointer to objects, need deep copy of vector, but the objects are the base of inherited objects
I want to have a deep copy of an vector with pointers to objects, but the object can either be C or B. I know confusing (the way I explain it), let me illustrate. class A { A(const A& copyme) { } void UnableToInstantiateMeBecauseOf() =0; }; class B { B(const B& copyme) : A(copyme) {} }; class C { C(co...
Use cloning: Copy object - keep polymorphism class Super { public: Super();// regular ctor Super(const Super& _rhs); // copy constructor virtual Super* clone() const = 0; // derived classes to implement. }; // eo class Super class Special : public Super { public: Special() : Super() {}; Special(co...
4,266,691
4,266,717
Problem with numeric_limits
Why this doesn't work? enum : long {MaxValue = std::numeric_limits<long int>::max()}; I'm getting error :Error 1 error C2057: expected constant expression What isn't constant about it? Limits of long int are known at compile time so what's the problem?
The problem is that although std::numeric_limits<long int>::max() function returns constant value it is called in run-time and you need constant value in compile-time Probably you can just use LONG_MAX value instead (see climits header)?
4,266,738
4,266,848
Win1251->UTF16 conversion
I have a dll-project, written in Windows-1251 encoding, and I need my dll's output encoded in UTF-16. I use the following function to do conversion: ptr = MultiByteToWideChar(CP_ACP, 0, str, -1, wbuff.getBuffer(), len); Unfortunately, MultiByteToWideChar uses system locale as a source encoding. So for example if my Wi...
setlocale is a CRT function. Obviously Windows API doesn't care what is set via it. You should set the needed codepage (1251 in your case) instead of CP_ACP (which means system default). res = MultiByteToWideChar(1251, 0, str, -1, wbuff.getBuffer(), len);
4,267,006
4,269,227
Identifying Major Page Fault cause
I've been asked to look at an internal application written in C++ and running on Linux thats having some difficulties. Periodically it will have a large amount of major page faults (~200k), which cause the wall clock run time to increase by x10+, then on some runs it will have none. I've tried isolating different piece...
You may like to consider Valgrid, described on the home page as: Valgrind is an instrumentation framework for building dynamic analysis tools. There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. You can also use Valgrind to build new to...
4,267,009
4,267,066
G++ won't accept inline constructors in C++
I have a problem, may be dumb. The thing is, I am unable to inline a constructor in a class. Consider I have a class called Foo. If I write the implementation of Foo something like this: class Foo { int p; public: Foo() { p = 1; } }; or even like this: class Foo { int p; public: Foo(); }; inline Foo::...
Inline functions must be defined in every source file in which they are used. The easiest way to achieve this is to put the definition(body) of the function in the header file and include the header wherever the function is used
4,267,120
4,267,253
Delphi: Doesn't load a DLL unless I install Visual C++ 2008 Redistributable
I have a DLL that gets loaded in my application, like so: procedure LoadTessDLL; var DLLHandle: THandle; begin DLLHandle := LoadLibrary(PChar(ExtractFilePath(application.exename) + 'tessdll.dll')); if DLLHandle >= 32 then begin TessDLLLoaded := True; We discovered that on an XP PC with Service Pack 2, the ...
Do you control the source DLL? If not then no, the DLL relies on the C++ 2008 Runtime and it must be installed for the DLL to run and you need to add that as part of your install. If you you do control the source for the DLL then statically link it to the C++ runtime, which will build the runtime into the DLL. This is...
4,267,176
4,267,808
Create service in Windows Xp with a config file
This is the command which I created a service of my program. Program normally uses a config file, but when I created this service, program could not start as a service. C:\>sc create MalwareService binPath= "C:\Program Files\mbam.exe"
You can't just run any random program as a service; there is a certain protocol the program has to follow.
4,267,194
4,267,258
Compiler warning for unary operation on unsigned int
I have this sample code which generates the following warning (VS2008 compiler with SP1): warning C4146: unary minus operator applied to unsigned type, result still unsigned Code: void f(int n) { } int main() { unsigned int n1 = 9; f(-n1); } But since function f is taking it's parameter as an int should...
Standard 5.3.1/7 The operand of the unary - operator shall have arithmetic or enumeration type and the result is the negation of its operand. Integral promotion is performed on integral or enumeration operands. The negative of an unsigned quantity is computed by subtracting its value from 2n, where n is ...
4,267,313
4,267,334
Call non-default constructor for object in vector initialization
I want to initialize a vector in an initialization list of a constructor. The vector consists of objects with a parameterized constructor. What I have is: Class::Class() : raster_(std::vector< std::vector<Cell> > (60, std::vector<Cell>(80))) { ... How can I call Cell::Cell with two parameters in the above line? Th...
You should try : Class::Class() : raster_(60, std::vector<Cell>(80, Cell(true, true))) { /* ... */ } Note that I removed the useless std::vector<std::vector<Cell> > from the initializer. Also be aware that this could be highly ineffective depending on the cost of copying a Cell : It creates an std::vector<C...
4,267,327
4,267,458
Overloading = operator in C++ when there are arrays of values to be copied
I'm somewhat new to C++ so, I guess this is a very basic question. Suppose I have this class: // file Graph.h class Graph { public: Graph(int N); // contructor ~Graph(); // destructor Graph& operator=(Graph other); private: int * M; int N; }; // file Graph.cpp Graph :: Graph(int size) { M = new int...
The canonical way is to use a std::vector<int> to avoid managing memory yourself. For the exercise though, the right way to do what you want is: #include <algorithm> class Graph { public: Graph(size_t n) { data_ = new int[n](); size_ = n; } Graph(Graph const& g) { data_ = new int(g.size_); ...
4,267,363
4,267,515
Base class on the initialisation list of a derived class' copy constructor (C++)
Let the example be: class Base { Base (const Base & copyFrom) { globalRegister (* this); } } class Derived { Derived (const Derived & copyFrom) : Base (copyFrom) {} } I've read suggestions to include the Base's copy constructor on the initialisation list of Derived in order to copy over the Base's properties (as ...
Would that be a case where I actually must use (implicitly or explicitly) Base's (default) constructor on the initialisation list of Derived's copy constructor, and call the Base's copy constructor only in the body of Derived's copy constructor, when there is actually an object that can be attached by Base's copy cons...
4,267,423
4,267,674
Namespace member definition
namespace M{ void f(); void M::f(){} } int main(){} The above code gives error like so: "ComeauTest.c", line 3: error: qualified name is not allowed in namespace member declaration void M::f(){} And G++ also gives error. But VS2010 compiles fine. My questions are: a) What is the exp...
Which portion of the Standard guides the behavior of such code? C++03 Section $8.3 says A declarator-id shall not be qualified except for the definition of a member function (9.3) or static data member (9.4) out-side of its class, the definition or explicit instantiation of a function or variable member of a namespa...
4,267,526
4,267,578
Issue with overloaded = function
Here is my issue. I have a class called AguiFont. It internally has a pointer to whatever type of font the font loader is set to. I overloaded the = operator so that users wouldn't ever have to manage its memory. It works great except for one circumstance. When I set the font for a widget in its constructor, for some r...
I'm inclined to blame the copy ctor (which you don't show). If the font is copied when a temporary is created, the first destructor will probably call loader->destroyFont(nativeFontPtr);. If the copy ctor didn't duplicate nativeFontPtr, this will destroy the single underlying font as soon as the temporary goes out of s...
4,267,546
4,267,596
C++ Boost ASIO simple periodic timer?
I want a very simple periodic timer to call my code every 50ms. I could make a thread that sleeps for 50ms all the time (but that's a pain)... I could start looking into Linux API's for making timers (but it's not portable)... I'd like to use boost.. I'm just not sure it's possible. Does boost provide this functionali...
The second example on Boosts Asio tutorials explains it. You can find it here. After that, check the 3rd example to see how you can call it again with a periodic time intervall
4,267,570
4,267,667
Can you create objects using variables in C++
I want to create a number of objects of a class, but this number won't be known until runtime. Intuition tells me that I should use the following loop to create my objects: for (int count = 0; count < no_of_objects; count ++) { ClassName object_name[count] } This, however does not work as the compiler doesn't app...
It's time to learn vectors: std::vector<ClassName> objects (no_of_objects); Now use objects[0] through objects[no_of_objects - 1]; note that objects.size() equals no_of_objects. When you're ready, look at vector's methods, etc., but for now, this plus knowing the header to include (<vector>) is enough to use objects ...
4,267,676
4,268,694
Do temporary objects have scope?
Names have scope (a compile-time property), while objects have lifetimes (a runtime property). Right? I often see people talking about temporary objects "going out of scope". But since a temporary object does not have a name, I think it does not make sense to talk about "scope" in this context. The lifetime of a tempor...
Names have scope (a compile-time property), Yes. I would not call it a property thought. But basically yes. while objects have lifetimes (a runtime property). Right? There are three types of variables. Each type has different properties in relation to lifetimes. Automatic storage duration: Static storage duration...
4,267,854
4,267,918
Creating and deallocating a Qt widget object
I heard that the widgets should be allocated on the heap (using new), and then there are no needs to delete them (it is done automatically). Can someone explain why? What happens if a widget is not allocated that way, but on a stack? I am not sure if it matters, but all widgets I am creating have a parent. This says ...
There's no magic involved. Simply put, a QObject automatically deletes its children in its destructor. So, as long as your widget has a parent and that you destroy that parent, you don't have to worry about the children. So if you wondered what was that QObject * parent parameter, well, that's what it's there for. Also...
4,267,960
4,268,061
Format float\double numbers to CString with zero filling and preset number of digits
I am looking for a simple method to format the following float\double numbers to a CString. I was hoping to use CString.Format(), but alternatives are welcome as well, as long as it ends up being a CString. 3.45 112.2 To the following format: 00003450 00112200 Notice there should be no decimal point.Can this be done ...
CString myString; myString.Format(_T("%08d"), static_cast<int>(num * 1000.0 + 0.5)); Alternatively: //... #include <sstream> #include <iomanip> using namespace std; //... ostringstream s; s << setfill('0') << setw(8) << static_cast<int>(num * 1000.0 + 0.5); CString myString(s.str().c_str()); //... Refs: CString::...
4,267,970
4,268,027
Find a char or substring with specifying start pos
I couldn't find a function which would let me specify the start pos for beginning a char or substring search. I have, for example: char *c = "S1S2*S3*S4"; I'd like search for 'S3' by searching the first '*' asterisk and then the second asterisk following it and finally getting the substring 'S3' enclosed by those aste...
One solution would be to find the location of the first asterisk, then the location of the second asterisk. Then use those positions as the start and end locations to search for S3.
4,268,019
4,268,131
SetThreadAffinityMask of pooled thread
I am wondering whether it is possible to set the processor affinity of a thread obtained from a thread pool. More specifically the thread is obtained through the use of TimerQueue API which I use to implement periodic tasks. As a sidenote: I found TimerQueues the easiest way to implement periodic tasks but since these...
If you do this, make sure you return things to how they were every time you release a thread back to the pool. Since you don't own those threads and other code which uses them may have other requirements/assumptions. Are you sure you actually need to do this, though? It's very, very rare to need to set processor affini...
4,268,208
4,268,226
Getting SIGSEGV when stack overflow happens in c++
So I recently made a code that handles SIGSEGV signals when it happens, such as when trying to use unitialised pointers. However, for some reason, stack overflows (as indicated by valgrind) fails to call the SIGSEGV signal handler. Is this standard behavior, or is it just a GCC quirk? Also, since I've been using backtr...
There's no such thing as either a stack overflow or a signal in C++, ironically. So this behavior you see is a platform-specific manifestation of some undefined behavior somewhere.
4,268,443
4,268,689
Hosting win32 windows in a WPF app?
I've got a legacy c++ win32 application, and extending it using wpf windows does work. But what I want to do is have a WPF window as main window, and not just any old window but a prism shell window. So to my legacy c++ project I want to add a Bootstrapper, shell window, MEF loader, all the bells and whistles. And in t...
Have you seen this?: How WPF uses HWNDs I also recommend reading this: Walkthrough: Hosting a Win32 Control in WPF As you will see there is a host window which will contain the control. The host window can also contain self painted content or whatever you want. You have to override WndProc from HwndHost. May be it is p...
4,268,616
4,268,669
When passing pointers to a class, who should manage the resources?
I'm creating a gui api for games. I have for example a font for each widget in the form of a Font* . Right now I have it so that I do not ever manage the memory of these (for obvious reasons) because I think the user can use smart pointers if they want this memory managed. The con to this is that it is not very idiot p...
It should be the responsibility of the caller to manage the memory of objects that are within the caller's scope. That being said, in this case, you should really use smart pointers because they will deallocate themselves when they are no longer of use.
4,268,734
4,268,761
Iterating over std::map<X,std::vector<Y> > and sorting the vectors
When iterating over std::map<X,std::vector<Y> >, may I sort the vectors, or might that invalidate the iterator? In other words, is the following code okay? typedef std::map<int, std::vector<int> > Map; Map m; for (Map::iterator it = m.begin(); it != m.end(); ++it) { std::sort(it->second.begin(), it->second.end()); } ...
Your code is okay. Iterators from a map are only invalidated when you remove elements from the map. Modifying an element of an STL container never invalidates that container's iterators, only operations on the container itself, like removing or sometimes adding elements.
4,268,809
4,337,150
Testing a qt object using cxxtest framework and valgrind
Is it possible to use cxxunit or any other unit testing framework (excluding QtTestLib) to test qt widgets? If yes, then there are two more questions : How? Since I am running unit tests using valgrind, can this report some errors?
Yes, it should be possible. I'm not sure about cxxunit specifically, but it is theoretically possible. To properly test Qt objects, you will probably need to create/destroy a QApplication object in your global setup and teardown functions. Unless you are specifically testing QApplication functionality, you should on...
4,268,829
4,268,898
C++ Callbacks? Should I use Member Func Pointers/Delegates/Events?
I am entering a realm that is new to me, but basically I need to implement callbacks in C++. I am designing a toolkit for myself to use to simplify my life. Basically it is a .dll plugin that will be exposing a lot of functions to my other .dll plugins. One of these functions is HookEvent(const char *event_name, void *...
If you want generalized event firing Boost.Signals2 might be applicable. The Boost.Signals2 library is an implementation of a managed signals and slots system. Signals represent callbacks with multiple targets, and are also called publishers or events in similar systems. Signals are connected to some set o...
4,268,867
4,269,129
How to handle C++ boost::filesystem functions that return string_type?
I'm trying to compile the following snippet of code: #include <boost/filesystem/path.hpp> //Other includes snipped for brevity boost::filesystem::path inPath("C:\\PathThatDoesNotExist"); std::cout << "Folder \'" << inPath.external_directory_string() << "\' does not exist."; and I'm getting this error: .\PathCheck...
With the mods below, your code compiles OK for me. This applies with or without the #define you mentioned. boost::filesystem::path inpath("C:\\PathThatDoesNotExist"); std::cout << "Folder \'" << inpath.external_directory_string() << "\' does not exist."; What version of Boost, and what compiler are you using? ...
4,268,882
4,269,238
Linking static libraries in visual studio with composite dependencies
Suppose you have two static libraries A and B such that A references methods from B. Is it possible to statically link an executable to A and B such that there are not unresolved symbols in B referenced by A? Here is my situation: When I try to link everything up that way in Visual Studio 2010, there are unresolved sy...
the dependecies should not matter ! they may even be circular ,like A refs B and B refs A. It sounds to me (since you get linker errors) that either you don't have headerfiles for those libs (do you declare funcs from A in B by hand or funcs from B in A) or the headerfiles compile differently in your program and in you...
4,268,886
4,268,956
Initialize a vector array of strings
Would it be possible to initialize a vector array of strings? for example: static std::vector<std::string> v; //declared as a class member I used static just to initialize and fill it with strings. Or should i just fill it in the constructor if it can't be initialized like we do with regular arrays.
Sort of: class some_class { static std::vector<std::string> v; // declaration }; const char *vinit[] = {"one", "two", "three"}; std::vector<std::string> some_class::v(vinit, end(vinit)); // definition end is just so I don't have to write vinit+3 and keep it up to date if the length changes later. Define it as: t...
4,269,034
4,269,064
What is the meaning of prepended double colon "::"?
I found this line of a code in a class which I have to modify: ::Configuration * tmpCo = m_configurationDB;//pointer to current db and I don't know what exactly means the double colon prepended to the class name. Without that I would read: declaration of tmpCo as a pointer to an object of the class Configuration... bu...
This ensures that resolution occurs from the global namespace, instead of starting at the namespace you're currently in. For instance, if you had two different classes called Configuration as such: class Configuration; // class 1, in global namespace namespace MyApp { class Configuration; // class 2, different from...
4,269,054
4,269,860
gdi+ GetWorldTransform() where is it in directx?
so im arguing with my friend about GetWorldTransform(). im saying that this DEVICE->GetTransform(D3DTS_WORLD, &matWorld); is the same as GetWorldTransform() in gdi+. am i right or wrong? if im wrong what is it than in directx?
Well, AFAIK GDI+ is 2D and DirectX is 3D. so they are not equal in that matter, and continuing on that, there wouldn't be a match either. So according to me: am i right or wrong? You are wrong. if im wrong what is it than in directx? There is no equivalent.
4,269,069
4,269,119
finding cube root in C++?
Strange things happen when i try to find the cube root of a number. The following code returns me undefined. In cmd : -1.#IND cout<<pow(( double )(20.0*(-3.2) + 30.0),( double )1/3) While this one works perfectly fine. In cmd : 4.93242414866094 cout<<pow(( double )(20.0*4.5 + 30.0),( double )1/3) From mathematical w...
pow(x, y) from <cmath> does NOT work if x is negative and y is non-integral. This is a limitation of std::pow, as documented in the C standard and on cppreference: Error handling Errors are reported as specified in math_errhandling If base is finite and negative and exp is finite and non-integer, a domain error occur...
4,269,104
4,269,329
How to execute a method in another thread?
I'm looking for a solution for this problem in C or C++. edit: To clarify. This is on a linux system. Linux-specific solutions are absolutely fine. Cross-plaform is not a concern. I have a service that runs in its own thread. This service is a class with several methods, some of which need to run in the own service's t...
There are several ways to achieve this, depending upon the complexity you want to accept. Complexity of the code is directly proportional to the flexibility desired. Here's a simple one (and quite well used): Define a classes corresponding to each functionality your server exposes. Each of these classes implements a fu...
4,269,365
4,269,386
Do enum values behave like global variables?
I have two enums, and if there is one value in one enum with the same name as a value in the other enum: enum A {joe, bob, doc}; enum B {sunday, monday, doc}; The compiler (Visual Studio's) complains about redefinition of doc, which implies it treats it as a global variable. Is this so? It is not the behavior I would ...
Enumerators in C++03 have the same scope as the enumeration . enum xxx { yyy, zzz }; ^ ^ ^ enumeration enumerator enumerator This is sometimes convenient, sometimes not really. In C++0x we will have enum classes which are more like C#'s enums. In the meantime...
4,269,382
4,269,398
Is a pointer guaranteed to stay the same no matter how many times you new and delete it?
Here in the following example: AguiWidget::setGlobalFont(segoe); label->setFont(AguiWidget::getGlobalFont()); label->resizeToText(); delete segoe; segoe = 0; segoe = new AguiFont(std::string("test.ttf"),24); I would have expected label to crash because label's font = globalFont which is = to segoe. Will this alwa...
No, when you call new and assign the pointer to a different object, the pointer may now point to a completely different memory address. The old memory address is now invalid (since you called delete on it), and any other code which uses that address is now using what's known as a "dangling pointer". A "dangling poin...
4,269,542
4,269,594
Activate Run the libLAS C++ library within R
I would like to use the libLAS C/C++ library functions within R to import, analyse, export terrestrial lidar data. libLAS is a C/C++ library for reading and writing the very common LAS LiDAR format ( http://liblas.org/index.html ). Would it be possible to use the Rcpp package to run this library (or other packages)? ht...
For the question Would it be possible to use the Rcpp package to run this library (or other packages)? the answer is whopping Yup! as using it for glueing R to a given C/C++ library was pretty much the reason Rcpp was written for. Come and see the documentation and/or the rcpp-devel list for examples. There is ...
4,270,118
4,270,162
Assignment operator could not be generated even when I overload the = operator
My class is polymorphic and should not be used to be ='d anyways. It has a member which is of type Font& and as a result the compiler cannot generate an = operator. So I just created dummy implementations of the assignment and copy constructor, put them in the private of the class, but it still warns me about assignmen...
The assignment operator that the compiler is warning you about is the one for your own class. What you have now is: AguiWidget& operator=(const AguiFont &tmp); What you need is: AguiWidget& operator=(const AguiWidget &tmp);
4,270,185
4,273,833
Allocation/Object detail interception & collection problem when user calls operator new
I'm working on a small memory tool which tracks allocations and deallocations, object sizes, object types, and so on. The method I'm using to track source files, line numbers, and object types works like this: #define DEBUG_NEW SourcePacket(__FILE__, __LINE__) * new #define new DEBUG_NEW SourcePacket is just a small ...
We need an expression that's valid when prefixed with "operator" and when not. This means we need to define an operator that takes a SourcePacket. It could take other arguments, but it turns out this isn't necessary. Unary operator * will do nicely: const SourcePacket& operator *(const SourcePacket& sp) { return s...
4,270,249
4,270,328
Connect without object
I want to connect some function as slot without class, can I do this: void update() { } int main() { QTimer timer = ...; QObject::connect(timer, SIGNAL(timeout()), SLOT(update())); return 0; } The compiler says, that without object it's impossible.
AFAIK, you can only connect signals to slots, and slots can only exist as member functions of a Q_OBJECT. While many people focus on the template vs. moc difference between Qt signals and boost::signals or GTKmm signals, THIS is the difference I ultimately care more about. Qt's signals are not as expressive and cause ...
4,270,316
4,270,339
Meaning of notations like _NAME, __NAME, _NAME_, __NAME__
I've seen this in countless C/C++ header and source files. Apart from personal preference, what's the meaning of each of these different notations? _NAME __NAME _NAME_ __NAME__ NAME_t Quite honestly, the only one I comprehend is _NAME, which is a private member of a class (at least in C# it is). Can someone expla...
Names that begin with _ or __ are typically for reserved identifiers, and you should not define/create identifiers that begin with that convention. (_ with Upper Case following) From C99 standard, 7.1.3 - "Reserved Identifiers" — All identifiers that begin with an underscore and either an uppercase letter or another ...
4,270,505
4,270,585
C++: How to check which datatype used in a template function?
I need to use different functions for each type, but most of the code remains unchanged. How do i test which datatype (or structs) i received to my template function parameter?
How do i test which datatype (or structs) i received to my template function parameter? Why should you? If you want to use a template, it's because the code is the same for every type. Otherwise you just use regular overloaded functions. On the other hand, if you have just a part of the algorithm that needs to be type-...
4,270,589
4,270,606
Checking for a null reference?
Lets say you have something like this: int& refint; int* foo =0; refint = *foo; How could you verify if the reference is NULL to avoid a crash?
You can't late-initialize a reference like that. It has to be initialized when it's declared. On Visual C++ I get error C2530: 'refint' : references must be initialized with your code. If you 'fix' the code, the crash (strictly, undefined behaviour) happens at reference usage time in VC++ v10. int* foo = 0; in...
4,270,673
4,270,876
C/C++ - Windows - how to keep track of HWND context data
In Windows, suppose you have multiple windows (HWNDs) of the same window class open. How do you keep track of the context data in the window procedure so that, for example, window 1 does not get modified when the user tried to type in window 2? CreateWindow() does not return until after the WndProc() has been called se...
if I'm understanding you correctly, you want to avoid one window to catch the messages from another. One way to avoid this is to use the solution proposed in this thread, which keeps track of the windows that is created by you and makes sure that the correct windows gets the messages associated to it by storing the poi...
4,270,720
4,270,749
How to call a template method?
There are a lot of online documents explaining how to write template methods, but not much example about how to call them, how to use them in code. I have a template method like this: VectorConvertor.h template <class T> static void AppendToVector(std::vector<T> & VectorToBeAppended, std::ve...
In C++ you can't separate the definition in a .cpp file when using templates. You need to put the definition in the header file. See: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12
4,270,902
4,270,917
Dangling reference. Alternatives for dangling pointers and references?
The following code produces dangling references: int main() { int *myArray = new int[2]{ 100, 200 }; int &ref = myArray[0]; delete[] myArray; cout << ref; // Use of dangling reference. } I know I shouldn't delete the array but in a large program what if somebody deletes memory to which I have a reference? Ca...
Don't delete the memory before you have finished with it. Sounds stupid, but that's your only protection - properly understand who owns the memory behind each variable, and when it can safely be freed. Smart pointers can help, but the above still applies. It's possible some static analysis tools could identify the tr...
4,270,955
4,271,002
C++: How to use same datatype with two different names in two different overloaded functions?
I have the following declaration to distinct that it uses different operations in my code: typedef unsigned int SOMEIDTYPE; Now when i create two overloaded functions: string something(const unsigned int &val){ ... itoa(val) ... } string something(const SOMEIDTYPE &val){ ... IDTABLE[val] ... } I get error: error C208...
A typedef only creates a nickname -- it doesn't create a new type. If you really want to do something like this, then you need to create a new type. You could create a class for this purpose, but in order for that class to behave like an int, you'd need to do some work: class SOMEIDTYPE { public: SOMEIDTYPE(); SOM...
4,270,973
4,271,086
C++ shader optimization question
Could someone explain me the pretty basics of pixel and vertex shader interaction. The obvious things are that vertex shaders receive basic vertex properties and then repass some of them to the actual pixel shader. But how does the actual vertex->pixel transition happens? I know that obviously all types of pipelines in...
The vertex shader is executed once for every vertex. It allows you to transform the vertex from world space coordinates (or whichever other coordinate system it might be in) into screenspace coordinates. That is, if you have a triangle, each vertex is transformed, so it ends up with a position on the screen. And given ...
4,271,130
4,271,162
C++: is push_back(new Object()) a memory leak?
Is the following C++ code a memory leak? list.push_back(new String("hi")); As I understand it, push_back from any std collection/container always makes a copy. So if the new string is copied, nothing can ever delete the new'd string right? since there is no reference to it after the push_back... Am I correct or wron...
No, the vector stores pointers and the copy is made of the pointer. You can delete the object any time later. (You may get a leak, if the statement happens to throw an exception and you don't catch and handle it properly. That's why you might consider using smart pointers.)
4,271,163
4,271,376
‘virtual char std::ctype<wchar_t>::do_narrow(wchar_t, char) const’ is protected
I'm trying to convert wstring to string with use of locale facets but I got stuck on following error: test_facet.cpp: In function ‘int main()’: test_facet.cpp:14: error: invalid initialization of reference of type ‘std::ctype<wchar_t>&’ from expression of type ‘const std::ctype<wchar_t>’ /usr/include/c++/4.4/bits/local...
2 things: 1) use_facet returns reference to const, so you can't assign it to a non-const one. So declare ct as: const ctype<wchar_t> &ct = .... 2) As the second error message states, do_narrow is protected, making it unaccessible to external callers. Use narrowinstead, which is public.
4,271,214
4,271,237
Why can my object not access it's own private member variable? [C++]
I have a class called class Car, which has be instantiated as the object Car car1. One of the member variables of Car is Car::width, but when I try to execute the line cout << car1.width << endl; from main() I am told that this is not possible because Car::width is private. It was my understanding that private members...
Private members are accessible by the methods of the same class to which they belong.
4,271,245
4,271,276
Why do I get no matching function when I inherit this function
Possible Duplicate: overloaded functions are hidden in derived class I have Class A and Class B (subclass of A) Class A has function virtual void foo(int, int); virtual void foo(int, int, int); When I try to do Class B with function virtual void foo(int, int); When I try to call foo(int, int, int) with the class t...
The reason why has to do with the way C++ does name lookup and overload resolution. C++ will start at the expression type and lookup upwards until it finds a member matching the specified name. It will then only consider overloads of the member with that name in the discovered type. Hence in this scenario it only co...
4,271,315
4,272,110
C++ How to check an input float variable for valid input
I'm writing a program that acts as a calculator; based on the character input by the user it performs a certain operation. The structure of the program seems to work fine, but I'd like to be able to check for erroneous input. After receiving the float variable, is there any way to check if it does not contain any chara...
To detect erroneous string input where you expected a number, C++ doesn't automatically know what you want, so one solution is to first accept your input as strings, validate those strings, then if valid, only then convert the strings to float numbers using the atof() function. The standard string class has a function ...
4,271,489
4,271,858
How to use cv::imdecode, if the contents of an image file are in a char array?
I have a jpeg image in buffer jpegBuffer. I'm trying to pass it to cv::imdecode function: Mat matrixJprg = imdecode(Mat(jpegBuffer), 1); I get this error: /home/richard/Desktop/richard/client/src/main.cc:108: error: no matching function for call to ‘cv::Mat::Mat(char*&)’ This is how I fill jpegBuffer: FILE* pFile; lo...
Mat has no constructor that takes a char* argument. Try this instead: std::ifstream file("img.jpg"); std::vector<char> data; file >> std::noskipws; std::copy(std::istream_iterator<char>(file), std::istream_iterator<char>(), std::back_inserter(data)); Mat matrixJprg = imdecode(Mat(data), 1); EDIT: You should also tak...
4,271,562
4,272,095
Error on std::pair when compiling for mac / linux
I have a problem when compiling my code under Mac OS. This function declaration in my header file apparently causes some errors (it does work fine under Windows, though): #include <string> #include <vector> #include <map> #ifdef WIN32 #include <windows.h> #endif [...] int setProcessEnvironment( const...
this was pointed out by André Caron: Out of curiosity, can you typedef std::vector< std::pair > EnvironmentBlock; (change the name to your liking). Replace the two instances in your function declaration. See if that clears up any parsing errors. I am now declaring typedef std::vector< std::pair<const wchar_...
4,271,881
4,272,301
Newbie problem with gcc 4.2 compiler (Mac OSX): fpu_control.h: No such file or directory
I am trying to compile a program in c/c++, but am getting the error message: fpu_control.h: No such file or directory From google, I have found out that this problem is about the way floating point precision is handled. I read that not all distributions of gcc include fpu_control.h. This is the only thing I can find...
Apple doesn't support setting the FPU flags, and doing so isn't needed. The reason is that they don't even use the i387 coprocessor for float and double, but SSE. The last reference also explains how to revert that approach, and how to perform FPU control using inline assembly.
4,271,928
4,271,936
Package for pre-compiled boost libraries (Ubuntu)
I'm trying to find the right boost package that comes pre-compiled as well. (For Ubuntu Lucid 10.04) I tried: sudo apt-get install libboost-dev-all I'm aware that most of boost is header only, but it looks like I don't have any lib files? I only got the files in /usr/include/boost/ Which package gives me the library f...
Look in /usr/lib for files beginning with 'libboost'.
4,272,432
4,272,499
c++ undefined reference to vtable
I'm learning C++. I'm trying to do an exercise where I define several implementations of a pure virtual class with a single function. I'm having trouble linking the class that uses these implementations. ==> BasicMath.h <== #ifndef BASIC_MATH_H #define BASIC_MATH_H #include<string> #include<vector> class BasicMat...
You're not including the Sum.o object file on your compile&link line (second g++ use).
4,272,445
4,272,457
How to convert char* to std::vector?
I have a char* variable: // char* buffer; // ... fread (buffer, 1, lSize, pFile); // ... How can I convert it to std::vector? Casting will get me an error.
Why not use a std::vector to begin with: std::vector<char> buffer(lSize); std::fread(&buffer[0], 1, buffer.size(), pFile);
4,272,641
4,272,760
Trying Favorite Tries: Radix, Suffix, and Hash! Even Ternaries, oh my!
So, I'm trying to pull together a collection of excellent datastructure implementations, partly for my personal collection, partly to try and build a larger set of highly optimized structures for somewhat specialized purposes. Part of this stems from the agony that deque and set inflicted with unexpected overheads and...
There are several PATRICIA trie implementations.
4,272,727
4,272,819
Rakefile rules in c++ project
I'm converting Makefile to Rakefile for small C++ project. I have src dir with *.h and *.cpp files and obj dir where all *.o goes (I don't want them in src). How to do it with Rake rules? This works fine but I want to have a generic rule. rule("#{OBJ_DIR}hello.o" => "#{SRC_DIR}hello.cpp") do |target| This returns "Don...
Copied shamelessly from here rule '.o' => '.cpp' do |target| sh "#{COMPILER} #{FLAGS} -c -o #{target.name} #{target.source}" end Maybe the problem lies in the fact that your example tries to mix where certain files are located, with the rule needed to handle any file with some extension regardless of it's location....
4,272,876
4,272,976
OpenSSL - SSL_CTX_set_default_passwd_cb
I'm needing to write a simple SSL client application to query the Amazon Web Service from C++. It's going to be used in multi-threaded applications. This is the first time I've ever looked at using OpenSSL and I'm needing to extend some of our our libraries to support SSL sockets. My question is: What is the purpose o...
According to this article, This callback is called when a password is required to decrypt an encrypted private key
4,272,901
4,272,971
C++ stable_partition Compiler Error
I'm trying to extend an example I found in Koenig and Moo's "Accelerated C++." I've got the following code which attempts to split a vector into two partitions. #include <algorithm> #include <vector> #include <iostream> using namespace std; struct MyClass { int* MyInt; MyClass() : MyInt(NULL) {} }; struct A...
The problem is that sameBaseReg is a member function of AnalyzeMemOps. You can't use it like an ordinary non-member function because it can only be called on an object. If you have a modern compiler that supports C++0x, C++ TR1, or if you have Boost handy, you can use bind to bind the pointer to member function to the...
4,272,902
4,274,252
Writing a Windows Media Center Plugin with C++
I have been searching for a way to create a windows media center plugin with C++, does anyone know if this is possible (with current available tools)? I have the SDK for C#, but would really rather stick to C++ if it all possible. Thanks for your help!
You could always use C++/CLI, either for the whole thing or just to create a thin shim between Media Center and your unmanaged C++. C++/CLI is rarely used but it is fantastic for creating a bridge between the managed and unmanaged worlds. It's much better than the old Managed C++, if the thought of that has put you off...
4,272,909
4,273,271
Is it safe to "upcast" a method pointer and use it with base class pointer?
Let's say I have a pointer type that can hold the address of a base class method. Can I assign the address of a subclass method to it and expect it to work correctly? In my case I'm using it with a base class pointer and the dynamic type of the object is the derived class. struct B { typedef void (B::*MethodPtr)();...
It's valid. If class B contains the original member, B doesn't contain D::Foo, so no. or is a base [...] of the class containing the original member B is a base of D, so this holds. As a result: the resulting pointer to member points to the original member Clause 5.2.9 9 says you can upcast only if you can also d...
4,272,931
4,272,961
C++ Win32 API include <string>
I'm trying without any luck to include strings in my C++ Win32 API beginner project. The code won't compile if I define a string. What's going on? Details: I was working in Dev C++, but now have switched to Code::Blocks using the (default?) "Gnu GCC Compiler". Here are the code cases I have tried, all similar, with ...
Does the source file have a .cpp extension? If it's .c, it will compile as C code, which probably excludes the directories containing the standard C++ headers.
4,272,939
4,274,236
Inverse Heisenbug - Unit test fails only when debugger is attached
I recently fixed a defect in our product, the symptom of which was an access violation caused by accessing a dangling pointer. For good practice I added a unit test to ensure that the bug doesn't come back. When writing a unit test I will always back out my defect fix and ensure the unit test fails, otherwise I know i...
I have isolated the cause of this problem - see this question for details. When running my test harness under the debugger, the memory consumed by the debugging environment meant that subsequent allocations/deallocations of the same object were always allocated in different parts of memory. This meant that when my tes...
4,272,949
4,273,104
Using appropriate data types (path, string, etc.) with boost::filesystem in C++ to efficiently iterate files, change filenames, and do file operations
The following code loops through files in "sourcepath" and copies them to "destpath". If they exist, they are renamed as "Copy of" the original filename. Do I really need this much code for this? I get the feeling I'm doing way too much back-and-forth converting between strings and paths, but I'm not sure how else to...
path objects have overloaded / operator, which appends the second operand with a separator to the path. Your std::string strSourceFilename(pathSource.string() + "/" + iterDir->filename()); std::string strDestFilename(pathDest.string() + "/" + iterDir->filename()); bfs::path pathSourceFilename(strSourceFilenam...
4,272,994
4,273,036
C++ asynchronous network programming
I have some simple questions, I have a client-server application and data sent on the wire. I'd like to be able to recover the data and handle it properly. struct T1 { int id; int foo; }; struct T2 { int id; char foo; int bar; }; Let's take these structures, they are sent on the network preceded by an int...
EDIT: Thanks to @timo for pointing out a mistake. async_read won't complete until an entire struct is read, so you don't need to loop. Otherwise, my answer is the same. Nothing will be lost, regardless of how the TCP protocol breaks up or coalesces the data. If there isn't enough data in the TCP buffers to fill your in...
4,272,998
4,273,015
Preventing others from calling a function based on a condition, but always allowing the class to call it?
I wasn't sure how to call this. Basically I have a Label widget. It has an auto size feature. The problem is I do not know who calls setSize(); I need to know if the class called it or if the user of the label called it because you cannot resize an auto sizing widget. I cannot directly change the size because, well 1, ...
Move the implementation into a (renamed) private method, make setSize() into a wrapper that checks the condition.
4,273,056
4,273,072
JSONCPP Not reading files correctly
So I recently installed JSONCPP and for some reason it gives me errors when I try this code: #include <json.h> #include <iostream> #include <fstream> int main(){ bool alive = true; while (alive){ Json::Value root; // will contains the root value after parsing. Json::Reader reader; std::string tes...
See the Json::Reader::parse documentation. For that overload, the string needs to be the actual document, not the filename. You can use the istream overload with a ifstream instead. std::ifstream test("testis.json", std::ifstream::binary); EDIT: I got it work with: #include "json/json.h" #include <iostream> #include ...
4,273,057
4,273,294
Is there a list of STL container methods that may throw an exception anywhere?
I know the STL will throw on a memory allocation error or if the contained type throws in its constructor / assignment operator. Otherwise, apparently 'a few' STL methods can throw other exceptions. The example everyone seems to mention is vector::at(), but I can't find a list of the others anywhere. Does anyone know o...
Won't be 100% accurate, and is for C++03, but a half-hour effort based on grepping through GCC 4.3.4 includes, ignoring tr1 and ext but including iostream. Crucially, some of these checks might be due to this implementation prefering more defensive coding, and might not be mandated in the Standard and available univer...
4,273,370
4,273,397
Creating a native application for X86?
Is there a way I could make a C or C++ program that would run without an operating system and that would draw something like a red pixel to the top left corner? I have always wondered how these types of applications are made. Since Windows is written in C I imagine there is a way to do this. Thanks
If you're writing for a bare processor, with no library support at all, you'll have to get all the hardware manuals, figure out how to access your video memory, and perform whatever operations that hardware requires to get a pixel drawn onto the display (or a sound on the beeper, or a block of memory read from the disk...
4,273,375
4,273,388
Why is the C++ std::exception::what member const?
I'm curious as to why the std::exception::what member function is const? class exception { public: exception() throw() { } virtual ~exception() throw(); /** Returns a C-style character string describing the general cause * of the current error. */ virtual const char* what() const throw(); };
Calling the what() member function should not modify the observable state of the exception object. Typically, exceptions are caught by const reference. For example, try { // ... } catch (const std::exception& ex) { std::cout << ex.what(); } If the what() member function was not const-qualified, this pattern w...
4,273,429
4,273,474
How to set a file's last access time on Win32 in C++ using FILETIME/SYSTEMTIME or boost?
I have some code that deletes some files based on time_t comparisons with the last access date, and am looking for how to write a SetLastAccessTime method to use in my unit test. Here's my Get: bool GetLastAccessTime(const std::string &filename, time_t& lastAccessTime) { WIN32_FIND_DATA FindFileData; HANDLE hFi...
From the Win32 API: SetFileTime. As stated in the documentation, you can pass in NULL if you don't want to change the other time stamps. Whatever you're doing, be careful with it. In Vista or more recent forms of Windows, the Last Access Time is not actually modified on access, just on writes, and is therefore an alias...
4,273,509
4,273,585
icon working as base weird icon appearing inside window
I just recently found out how to add an icon to a win32 project after I tried it out the base icon on my application worked fine but when I open the application the actual 16x16 icon in the top left corner is a question mark in a bubble the odd thing is when I accidently forgot to put -mwindows in my compile code the c...
Windows uses the "first" icon resource as application icon. This icon is displayed by Windows Explorer and e.g. a console window, but is not used automatically for windows that you create. Note: as I recall the definition of "first" has varied or was never well-defined in the first place, but typically icon with lowest...
4,273,570
4,273,589
What is the point of Boost::Signals?
Firstly, I am an absolute beginner in programming, so don't make fun of me too much. The only thing that I have seen signals used for are GUI toolkits, and GUI toolkits all come with their own signaling. So, can Boost:Signals even be used with these GUI toolkits? Would this be a good idea? What other applications do si...
Signals is an event messaging implementation, much like Smalltalk/Objective C Messages or Events in various other (e.g. C#) lanugages. You can use them for a wide variety of tasks, take a look at the Observer Pattern Why would you use the Observer Pattern? The benefits are largely organisational, when you work with lar...
4,273,591
4,273,862
Pass a container of smart pointer as argument in C++
I have a function like below void functionA(unordered_map<string, classA*>* arg1); I need to pass in unordered_map<string, shared_ptr<classA>> How could I pass in the container with shared_ptr to the function which takes in a container of raw pointer? I am using C++0x here. Thanks
Since you asked, here's what a template might look like for this function: template <typename MAP_TYPE> void functionA(const MAP_TYPE& arg1) { // Use arg1 here } You could use a pointer and/or make it non-const if you must. As long as the map passed in uses a compatible key type and some kind of pointer to the rig...
4,273,594
4,273,659
Overlapped IO and ERROR_IO_INCOMPLETE
I have had overlapped IO working for 2 years now but ive used it with a new application and its chucking this error at me (when i hide the main form). I have googled but i fail to understand what the error means and how i should handle it? Any ideas? Im using this over NamedPipes and the error happens after calling Get...
ERROR_IO_INCOMPLETE is an error code that means that the Overlapped operation is still in progress; GetOverlappedResult returns false as the operation hasn't succeeded yet. You have two options - blocking and non-blocking: Block until the operation completes: change your GetOverlappedResult call to: BOOL fSuccess = Get...
4,273,622
4,273,681
How to use a single Template statement for more than one function or struct?
I've been trying to represent Stacks as a template, I used a struct and every thing is good, but every time I wanted to write a template function, I had to write the same template statement, which didn't seem correct -although working- So how can I write one template statement for all the functions?, here is my code : ...
If (as appears to be the case based on your comment) you want them as free functions, you can't. You'll also have to change the Stack parameter, something like this: template <typename T> void Push(T Value, Stack<T>* &Top) { Stack * Cell = new Stack(); Cell->Value = Value; Cell->next = Top; Top = Cell; ...
4,274,024
4,279,686
wxGrid Problem in wxWidgets 2.9.1
Hi All I have a code built in wxWidgets 2.6.3 I have complied that code in wxWidgets 2.9.1 But it has given error in using wxGrid Is wxGrid become obselete or whats the problem?
Short Answer: No. wxGrid is still there, with minor changes. Long Answer: 2.6.3 was released in March, 2006, while 2.9.1 just came out back in July, 2010. That's over four years worth of changes. Many things have changed. That aside, 2.9.1 is not intended to be compatible with 2.6.x, and in fact, as noted on the websit...
4,274,058
4,274,180
Is it possible to mark a segment of memory as "out of bounds" so the heap manager doesn't allocate from it?
Earlier today I asked this question. After spending some time investigating this issue, I have discovered what is going on. I am posting this as a new question because I think it is interesting enough to track as a separate issue. I will update that question with the answer (and a link to this one). Launching unit te...
Your unit test is flawed, since it's relying on undefined behavior. You should rewrite your unit test so that it doesn't rely on undefined behavior, in which case it will always pass regardless of how the memory manager decides to allocate memory. What you're doing is this: Object* pObject = new Object(...); ... delet...
4,274,130
4,274,263
REALLY strange error on c++ code. Parameter being copied with a trash value and not the one i wanted
I don't think i could explain how pissed I am because i can't find where i missed here.. Images can explain everything: Debug screenshot, with nxxx value (used to call it n, but that crappy variable doesn't deserve such a cool name). Breakpoint was on first line of this method. http://img202.imageshack.us/img202/5057/v...
It looks like all the values have shifted (Q is 2 instead of 3, q1 is 3 instead of 4, R is 0 instead of 1). Where an int is interpreted as float, weird values are expected. I guess nxxx must be seeing the value meant for B. Is there some mismatch between the definition and declaration of init?