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 |
|---|---|---|---|---|
387,633 | 387,667 | Dispatching exceptions in C++ | How should exceptions be dispatched so that error handling and diagnostics can be handled in a centralized, user-friendly manner?
For example:
A DataHW class handles communication with some data acquisition hardware.
The DataHW class may throw exceptions based on a number of possible errors: intermittent signal, no si... | Avoid duplicating the catch blocks at each call site by catching (...) and calling a shared handler function which rethrows and dispatches:
f()
{
try
{
// something
}
catch (...)
{
handle();
}
}
void handle()
{
try
{
throw;
}
catch (const Foo& e)
{
... |
387,654 | 387,781 | Why is there no Z80 like LDIR functionality in C/C++/rtl? | In Z80 machine code, a cheap technique to initialize a buffer to a fixed value, say all blanks. So a chunk of code might look something like this.
LD HL, DESTINATION ; point to the source
LD DE, DESTINATION + 1 ; point to the destination
LD BC, DESTINATION_SIZE - 1 ; copying this many bytes
LD ... | I believe this goes to the design philosophy of C and C++. As Bjarne Stroustrup once said, one of the major guiding principles of the design of C++ is "What you don’t use, you don’t pay for". And while Dennis Ritchie may not have said it in exactly those same words, I believe that was a guiding principle informing hi... |
387,792 | 388,068 | Vim indentation for c++ templates? | Does anyone have or know about vim plugin/macro/function that indents nicely c++ templates?
When I highlight template definition in vim .hpp/.h file and indent it with '=' I get something like this:
> template <
> class TFilter,
> class TParser,
> class TConsumer,
> ... | You can use the identexpr option to specify indent by evaluating an expression (i.e. writing a vim script function). This function should accept a string -- the line -- and return the number of spaces to indent. This gives you the flexibility to return an indent level for this template condition, or fall-back to autoin... |
387,936 | 389,299 | How to detect leaks under WinCE C/C+ runtime library? | I know the possibilities of basic leak detection for Win32 using the crtdbg.h header, but this header is unavailable in the CE CRT library headers (i'm using the lastest SDK v6.1).
Anyone knows how I can automatically detect leaks in a WinCE/ARMV4I configuration with VC 9.0? I don't want to override new/delete for my ... | At work (developing WindowsCE based OS + Applications) we have created our own memory manager, roughly based on the Fluid Studios Memory Manager (the link which I found using SO!). I'm pretty sure with a few simple modifications you could adapt it to use on your platform.
Basically it doesn't override new and delete, b... |
388,200 | 388,305 | Architectural Suggestions in a Linux App | I've done quite a bit of programming on Windows but now I have to write my first Linux app.
I need to talk to a hardware device using UDP. I have to send 60 packets a second with a size of 40 bytes. If I send less than 60 packets within 1 second, bad things will happen.
The data for the packets may take a while to gen... | I posted this answer to illustrate a quite different approach to the "obvious" one, in the hope that someone discovers it to be exactly what they need. I didn't expect it to be selected as the best answer! Treat this solution with caution, because there are potential dangers and concurrency issues...
You can use the se... |
388,878 | 388,988 | Registering derived classes in C++ | EDIT: minor fixes (virtual Print; return mpInstance) following remarks in the answers.
I am trying to create a system in which I can derive a Child class from any Base class, and its implementation should replace the implementation of the base class.
All the objects that create and use the base class objects shouldn't ... | This sort of pattern is fairly common. I'm not a C++ expert but in Java you see this everywhere. The dynamic cast appears to be necessary because the compiler can't tell what kind of factory you've stored in the map. To my knowledge there isn't much you can do about that with the current design. It would help to kn... |
388,934 | 389,053 | Aligning Member Variables By Template Type | I want to align my member variables based on a class template type but I'm not sure if it is actually possible.
The following is a (very) simple example of what I'd like to do
template<int Align>
class MyClass
{
private:
struct MyStruct
{
// Some stuff
} __declspec(align(Align));
__declspec(align(Align)) i... | Custom alignment isn't in the standard, so how the compilers deal with it is up to them - looks like VC++ doesn't like combining templates with __declspec.
I suggest a work-around using specialisation, something like this:
template<int A> struct aligned;
template<> struct aligned<1> { } __declspec(align(1));
template<>... |
389,069 | 389,074 | Programmatically reading a web page | I want to write a program in C/C++ that will dynamically read a web page and extract information from it. As an example imagine if you wanted to write an application to follow and log an ebay auction. Is there an easy way to grab the web page? A library which provides this functionality? And is there an easy way to par... | Have a look at the cURL library:
#include <stdio.h>
#include <curl/curl.h>
int main(void)
{
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "curl.haxx.se");
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl... |
389,244 | 389,338 | Best way to use a VB.NET class library from a C++ DLL? | I need to use one of my VB.NET projects in a C++ project. The interface between the two will be for the C++ code to instantiate and call methods on one of the .NET assembly objects.
Both compile to DLLs (and then the C++ DLL is loaded from the NTVDM as a VDD, but that's probably not relevant.)
If possible I would like ... | Do you really need native C++ or can you use C++/CLI?
If you can do it all in C++/CLI, then you'll end up with a pure .NET application.
If you need 'native' C++, then you can create an assembly that includes managed and unmanaged C++ directly from Visual Studio (the native C++ calls C++/CLI which then calls through to ... |
389,922 | 389,944 | C++ namespace and include | Why do we need both using namespace and include directives in C++ programs?
For example,
#include <iostream>
using namespace std;
int main() {
cout << "Hello world";
}
Why is it not enough to just have #include <iostream> or just have using namespace std and get rid of the other?
(I am thinking of an analogy with ... | In C++ the concepts are separate. This is by design and useful.
You can include things that without namespaces would be ambiguous.
With namespaces you can refer to two different classes that have the same name. Of course in that case you would not use the using directive or if you did you would have to specify the na... |
389,957 | 389,963 | Forward Declaration of a Base Class | I'm trying to create proper header files which don't include too many other files to keep them clean and to speed up compile time.
I encountered two problems while doing this:
Forward declaration on base classes doesn't work.
class B;
class A : public B
{
// ...
}
Forward declaration on STD classes doesn't work... | The first problem you can't solve.
The second problem is not anything to do with standard library classes. It's because you declare an instance of the class as a member of your own class.
Both problems are due to the requirement that the compiler must be able to find out the total size of a class from its definition.
H... |
390,102 | 390,163 | Memory allocation and deallocation across threads | I'm still trying to debug a very sneaky memory corruption problem. I came across a section of my code that allocates memory on one thread and deletes it on another.
I have a vague feeling that this is wrong, but I'm not sure why. The threads share the process memory and access to these structures is protected by a mute... | As indicated in another answer by @monjardin, there is nothing inherently wrong with what you are trying to do.
As an additional thought, you didn't mention the platform, etc. you are running into this problem on but if multi-threading is new to you and/or this application you are working on, you want to be sure that t... |
390,615 | 390,623 | Implementation of finally in C++ | Is this a good way to implement a Finally-like behavior in standard C++?
(Without special pointers)
class Exception : public Exception
{ public: virtual bool isException() { return true; } };
class NoException : public Exception
{ public: bool isException() { return false; } };
Object *myObject = 0;
try
{
... | The standard answer is to use some variant of resource-allocation-is-initialization abbreviated RAII. Basically you construct a variable that has the same scope as the block that would be inside the block before the finally, then do the work in the finally block inside the objects destructor.
try {
// Some work
}
f... |
390,789 | 391,097 | keep a formless application from closing for a keyboard hook | I am working on a c++ win32 program that involves a keyboard hook. The application is a win32 project with no user interface whatsoever. I need to keep the application from closing without using causing the hook to not work or use up a bunch of system resources. I used to use a message box but I need the application to... | I think what you need is message only window
(MSDN says) A message-only window enables you to send and receive messages. It is not visible, has no z-order, cannot be enumerated, and does not receive broadcast messages. The window simply dispatches messages.
|
390,997 | 391,015 | When virtual doesn't work | I have a weird error in my C++ classes at the moment. I have an ActiveX wrapper class (as part of wxWidgets) that i added a new virtual function to. I have another class that inherits from the ActiveX one (wxIEHtmlWin) however the ActiveX class always calls its own function instead of the one in wxIEHtmlWin which overr... | You are calling the virtual method from within the class's constructor (via another call). This will call the method on the current class as the sub-class hasn't been constructed yet. The fix is to use an init() method and call it after constructing the class.
i.e something like this:
class wxActivex {
wxActivex() {}... |
391,022 | 391,675 | Local WideString variable debug error "Int3 DbgBreakPoint" | In C++Builder, I wrote the following code (in Button1Click handler), When I run in debug mode, I get the "Int3 DbgBreakPoint" (Stack corrupted?). This doesn't happen for AnsiSting (Maybe reference counting).
WideString boshluq;
boshluq=L" ";
Is this normal? What do you suggest me to fix this code?
| WideStrings are pointer referenced variables for Windows WideStrings, maybe the problem is in your windows system library.
I have the same problem with breakpoint in the ntdll.dll, I dont know if it is the same for you.
I solve with this unit http://www.tbosystems.bluehosting.com.br/dbx4/int3.pas (Thanks to Leonel Tog... |
391,125 | 391,324 | How to change pane text of status bar from a thread in MFC? | I have a dialog in MFC with a CStatusBar. In a separate thread, I want to change the pane text of status bar. However MFC complains with asserts? How is it done? An example code would be great.
| You could post a private message to the main frame window and 'ask' it to update the status bar. The thread would need the main window handle (don't use the CWnd object as it won't be thread safe). Here is some sample code:
static UINT CMainFrame::UpdateStatusBarProc(LPVOID pParam);
void CMainFrame::OnCreateTestThre... |
391,532 | 391,615 | Send HTTP request from VC++ file | I am trying to send an HTTP request with the contents of a file set as the body of the HTTP request and want to get the response from a server using VC++.
Any help is appreciated. Thanks.
I think I was not very clear with what I wanted to do or I misunderstood the answers. Neways, what I want to accomplish is, one of m... | You can use cURL library. There is also a similar topic Programmatically reading a web page
|
391,553 | 391,567 | Is there any cheatsheet available for C++? | What do you like to have in the C++ cheat sheet?
| I found this one that seems to be detailed enough.
It covers basics of templates, inheritance, operators, exceptions, etc. It has a lot of information in a very small space.
|
391,595 | 391,616 | When is it OK to throw an exception from a destructor in C++? | I know the rule is to NEVER throw one during a destructor, and I understand why. I would not dare do it. But even the C++ Faq Lite says that this rule is good 99% of the time. What is the other 1% that they fail to delve into?
Link to the C++ Faq Lite bullet point on throwing from ~():
| Just don't do it.
If the stars and planets align in such a way that you find you need to...
Still don't do it.
|
391,693 | 391,745 | Strange DLL + InterropServices problem | I'm trying to learn the basics of tying up unmanaged C++ and .NET. So, I've got the DLL compiled and callable from C#. Great. Now I run into this weird problem:
Here's my C++ file, Main.cpp:
#include <stdio.h>
extern "C" __declspec(dllexport) void DisplayHelloFromDLL()
{
printf ("Hello from the World of 1986!\n");... | Well I see the same behavior here, and I can't fully explain it. However I think that trying to run in debug mode (F5) against a Release build, you should expect undefined behavior. If I use ctrl-F5 it runs properly.
Since that's working, we can deduce that the binary is correctly built, so there's no compiler issue,... |
391,756 | 391,763 | Can an anonymous object be declared static in C++? | Is this allowed? :
class A;
void foo()
{
static A();
}
I get signal 11 when I try to do it, but the following works fine:
class A;
void foo()
{
static A a;
}
Thank you.
| Nope. There is no such thing as an "anonymous object" in C++. There is such a thing as defining an object to type A that is immediately discarded; what you've written is an expression that returns an A object that's never assigned to a variable, like the return code of printf usually is never assigned or used.
In tha... |
391,772 | 391,941 | How do I append children to QDomDocumentFragment object in qt with c++ | I'm using qt 4.4.3 with c++. I want to implement a QDomDocumentFragment object, and pass it as a return value for a function. I am using it the same way as QDomElement objects, with appendChild():
QDomDocumentFragment rootnode;
QDomNode initmodnode = doc.createElement("initmod");
QDomText initmodval = doc.createTextNo... | Ok sorry for wasting everyone's time.. looks like I needed to create the document fragment using:
QDomDocumentFragment rootnode = doc.createDocumentFragment();
|
391,917 | 613,488 | JPEG support with ijg - getting access violation | I was recently trying to update my game to store graphics in compressed formats (JPEG and PNG).
Whilst I ended up settling on a different library, my initial attempt was to incorporate ijg to do JPEG decompression. However, I was unable to get even the simplest console application to work and am wondering if anyone mig... | I've just encountered the same problem (although I was trying to encode an image).
Apparently, FILE* are not portable between DLLs so you can't use any libjpeg API that takes a FILE* as a parameter.
There are several solutions, but they all come down to having to rebuild the library:
Build the library as a static lib,... |
392,120 | 392,138 | Why can't I declare a friend through a typedef? | Does anyone know why typedefs of class names don't work like class names for the friend declaration?
class A
{
public:
};
class B : public A
{
public:
typedef A SUPERCLASS;
};
typedef A X;
class C
{
public:
friend class A; // OK
friend class X; // fails
friend class B::SUPERCLASS;... | It can't, currently. I don't know the reason yet (just looking it up, because i find it interesting). Update: you can find the reason in the first proposal to support typedef-names as friends: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2003/n1520.pdf . The reason is that the Standard only supported elaborated-t... |
392,142 | 392,148 | How would you list the available functions etc contained within a compiled library? | How do I determine whether a function exists within a library, or list out the functions in a compiled library?
| You can use the nm command to list the symbols in static libraries.
nm -g -C <libMylib.a>
|
392,359 | 392,365 | How to force a template code creation without creating object instance? | I have a template class that is only valid for couple of template parameters:
doIt.h:
// only int and float are valid T
template <typename T>
class doer
{
public:
void doIt();
}
I want to hide the implementation inside the .cpp file (for faster compile and also because its proprietary):
doIt.cpp:
template <>
void d... | See the article How to Organize Template Source Code. I think you are after the second method described there: explicit template instantiation.
|
392,375 | 392,409 | Turn while loop into math equation? | I have two simple while loops in my program that I feel ought to be math equations, but I'm struggling to convert them:
float a = someValue;
int b = someOtherValue;
int c = 0;
while (a <= -b / 2) {
c--;
a += b;
}
while (a >= b / 2) {
c++;
a -= b;
}
This code works as-is, but I feel it could be simplif... | It can be proved that the following is correct:
c = floor((a+b/2)/b)
a = a - c*b
Note that floor means round down, towards negative infinity: not towards 0. (E.g. floor(-3.1)=-4. The floor() library functions will do this; just be sure not to just cast to int, which will usually round towards 0 instead.)
Presumably b ... |
392,540 | 392,548 | Adding parameters for a program at launch | I'm currently trying to make a small application that performs different duties. Right now I have a console app pop up and ask what I want to do, but sometimes I would rather just launch it with something like MyApp.exe -printdocuments or some such thing.
Are there any tutorials out there that can show me a simple exa... | In C++, your main() function can have argc and argv parameters, which contain the arguments passed on the command line. The argc is the count of arguments (including the executable name itself), and argv is an array of pointers to null-terminated strings of length argc.
For example, this program prints its arguments:
#... |
392,932 | 392,946 | How do I use the conditional (ternary) operator? | I've always wondered how to write the "A ? B : C" syntax in a C++ compatible language.
I think it works something like: (Pseudo code)
If A > B
C = A
Else
C = B
Will any veteran C++ programmer please help me out?
| It works like this:
(condition) ? true-clause : false-clause
It's most commonly used in assignment operations, although it has other uses as well. The ternary operator ? is a way of shortening an if-else clause, and is also called an immediate-if statement in other languages (IIf(condition,true-clause,false-clause) in... |
393,241 | 586,334 | Read\write boost::binary_oarchive to pipe | I am continue to build two simple processes throwing class objects one to another (see my previous post) through simple (anonymous) pipes. Now I revealed for myself boost::serialization (thanks answered people) and have tried to make some class be serialized through ::WriteFile::ReadFile. So - what I am doing wrong?
1... | I think the problem here is that you're trying pass a pointer the the archive object in the WriteFile function. What you should do instead is provide a pointer to serialized data.
std::stringstream ss;
boost::archive::binary_oarchive oa(ss);
oa << tc;
::WriteFile(hPipe, ss.str().data(), ss.str().data().size(), &dwWritt... |
393,885 | 393,945 | Neatest / Fastest Algorithm for Smallest Positive Number | Simple question - In c++, what's the neatest way of getting which of two numbers (u0 and u1) is the smallest positive number? (that's still efficient)
Every way I try it involves big if statements or complicated conditional statements.
Thanks,
Dan
Here's a simple example:
bool lowestPositive(int a, int b, int& result)
... | I prefer clarity over compactness:
bool lowestPositive( int a, int b, int& result )
{
if (a > 0 && a <= b) // a is positive and smaller than or equal to b
result = a;
else if (b > 0) // b is positive and either smaller than a or a is negative
result = b;
else
result = a; // at least b is nega... |
393,954 | 395,408 | How to convert an OpenCV IplImage to an SDL_Surface? | I'm trying to write a program which takes an SDL_Surface, converts it to an IplImage, uses the cvBlobsLib to find blobs, paints the blobs as spots back over the image, then converts the output IplImage back to an SDL_Surface.
I'm almost done: only converting the IplImage back to an SDL_Surface hasn't been done yet. Thi... | Ok, I got it working!
I think I was confused by the fact that an OpenCV depth of 8 means a pixel has 8 bits per channel, so in a 3-channel image, a pixel has 24 bits. So when converting that to the SDL meaning of depth, we get 8 * 3 = 24 bits.
The image was 24 bits after all, which SDL supports. So converting the image... |
394,061 | 394,077 | Critical section - to be or not to be? | I`m writing a chat using WinSock2 and WinAPI functions. And I have a little trouble.
I store the std::vector of client connections on server. When new client connects, new thread starts and all work with the client is done in this new thread. I do not use classes (I know it is not very good) so this list of connections... | Yes, you are just lucky never to experience any problems. This is the problem with synchronization issues and race conditions, that the code will work in 99.9% of all cases, and when disaster strikes you won't know why.
I would take away the constructor taking a CRITICAL_SECTION as a parameter since it is not clear wit... |
394,146 | 394,156 | Displaying polymorphic classes | I have an existing app with a command-line interface that I'm adding a GUI to. One situation that often comes up is that I have a list of objects that inherit from one class, and need to be displayed in a list, but each subclass has a slightly different way of being displayed.
Not wanting to have giant switch statemen... | I don't think this will solve your problem of not needing to write the code, but you should be able to abstract the GUI logic from the data objects.
Look at a Visitor pattern (http://en.wikipedia.org/wiki/Visitor_pattern) it will allow you to add code to an existing object without changing the object itself. You can a... |
394,162 | 394,182 | Fastest way to determine whether a string contains a real or integer value | I'm trying to write a function that is able to determine whether a string contains a real or an integer value.
This is the simplest solution I could think of:
int containsStringAnInt(char* strg){
for (int i =0; i < strlen(strg); i++) {if (strg[i]=='.') return 0;}
return 1;
}
But this solution is really slow when t... | You are using strlen, which means you are not worried about unicode. In that case why to use strlen or strchr, just check for '\0' (Null char)
int containsStringAnInt(char* strg){
for (int i =0;strg[i]!='\0'; i++) {
if (strg[i]=='.') return 0;}
return 1; }
Only one parsing through the string, than parsi... |
394,370 | 394,466 | Is it worth learning AMD-specific APIs? | I'm currently learning the APIs related to Intel's parallelization libraries such as TBB, MKL and IPP. I was wondering, though, whether it's also worth looking at AMD's part of the puzzle. Or would that just be a waste of time? (I must confess, I have no clue about AMD's library support - at all - so would appreciate a... | The MKL and IPP libraries will perform (nearly) as well on AMD machines. My guess is that TBB will also run just fine on AMD boxes. If I had to suggest a technology that would be beneficial and useful to both, it would be to master the OpenMP libraries. The Intel compiler with the OpenMP extensions is stunningly fast a... |
394,564 | 394,636 | boost::filesystem::path for unicode file paths? | Is there a way to use boost::filesystem::path with unicode file paths?
In particular I'd like to use it with std::wstring instead of std::string.
I'm working on the windows platform and I need to sometimes process a filepath that has a unicode char in it.
| Looking at the header file, I see a wpath that's templated with std::wstring.
|
394,854 | 394,867 | Silencing GCC warnings when using an "Uncopyable" class | I have several classes that I don't want to be copyable, some of these classes have pointer data members. To make these classes uncopyable I privately inherit the following class template:
template <class T>
class Uncopyable
{
protected:
Uncopyable() {}
virtual ~Uncopyable() {}
private:
Uncopyable(const... | C++ says
Because a copy assignment operator is
implicitly declared for a class if not declared by the user, a base class copy assignment operator is always
hidden by the copy assignment operator of a derived class (13.5.3). A using-declaration (7.3.3) that brings
in from a base class an assignment operator with ... |
394,900 | 395,028 | How to write an automated test for thread safety | I have a class which is not thread safe:
class Foo {
/* Abstract base class, code which is not thread safe */
};
Moreover, if you have foo1 and foo2 objects, you cannot call foo1->someFunc() until foo2->anotherFunc() has returned (this can happen with two threads). This is the situation and it can't be changed (... | Instead of just checking that a particular thread is finished or not, why not create a fake Foo to be invoked by your wrapper in which the functions record the time at which they were actually started/completed. Then your yield thread need only wait long enough to be able to distinguish the difference between the reco... |
395,060 | 395,068 | Extern keyword and unresolved external symbols | I drew a little graph in paint that explains my problem:
But it doesn't seem to show up when I use the <img> tag after posting?
Graph:
| You need to instantiate the database outside of main(), otherwise you will just declare a local variable shadowing the global one.
GameServer.cpp:
#include GameSocket.h
Database db(1, 2, 3);
int main() {
//whatever
}
|
395,088 | 395,143 | How to programmatically capture a web page with forced updates | I need to capture a web site and am looking for an appropriate library or program to do this. The website uses Java Script and pushes updates to the page and I need to capture these as well as the page itself. I am using curl to capture the page itself but I don't know how to capture the updates. Where given a choice I... | Install Firefox and GreaseMonkey. Have the GM script add DOM events where appropriate to track modifications. You can then use XMLHttpRequest to send the information to a server, or write them to local files with XPCOM file IO opearation.
With this, you can do what you want in a dozen lines and little to no reverse eng... |
395,169 | 395,216 | Using CMake to generate Visual Studio C++ project files | I am working on an open source C++ project, for code that compiles on Linux and Windows. I use CMake to build the code on Linux. For ease of development setup and political reasons, I must stick to Visual Studio project files/editor on Windows (I can't switch to Code::Blocks, for example). I see instructions to generat... | CMake is actually pretty good for this. The key part was everyone on the Windows side has to remember to run CMake before loading in the solution, and everyone on our Mac side would have to remember to run it before make.
The hardest part was as a Windows developer making sure your structural changes were in the cmake... |
395,685 | 395,738 | How do you choose between a singleton and an unnamed class? | I'd use a singleton like this:
Singleton* single = Singleton::instance();
single->do_it();
I'd use an unnamed class like this:
single.do_it();
I feel as if the Singleton pattern has no advantage over the unnamed class other than having readable error messages. Using singletons is clumsier than using an unnamed class... | I think the most important reason is that you cannot put an unnamed class in namespace scope. So, the following is not valid (gcc accepts, but warns. comeau doesn't accept in strict mode):
class { } single;
int main() { }
The type of single has no linkage because there is no way to declare its name in another scope re... |
395,877 | 395,883 | Are child processes created with fork() automatically killed when the parent is killed? | I'm creating child processes with fork() in C/C++.
When the parent process ends (or is killed for some reason) I want all child processes to be killed as well.
Is that done automatically by the system? Or I have to do it myself?
Pre-existing similar questions:
How can I cause a child process to exit when the parent d... | No. If the parent is killed, children become children of the init process (that has the process id 1 and is launched as the first user process by the kernel).
The init process checks periodically for new children, and waits for them (thus freeing resources that are allocated by their return value).
The question was al... |
395,990 | 396,034 | Is it Wise to Spend Cash on a C++ Book Keeping in View the Upcoming C++0x? | I just purchased C++ GUI Programming with Qt4 and after reading the code samples in this book I'm beginning to realize that my knowledge of C++ is incomplete. I learned C++ two years ago from online tutorials and a couple of ebooks I downloaded, and it turns out none of these resources were good enough. Since then I ha... | I wouldn't hold my breath for C++0x. I doubt it will be out by the end of this decade. Even when it will be out, you should probably count a year or so for compilers to implement it. Learn the fundamentals now, and it should be relatively easy for you to learn most of the new features when the standard is out. The ... |
396,084 | 396,094 | Headers Including Each Other in C++ | I'm a C++ newbie, but I wasn't able to find the answer to this (most likely trivial) question online. I am having some trouble compiling some code where two classes include each other. To begin, should my #include statements go inside or outside of my macros? In practice, this hasn't seemed to matter. However, in t... | By "the macros" I assume you mean the #ifndef include guards?
If so, #includes should definitely go inside. This is one of the major reasons why include guards exists, because otherwise you easily end up with an infinite recursion as you noticed.
Anyway, the problem is that at the time you use the A and B classes (insi... |
396,100 | 396,105 | What is the best way to check for memory leaks in c++? | I'm implementing a sparse matrix with linked lists and it's not fun to manually check for leaks, any thoughts?
| The valgrind profiler for Unix offers a decent leak detection.
However, this is only one part of a successful approach. The other part is to prevent (i.e. minimize) explicit memory handling. Smart pointers and allocators can help a great deal in preventing memory leaks. Also, do use the STL classes: a leak-free linked ... |
396,183 | 396,308 | How do you get a minimal SDL program to compile and link in visual studio 2008 express? | I'm trying to use SDL in C++ with Visual Studio 2008 Express. The following program compiles but does not link:
#include <SDL.h>
int main(int argc, char *argv[])
{
return 0;
}
The link error is:
LINK : fatal error LNK1561: entry point must be defined
I get this regardless of how or if I link with SDL.lib and SDL... | I don't have VC++ available at the moment, but I have seen this issue several times.
You need to create a Win32 project as opposed to a console project. A Win32 project expects a WinMain function as a program entry point. SDLmain.lib contains this entry point and the SDL_main.h header file has a macro that remaps your ... |
396,327 | 396,353 | Question on multiple inheritance, virtual base classes, and object size in C++ | The following code prints 20, i.e. sizeof(z) is 20.
#include <iostream.h>
class Base
{
public:
int a;
};
class X:virtual public Base
{
public:
int x;
};
class Y:virtual public Base
{
public:
int y;
};
class Z:public X,public Y
{
};
int main()
{
Z z;
cout << size... | Let's look at the class layout of the two cases.
Without the virtual, you have two base classes ("X" and "Y") with an integer each, and each of those classes have integrated into them a "Base" base class which also has an integer. That is 4 integers, 32-bits each, totalling your 16 bytes.
Offset Size Type Scope Nam... |
396,579 | 396,808 | How can I create cells or grids in C++ for a randomized maze? | I'm trying to create a randomized maze in C++, but I can't start because I don't know how to create grids or cells. How could I create it? And I also want to create it using ASCII characters. how can i store it in array? (can any one give a sample code and some explanation so i can understand it better)
Another questio... | You probably want to store your maze in a 2-dimension char array. You can declare an array with or without initializing it in C++.
char a[30][10]; // declares a char array of 30 rows and 10 columns.
// declare an array with 3 rows and 3 columns, and provide initial values
char ticTacToeBoard[3][3] = {{'x', 'x', 'o'}... |
396,923 | 396,936 | FastCGI request handling | The docs at www.fastcgi.com aren't clear on this (to me), so I hope someone can give me a definitive answer.
I have written a FastCGI application in C++ to do some heavy duty number crunching. When the application first loads (when apache starts), it performs some caching of MySQL data into a vector, which takes abo... | Looking at my web server, I only have one of each FastCGI process running at any one time, no matter how many Apache instances are running. So I have to assume it's queuing them up.
|
397,064 | 397,177 | calling code stored in the heap from vc++ | Imagine I am doing something like this:
void *p = malloc (1000);
*((char*)p) = some_opcode;
*((char*)p+1) = another_opcode; // for the sake of the example: the opcodes are ok
....
etc...
How can I define a function pointer to call p as if it was a function? (i'm using VC++ 2008 express).
Thanks
| A comment wasn't enough space. Joe_Muc is correct. You should not stuff code into memory obtained by malloc or new. You will run into problems if you change the page properties of pages that Windows allocates.
This isn't a problem becuase using VirtualAlloc() and the related WIn32 APIs is every easy: call VirtualA... |
397,128 | 397,146 | sending commands to an application from Excel? COM? | I wrote a device controller (rs232) and it is being used successfully, however users want to view data and control the device (or perhaps communicate through my program) from Excel. I dismissed DDE as an option and found that RTD (IRtdServer) is probably a good start (though no way to send data back to the "server" fr... | Option #1:
Create a small COM server - make sure its interfaces are suitable for scripting with the built Visual Basic engine in Excel. (e.g. use simple types and BSTRS).
Write Excel VB Macros to (1) add your own tool bar to excel and (2) call your COM server.
You can also add buttons and other UI elements to sheets ... |
397,263 | 397,267 | When to use pointers and when not to? | I'm used to doing Java programming, where you never really have to think about pointers when programming. However, at the moment I'm writing a program in C++. When making classes that have members of other classes, when should I use pointers and when should I not? For example, when would I want to do this:
class Foo {
... | Start by avoiding pointers.
Use them when:
You want to use the Pimpl idiom, or an abstract factory.
The Bar instance is actually managed by some other part of your program, whereas the Foo class just needs to be able to access it.
You want to postpone the construction of the Bar object (i.e., you want to create it aft... |
397,404 | 397,409 | virtual function call from base class | Say we have:
Class Base
{
virtual void f(){g();};
virtual void g(){//Do some Base related code;}
};
Class Derived : public Base
{
virtual void f(){Base::f();};
virtual void g(){//Do some Derived related code};
};
int main()
{
Base *pBase = new Derived;
pBase->f();
return 0;
}
Wh... | The g of the derived class will be called. If you want to call the function in the base, call
Base::g();
instead. If you want to call the derived, but still want to have the base version be called, arrange that the derived version of g calls the base version in its first statement:
virtual void g() {
Base::g();
... |
397,420 | 399,249 | Can any one provide me a sample of using CreateHatchBrush | I want to draw a shadow around a thumbnail in my software.
It seems CreateHatchBrush can help but I do not know how to use it, can anyone provide me a sample in C++?
Many thanks!
| The easiest option would be to use GDI+ to do this. Here's a quick and dirty shadow rendering sample:
void Render( HDC hdc )
{
Graphics gr( hdc );
Image image( L"sample.jpg" );
const int SHADOW_OFFSET = 7;
//
// draw shadow
//
SolidBrush shadow( Color( 190, 190, 190 ) );
Rect rc( 50, 5... |
397,483 | 397,503 | C++ associative array with arbitrary types for values | What is the best way to have an associative array with arbitrary value types for each key in C++?
Currently my plan is to create a "value" class with member variables of the types I will be expecting. For example:
class Value {
int iValue;
Value(int v) { iValue = v; }
std::string sValue;
Value(std::st... | boost::variant seems exactly what you are looking for.
|
397,895 | 397,969 | How could I create a list in c++? | How can I create a list in C++? I need it to create a linked list. How would I go about doing that? Are there good tutorials or examples I could follow?
| I take it that you know that C++ already has a linked list class, and you want to implement your own because you want to learn how to do it.
First, read Why do we use arrays instead of other data structures? , which contains a good answer of basic data-structures. Then think about how to model them in C++:
struct Node... |
398,069 | 398,126 | Static member variable in template, with multiple dlls | My code is built to multiple .dll files, and I have a template class that has a static member variable.
I want the same instance of this static member variable to be available in all dlls, but it doesn't work: I see different instance (different value) in each of them.
When I don't use templates, there is no problem: i... | Create template specialization and then export the static members of the specialization.
|
398,543 | 398,656 | Passing newly allocated data directly to a function | While learning different languages, I've often seen objects allocated on the fly, most often in Java and C#, like this:
functionCall(new className(initializers));
I understand that this is perfectly legal in memory-managed languages, but can this technique be used in C++ without causing a memory leak?
| Your code is valid (assuming functionCall() actually guarantees that the pointer gets deleted), but it's fragile and will make alarm bells go off in the heads of most C++ programmers.
There are multiple problems with your code:
First and foremost, who owns the pointer? Who is responsible for freeing it? The calling co... |
398,641 | 399,612 | Trouble with Factory and dynamic allocation in C++ | I have a factory that builds the objects with longest lifetime in my application. These have types, lets say, ClientA and ClientB, which depend on Provider (an abstract class with many possible implementations), so both clients have a reference to Provider as member.
According to the command-line arguments, the factory... | It's very simple with a shared ownership smart pointer:
App AppFactory::buildApp()
{
boost::shared_ptr<Provider> provider;
if (some condition)
{
provider.reset(new ProviderX());
}
else
{
provider.reset(new ProviderY());
}
ClientA clientA(provider);
ClientB clientB(... |
398,682 | 398,742 | Finding statement pattern in c++ file | I have a macro that looks like this:
#define coutError if (VERBOSITY_SETTING >= VERBOSITY_ERROR) ods()
where ods() is a class that behaves similarly to cout, and VERBOSITY_SETTING is a global variable. There are a few of these for different verbosity settings, and it allows the code to look something like this:
... | You could try - temporarily - modifying the macro to something like this, and see what doesn't compile...
#define coutError {} if (VERBOSITY_SETTING >= VERBOSITY_ERROR) ods()
The 'else' clauses should now give errors.
|
398,888 | 398,911 | Extending a C++ application with C# plugins | I have a C++ Windows application that can be extended by writing C++ plugins, using an API that is exposed by the application. There is also one plugin that translates the C++ API to Python (e.g. plugins can be written in Python).
I want to allow users to write plugins in C# in addition to C++ and Python. Since I'm not... | There are a couple of prior posts that may help you out:
Interfacing using a simple API
Communicating between C++ and C# via DLL interface
|
399,003 | 399,030 | Is the sizeof(some pointer) always equal to four? | For example:
sizeof(char*) returns 4. As does int*, long long*, everything that I've tried. Are there any exceptions to this?
| The guarantee you get is that sizeof(char) == 1. There are no other guarantees, including no guarantee that sizeof(int *) == sizeof(double *).
In practice, pointers will be size 2 on a 16-bit system (if you can find one), 4 on a 32-bit system, and 8 on a 64-bit system, but there's nothing to be gained in relying on a ... |
399,304 | 399,322 | Store huge std::map, mostly on disk | I've got a C++ program that's likely to generate a HUGE amount of data -- billions of binary records of varying sizes, most probably less than 256 bytes but a few stretching to several K. Most of the records will seldom be looked at by the program after they're created, but some will be accessed and modified regularly.... | I doubt you will find a library that meets your requirements exactly, so you'll have to decide on what 'features' are really important to you and then decide if an existing DB solution comes close enough.
Billions of records is a large dataset by any stretch. What rate are records generated at? How long do they persi... |
399,452 | 399,682 | Forward declare method pointer | I am using the pimpl idiom and want to reference one of the methods of the forward declared class. Below isn't exactly what I'm doing but uses the same concepts.
template< typename Class, void (Class::*Method)(void) >
struct Call
{
Call( Class* c )
: m_c(c)
{ }
void operator()( void )
{
(m_c->*M... | You cannot forward declare a member function. I think the reason is that, when you call the function on a pointer to B, the compiler has to pass the this pointer to that method. But it doesn't know the precise class hierarchy of B yet. So possible adjustments of that pointer (due to the method being virtual, for exampl... |
399,538 | 399,668 | How do I link PDCurses to a C++ application on Windows? | I'm building a C++ application and need to use PDCurses on Windows. I'm compiling with VC++ from MS VS 2005 and I'm getting a link error.
error LNK2019: unresolved external
symbol __imp__GetKeyState@4 referenced
in function __get_key_count
There are 11 errors all with the same error code and different symbols. Th... | GetKeyState() is a Windows function in "user32.dll", so you need to be sure you're linking against "user32.lib". You may also need to make sure it comes after the PDCurses library in the list of linker libraries, too.
|
399,740 | 399,742 | Design question for abstract base class? | Have a interface
class abc {
public:
virtual int foo() = 0;
...
}
class concrete1: public abc {
public:
int foo() {
..
}
class concrete2 : public abc {
public:
int foo() {
..
}
}
Now in my main program I need to construct classes based upon a value of a variable
abc *a;
if (var == 1)
a = new concre... | You are looking for http://en.wikipedia.org/wiki/Factory_method_pattern
|
399,792 | 399,819 | Inadvertent use of = instead of == | It seems that
if (x=y) { .... }
instead of
if (x==y) { ... }
is a root of many evils.
Why don't all compilers mark it as error instead of a configurable warning?
I'm interested in finding out cases where the construct if (x=y) is useful.
| Most of the time, compilers try very hard to remain backward compatible.
Changing their behavior in this matter to throw errors will break existing legitimate code, and even starting to throw warnings about it will cause problems with automatic systems that keep track of code by automatically compiling it and checking ... |
399,907 | 399,915 | Pointer class assistance | I'm writing a sparse matrix class in C++ in which every row and column are arrays of linked lists from a class I created (aptly named: LinkedList).
I want to write a class that is a "smart" pointer to one cell in this matrix.
In that class, let say LIPointer, I will implement a ++ operator function for moving in the li... | For compressed row matrices, I use something like:
std::vector<std::map<size_t, double> > matrix;
I can then add an entry using:
matrix[row][col] += val;
For each row, I can then iterate through the column entries in ascending order and read out the value.
Edit: The person posing the question does point out... |
399,942 | 399,960 | C++ variable with same name, context : global and private, | In the following code, g++ gives this error :
1.cpp: In member function void W::test()':
1.cpp:6: error:int F::glob' is private
1.cpp:19: error: within this context
But, shouldn't the globally declared
variable 'glob' be used here, instead
of the "private" "glob"?
#include <iostream.h>
int glob;
class F
... | Variables and functions are accessed using scoping rules, not visbility rules. Because F::glob is the glob in the scope of W::test(), it is used. However, W::test() does not have access to F::glob, and an error results. The compiler does not check for ::glob because something else preceeds it in scope "priority" (no... |
399,946 | 400,769 | How often do you check for an exception in a C++ new instruction? | I just started reading Effective C++ today and got to the point where the author talks about the operator new.
The book explains very well how you can catch (with various degrees of elegance) the std::bad_alloc exception that the operator new can raise if you run out of memory.
My question is: How often do you check fo... | I catch exceptions when I can answer this question:
What will you do with the exception once you've caught it?
Most of the time, my answer is, "I have no idea. Maybe my caller knows." So I don't catch the exception. Let it bubble up to someone who knows better.
When you catch an exception and let your function procee... |
400,116 | 400,127 | what is the purpose and return type of the __builtin_offsetof operator? | What is the purpose of __builtin_offsetof operator (or _FOFF operator in Symbian) in C++?
In addition what does it return? Pointer? Number of bytes?
| It's a builtin provided by the GCC compiler to implement the offsetof macro that is specified by the C and C++ Standard:
GCC - offsetof
It returns the offset in bytes that a member of a POD struct/union is at.
Sample:
struct abc1 { int a, b, c; };
union abc2 { int a, b, c; };
struct abc3 { abc3() { } int a, b, c; }; /... |
400,257 | 400,293 | How can I pass a class member function as a callback? | I'm using an API that requires me to pass a function pointer as a callback. I'm trying to use this API from my class but I'm getting compilation errors.
Here is what I did from my constructor:
m_cRedundencyManager->Init(this->RedundencyManagerCallBack);
This doesn't compile - I get the following error:
Error 8 err... | That doesn't work because a member function pointer cannot be handled like a normal function pointer, because it expects a "this" object argument.
Instead you can pass a static member function as follows, which are like normal non-member functions in this regard:
m_cRedundencyManager->Init(&CLoggersInfra::Callback, th... |
400,903 | 401,514 | Borland C++ Builder 5 - Cancel Via Escape Key Not Working | I'm having a rather perplexing problem with the Escape key handler on a dialog box in Borland C++ Builder 5. Are there any other requirements for the Escape key to fire a cancel event (other than those I've listed below)?
The "Cancel" button (a TBitBtn) has its Cancel property set to true.
The "Cancel" button has its... | You should check all possible ways the cancel event could be blocked:
First of all, check if clicking the cancel button actually closes the form.
Then check if any other button has its Cancel property set to true.
After that check all key event handlers, don't forget the event handlers of the form, especially if you ... |
401,621 | 401,801 | Best way to for C++ types to self register in a list? | Suppose I have some per-class data: (AandB.h)
class A
{
public:
static Persister* getPersister();
}
class B
{
public:
static Persister* getPersister();
}
... and lots and lots more classes. And I want to do something like:
persistenceSystem::registerPersistableType( A::getPersister() );
persistenceSystem::regis... | You can execute something before main once if a instantiation of a template is made. The trick is to put a static data member into a class template, and reference that from outside. The side effect that static data member triggers can be used to call the register function:
template<typename D>
struct automatic_register... |
401,812 | 401,879 | What is the proper way to cast from an 'OLE_HANDLE' to an 'HICON'? | What is the proper way to cast from an 'OLE_HANDLE' to an 'HICON' for an x64 target build?
In particular with a normal C-Style cast, I get this warning when compiling with an x64 config:
warning C4312: 'type cast' : conversion from 'OLE_HANDLE' to 'HICON' of greater size
Here is the offending code:
imgList.Add((HICON)o... | The H gives it away, in this case the library code has created a distinct type to give you a little more type safety (in the days of old C APIs).
They are actually both HANDLEs, which is a kernel object that doesn't really care what the resource is, just that you have a 'handle' to it. Remember the API is a C one, so u... |
401,851 | 404,244 | Naming convention for Qt widgets | I'm working with a group of other programmers on an open source project built using C++ and Qt.
Now, we need a naming convention for widgets (and other variables generally) to use it as a standard in all of our code so that, the code gets better readability and we get better coordination between programmers.
Any advice... | As long as you are thinking along these lines, I'd start by reading this QtQuarterly article from start-to-finish.
Designing Qt-Style C++ APIs
That said, one thing that we do is to put the "use" of the instance as the first part and the last full word of the class as the last part.
So, your "user name" QTextEdit is
QTe... |
402,314 | 403,511 | How do you identify (and get access to) modules/debug symbols to use when provided a windows .dmp or .minidmp | In a way following on from reading a windows *.dmp file
Having received a dump file from random customer, running the debug session to see the crash, you often find it is in a MS or other third party library. The next issue is that you may not have knowledge of the PC setup to such an extent that you can ensure you ha... | What are you using to debug the minidump? I.e., WinDBG or Visual Studio? And how was the minidump generated?
There should be enough information in the minidump to resolve system dll symbols correctly. Are you using a local download of symbols or http://msdl.microsoft.com/?
Update: You should be able to add the public m... |
402,316 | 402,320 | Learning Algorithm and Saving Data in Software | I'm coming from a web-development background and I am wondering how I would make a learning algorithm in Java/C++. Not so much the algorithm part, but making the program "remember" what it learned from the previous day. I would think something like saving a file, but I suspect their might be an easier way. Apologies if... | I think that would depend a bit on the problem domain. You might want to store learned "facts" or "relationships" in a DB so that they can be easily searched. If you are training a neural network, then you'd probably just dump the network state to a file. In general, I think once you have a mechanism that does the lear... |
402,432 | 402,456 | C++ Returning and Inserting a 2D array object | I am trying to return an array Data Member from one smaller 2D Array Object, and trying to insert the array into a larger 2D array object. But when attempting this, I came into two problems.
First problem is that I want to return the name of the 2D array, but I do not know how to properly syntax to return 2D Array name... | When passing your array around, you have to decide whether or not you want to make a copy of the array, or if you just want to return a pointer to the array. For returning arrays, you can't (easily) return a copy - you can only return a pointer (or reference in C++). For example:
// Piece::returnPiece is a function t... |
402,598 | 406,278 | Debugging C++ lib with eclipse | I am working on project in Linux which involves
1) Static Lib in C++
2) GUI developed in C++/QT which uses static lib.
Now both the lib and gui are build from command prompt using makefiles.
I am trying to debug both like when I hit one button, call should go from GUI to lib.
Is it possible to do like this in Linux wit... | Well I figured it out..
I am currently using Kdevelop..
With Kdevelp we can create QT project as well as c++(lib) project.
And there is option to attach process also.
So I can step through lib code by attaching GUI .
|
402,824 | 402,898 | Automatic generation of function stubs | Is there any Visual Studio add-on (or windows/unix stand-alone program) that creates stub implementations in the cpp file for the functions (including class member functions) that are defined in the header file?
| I have the same problem before and now I am using trial version of Visual Assist X. The task mentioned can be done by right clicking on the method name -> Refactor -> Create Implementation and then Refactor -> Move Implementation to CPP file.
I am no Visual Assist X's affiliate or what, but this really increases my cod... |
402,969 | 403,024 | What makes the Java compiler so fast? | I was wondering about what makes the primary Java compiler (javac by sun) so fast at compilation?
..as well as the C# .NET compiler from Microsoft.
I am comparing them with C++ compilers (such as G++), so maybe my question should have been, what makes C++ compilers so slow :)
| That question was nicely answered in this one: Why does C++ compilation take so long? (as jalf pointed out in the comments section)
Basically it's the missing modules concept of C++, and the aggressive optimization done by the compiler.
|
402,992 | 403,140 | Passing function Pointers in C++ | i want to do this simple piece of code work.
#include <iostream>
#include <windows.h>
void printSome (int i)
{
std::cout << i << std::endl;
}
void spawnThread (void (*threadName)(int i))
{
CreateThread
(
0, // default security attributes
... | Personally, I wouldn't consider passing in a function pointer like you are trying to do as very C++ like. That's coding C in C++
Instead, I'd wrap that thing in a class. The big advantage there is you can just override the class to have however many members you want, rather than having to perform greazy casting tricks ... |
403,349 | 403,366 | unicode char comparing to non unicode char, but no warning nor error | Why does the following code NOT give an error, nor any type of a warning about an implicit conversion?
std::wstring str = L"hi";
if(str[0] == 'h')
cout<<"strange"<<endl;
The proper normal code is:
std::wstring str = L"hi";
if(str[0] == L'h')
cout<<"strange"<<endl;
Compiler: visual studio 2005
Warning leve... | It doesn't give a warning because the comparison is valid. In general, you can always compare integral types, they just get promoted to wider types as needed.
And I'm pretty sure some compilers would issue a warning about this. Which one are you using? (In any case, warnings are compiler-specific, and they're not requi... |
403,420 | 403,452 | Convert XSD into SQL relational tables | Is there something available that could help me convert a XSD into SQL relational tables? The XSD is rather big (in my world anyway) and I could save time and boring typing if something pushed me ahead rather than starting from scratch.
The XSD is here if you want to have a look. It's a standardized/localized format to... | Altova's XML Spy has a feature that will generate SQL DDL Script from an XSD file. XML Spy will cost you some money though.
Interestingly enough, a developer used a really clever trick of using an XSLT translation to create the DDL script from an XSD file. They have outlined it in two parts here and here.
I might have ... |
403,747 | 403,907 | Bests practices for localized texts in C++ cross-platform applications? | In the current C++ standard (C++03), there are too few specifications about text localization and that makes the C++ developer's life harder than usual when working with localized texts (certainly the C++0x standard will help here later).
Assuming the following scenario (which is from real PC-Mac game development cases... | At a small Video Game Company, Black Lantern Studios, I was the Lead developer for a game called Lionel Trains DS. We localized into English, Spanish, French, and German. We knew all the languages up front, so including them at compile time was the only option. (They are burned to a ROM, you see)
I can give you infor... |
403,929 | 403,958 | Which compiler is correct for the following overloading/specialization behavior? | Consider the following code:
#include <stdio.h>
namespace Foo {
template <typename T>
void foo(T *, int) { puts("T"); }
template <typename T>
struct foo_fun {
static void fun() { foo((T *)0, 0); };
};
}
namespace Foo {
void foo(int *, int) { puts("int"); }
}
using namespace Foo;
int main() {
foo_... | The second void foo(... is an overload (and not a specialization) which is not visible at the definition of foo_fun::fun so it won't be found in the context of the template definition. Because T* is a dependent type, resolution of foo in the expression foo((T*)0, 0) will be delayed until template instantiation time and... |
403,946 | 403,954 | Trying to get rid of a c++ boost warning | Whenever I include boost in my project I get a million of these warnings. Does anyone know how I can get rid of the warnings?
../depends\boost/config/abi_prefix.hpp(19)
: warning C4103:
'depends\boost\config\abi_prefix.hpp'
: alignment changed after including
header, may be due to missing #pragma
pack(pop)
... | The reason is that boost doesn't push/pop these pragmas in every file that needs data to be packed. They #include a separate file which does the push (abi_prefix.hpp), and then another (abo_suffix.hp) afterwards which does the pop.
That allows them to reuse the same #pragma pack code everywhere, which is handy as it ma... |
404,169 | 415,861 | GNU Compiler Debug 'Level' | While browsing the various option switches for my compiler (GNU C++ 3.2.3 is supported by my organization for my given hardware configuration), I ran across this:
-glevel
:
Level 3 includes extra information, such as all the macro definitions
present in the program. Some debuggers support macro expansion when
you us... | Your question appears to imply that you don't understand what macros are. Of course you can't step into a macro.
The -g3 is quite useful for "macro heavy" programs. Consider:
int main()
{
int i;
for (i = 0; i < 20; ++i) {
#define A(x) case x: printf(#x "\n"); break
switch(i) {
A(1); A(2); A(3); A(4); /* l... |
404,231 | 404,263 | Using an enum as an array index | I have this enum:
enum ButtonState {
BUTTON_NORMAL = 0,
BUTTON_PRESSED = 1,
BUTTON_CLICKED = 2
};
const u8 NUM_BUTTON_STATES = 3;
In my Button class I have member variables ButtonState state; and ButtonColors colors[NUM_BUTTON_STATES];. When drawing the button, I use colors[state] to get the colours for w... | Is this good programming style?
I think so. I do the same thing quite frequently.
Is there a better way to do it?
class Button
{
public:
// Used for array indexes! Don't change the numbers!
enum State {
NORMAL = 0,
PRESSED,
CLICKED,
NUMBER_OF_BUTTON_STATES
};
};
Drawback is that NUMBER_OF_BUT... |
404,258 | 404,269 | How do I erase a reverse_iterator from an stl data structure? | For some reason the following code fails. You can't simply erase a reverse_iterator by using its base() method.
#include <set>
#include <iostream>
int main()
{
std::set<int> setOfInts;
setOfInts.insert(1);
setOfInts.insert(2);
setOfInts.insert(3);
std::set<int>::reverse_iterator rev_iter = setOfI... | Apparently the solution is what base() returns is 1 off. The following identity holds for a reverse_iterator:
&*(reverse_iterator(i)) == &*(i - 1)
Or in other words, the reverse_iterator is always one pass the regular iterator it is the base of. Not sure why.
In GCC
Simply change
// SEGFAULT HERE
setO... |
404,311 | 404,317 | Is there a way to set a pragma disable warning for visual studio for an entire solution? | Is there a way to set a pragma disable warning for visual studio for an entire solution?
| Use the /w compiler switch for per-project suppression. I'm not aware of any way to do it solution wide without selecting all projects and adding it to the command-line for each project (which can be done in one operation).
|
404,468 | 404,480 | typedef a std::string - Best practice | I am writing a library in standard C++ which does the phonetic conversion. I have used std::string as of now. But in future I may have to change this to someother (std::wstring or something else). So I need to write my library in such a way that I can switch this easily. I have done the following so far to achieve this... | You can write template functions that will work with either type of string, or for that matter anything that has the proper methods.
If you do the typedef as you suggest, you will need to change all your code in the future when you change the typedef. I'd recommend against it.
Edit: the point is that string and wstrin... |
404,513 | 404,517 | Private member variables scope - C++ | I am just starting with C++ and got some problems in understanding how the scope for private member variables in a class works. Please see the below code
class Foo{
private:
std::vector<int> container;
public:
// other methods
};
int main(int argc, char* argv[])
{
Foo* foo = new Foo;
//... |
Yes, the lifetime of the container member will last as long as the object that contains it exists, which is until you call delete on the pointer pointing to it (foo in your case).
No, there is no reason to do that. Making it a pointer requires you to create a dynamic object of vector<int> which you would need to mana... |
404,886 | 404,916 | Alternative to CString::Format? | Is there any better alternative for doing string formatting in VC6, with syntax checking before substitution?
| CString offers the Format method for printf-style formatting, but this isn't type-safe.
For type-safe string formatting you could either use std::stringstream / std::wstringstream or the Boost Format library, although these both work with the C++ std::basic_string class template, and not the MFC CString class. I've use... |
404,934 | 404,939 | Can someone explain this C++ notation? | if (vector1.x > ((float*)&vector1)[j])
Is j simply just an index into the vector?
e.g. is C++ able to retrieve these values using array notation even though vector isn't an array?
If so I'm guessing it achieves this by referencing vector by its address?
| The C++ Standard says that casting a (pods) struct's pointer to a pointer of the type of its first element will yield a pointer to its first element:
struct a {
float a1;
float a2;
float a3;
};
a o1; ((float*)&o1); // points to o1.a1
I suspect that code told the compiler not to add any padding between a1,... |
405,039 | 405,068 | "Permanent" std::setw | Is there any way how to set std::setw manipulator (or its function width) permanently? Look at this:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <iterator>
int main( void )
{
int array[] = { 1, 2, 4, 8, 16, 32, 64, 128, 256 };
std::cout.fill( '0' );
std::cout.flags( std::ios::hex );
st... | Well, it's not possible. No way to make it call .width each time again. But you can use boost, of course:
#include <boost/function_output_iterator.hpp>
#include <boost/lambda/lambda.hpp>
#include <algorithm>
#include <iostream>
#include <iomanip>
int main() {
using namespace boost::lambda;
int a[] = { 1, 2, 3,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.