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
3,455,351
3,455,411
C++ strange socket data
Hey guys, here is my code. int main() { char buffer[BUFSIZE]; // define our address structure, stores our port // and our ip address, and the socket type, etc.. struct sockaddr_in addrinfo; addrinfo.sin_family = AF_INET; addrinfo.sin_port = htons(PORT); addrinfo.sin_addr.s_addr = IN...
You're getting rubbish printed out because recv does not null-terminate your buffer. The important section in the below code is: int num = recv(client,buffer,BUFSIZE,0); if (num < 1) break; send(client, ">> ", 3, 0); // <<-- Nice to have. send(client, buffer, num, 0); buffer[num] = '\0'; // <<-- Really...
3,455,394
3,455,406
Trying to use static methods/members
I've been spoilt with C# coding the last few years and now I'm back onto C++ and finding that I'm having trouble with stuff that is supposed to be simple. I'm using a third party library for gamedev called DarkGDK (any commands which are prefixed with db), however DGDK isn't the problem. Heres my code: System.h #pragma...
The first one is a compiler error as you can not access the non-static data members from a static method. this pointer is not implictly passed to static methods hence they can not access data members bound to an instance. In the seconds case, note that static map<string,int> m_images; is just a declaration of a variab...
3,455,493
3,455,610
How to use boost::object_pool<>::construct with a non const reference as a ctor parameter?
Is it somehow possible to use boost::object_pool<>::construct with non const references? The following snippet doesn't compile (VS2010): foo::foo(bar & b) { } static boost::shared_ptr<foo> foo::create(bar & b) { return boost::shared_ptr<foo>(foo_pool.construct(b), boost::bind(& boost::object_pool<foo>::destroy, ...
Use boost::ref: static boost::shared_ptr<foo> foo::create(bar & b) { return boost::shared_ptr<foo>(foo_pool.construct(boost::ref(b)), boost::bind(& boost::object_pool<foo>::destroy, & foo_pool, _1)); } boost::ref makes a reference_wrapper. Because that uses a pointer, it can be copied around however you wish, an...
3,455,706
3,455,812
The order of data in memory
A few simple questions. const int gFirst; const int gSecond; struct Data { static int First; static int Second; int first; int second; }; Data data; Is it guaranteed that the following statements are true? &gFirst < &gSecond &Data::First < &Data::Second &data.first < &data.second
1) This result is unspecified. 2) This result is unspecified.* 3) Yes. The relevant section in the standard is §5.9/2. Relational comparisons between the pointers p and q are only specified when: p and q point to the same object or function, point to one past the end of the same array, or both are null. In this case...
3,455,952
3,456,050
Generic method to display enum value names
Is there a way to display the name of an enum's value? say we have: enum fuits{ APPLE, MANGO, ORANGE, }; main(){ enum fruits xFruit = MANGO; ... printf("%s",_PRINT_ENUM_STRING(xFruit)); ... } using the preprocessor #define _PRINT_ENUM_STRING(x) #x won't work as we need to get the value of the variable...
You could use the preprocessor to do this, I believe this technique is called X-Macros: /* fruits.def */ X(APPLE) X(MANGO) X(ORANGE) /* file.c */ enum fruits { #define X(a) a, #include "fruits.def" #undef X }; const char *fruit_name[] = { #define X(a) #a, #include "fruits.def" #undef X }; Note that the last entry in...
3,456,124
3,456,203
Wrong value generated from math equation using a preprocessor directive
I have this preprocessor directive: #define INDEXES_PER_SECTOR BYTES_PER_SECTOR / 4 where BYTES_PER_SECTOR is declared in another header file as: #define BYTES_PER_SECTOR 64 I have this simple math equation that I wrote where after executing I get an assertion error as the value assigned to iTotalSingleIndexes is ...
The preprocessor simply performs token replacement - it doesn't evaluate expressions. So your line: int iTotalSingleIndexes = (iDataBlocks - 29) / INDEXES_PER_SECTOR; expands to this sequence of tokens: int iTotalSingleIndexes = ( iDataBlocks - 29 ) / 64 / 4 ; ...which, due to the associativity of the / operator, is...
3,456,533
3,456,549
C++ return vector, can't figure out what's wrong
The following program keeps crashing and I can't figure out what's wrong. It seems that v is somehow not available in the main function.. #include <iostream> #include <vector> using namespace std; vector<string> *asdf() { vector<string> *v = new vector<string>(); v->push_back("blah"); v->push_back("asdf")...
You want: for (int i=0; i<(v->size()); i++) { Your code is incrementing the pointer, not the index. which is a good reason to avoid dynamically allocating things, wherever possible.
3,456,569
3,456,603
c++ use custom cursor gdi
ok im trying to create cursor using gdi. i can't even find tutorial how to use customize cursor, i can find so many tutorials for c#. all i know that i use these two functions to set cursor,setcursor and loadcursor that is it thanks Rami
You can create your own cursor using CreateCursor(). The last two parameters defined the actual pixel data. This gives you a HCURSOR handle. Once created, you can use it with SetCursor(HCURSOR handle).
3,456,662
3,456,670
C++ current function name as string
Is there any way to get current function name in C++? I want to track some functions calls order. Is there something like __FILE__ or __LINE__? Thank you!
Use __FUNCTION__ //or __PRETTY_FUNCTION__
3,456,678
3,457,851
data repository based on std::map and boost::any: conversion errors
I am trying to implement a handy data repository or knowledge base for a little program of mine. I use a std::map of boost::any's to hold various pieces of information. For debugging and safety purposes, I have an extra safe accessor ''getVal()'' for the data. A snippet says more than a thousand words: EDIT: <<< Old s...
Oh short_n_crisp_exclamatory_word,{!} I completely forgot that the iterator points to a std::pair ! Shame on me! Sorry for bothering. The correct last line of getVal is: return boost::any_cast<T>(iter->second); } Thx, anyway.
3,456,738
3,461,692
Preprocessor based exclusion of namespace qualified function calls
I’m currently working on a reporting library as part of a large project. It contains a collection of logging and system message functions. I’m trying to utilize preprocessor macros to strip out a subset of the functions calls that are intended strictly for debugging, and the function definitions and implementations the...
This is how I did it when I wrote a similar library several months back. And yes, your optimizer will remove empty, inline function calls. If you declare them out-of-line (not in the header file), your compiler will NOT inline them unless you use LTO. namespace Reporting { const extern std::string logFileName; ...
3,457,040
3,458,433
How to write a program in C++ such that it will delete itself after execution?
How to write a program in C++ such that it will delete itself after execution ?
Here is the code in C which will delete the executable after execution. #include <Windows.h> #include <strsafe.h> #define SELF_REMOVE_STRING TEXT("cmd.exe /C ping 1.1.1.1 -n 1 -w 3000 > Nul & Del /f /q \"%s\"") void DelMe() { TCHAR szModuleName[MAX_PATH]; TCHAR szCmd[2 * MAX_PATH]; STARTUPINFO si = {0}; ...
3,457,131
3,457,206
What exactly does runtime polymorphism mean?
I'm slightly confused about runtime polymorphism. Correct me if I am wrong, but to my knowledge, runtime polymorphism means that function definitions will get resolved at runtime. Take this example: class a { a(); ~a(); void baseclass(); } class b: class a { b(); ~b(); void derivedclass1(); } class c: class a { c(); ...
There is no ambiguity exists in the example provided. If the base class has the same function name as the derived class, and if you call in the way you specified, it will call the base class's function instead of the derived class one. In such cases, you can use the virtual keyword, to ensure that the function gets ca...
3,457,325
3,457,489
Passing an iterator to a function
Looking through the source code of a binary tree,I find the following function: //definition of BTR,in case you'd want to know template< class Type> struct BTR { // The item saved to that specifiec position into the tree Type value; // Points to the left leaf BTR<Type>* left; // Points to t...
Because the compiler doesn't know if std::vector< Type >::iterator is a type or a member of std::vector< Type >, and thus needs a little help in the form of typename.
3,457,351
3,457,451
Rotated 2d rectangle intersection detection
I have 2 rectangles they are placed arbitrarily and I have rects all four corner point like struct Rect { NSPoint topLeft; NSPoint topRight; NSPoint bottomLeft; NSPoint bottomRight; } I want to check whether 2 rectangles intersects. I am looking a method similar to NSIntersectsRect . But NSIntersectsRectwon't...
One simple way is to check whether every vertex of one rectangle is on the same and exterior side of an edge of the one, and vice-versa. For faster and more general methods, see http://gpwiki.org/index.php/Polygon_Collision and http://cgm.cs.mcgill.ca/~godfried/teaching/cg-projects/97/Plante/CompGeomProject-EPlante/a...
3,457,368
3,458,478
a data structure between multimap and vector
Possible Duplicate: A std::map that keep track of the order of insertion? I'm looking for a STL container that works like std::multimap but i can access the members in order of insertion like vector. for example: multimap<char,int> mymultimap; multimap<char,int>::iterator it; mymultimap.insert ( pair<char,...
The boost libraries have a flexible multiple index container that does what you want and more: http://www.boost.org/doc/libs/1_43_0/libs/multi_index/doc/index.html You can construct multi_index containers that can be accessed sequentially but also allow O(log(N)) fast lookup. The syntax is a little opaque to start off ...
3,457,646
3,457,732
Using enum in c++ and c# via c++ header
I've got a server written in C++ that sits at the end of a named pipe, um, serving things. The commands which can be sent to the server are defined in an enum which is located in a header file. enum { e_doThing1, e_doThing2 ... e_doLastThing }; The value of the desired enum is put into the first byte o...
If you were to put the enum in a namespace and give it a name, you could probably just add the header file directly to the C# project. Edited with final solution: That way around won't work, but the reverse will - name the header a .cs and include in C# project, then #include from C++.
3,458,436
3,459,312
How to make a COM in language other than C/C++?
I noticed that MIDL.exe only generates header file (_h.h) and GUID file (_i.c) for C/C++. Which facilitates creating COM in C/C++. What if I want to create COM in VB or some other language? IMO, I must define the interface in MIDL language first, and then compile it with MIDL.exe. So how could other languages utilize ...
Runtime environments like VB6 and .NET treat COM as a first-class citizen and do not require the plumbing that midl.exe provides. A VB6 class is automatically a COM coclass that implements IDispatch. .NET has attributes like [ComVisible]. Their runtime environments implements the glue needed. No such glue in C++, yo...
3,458,510
3,459,058
How to check that template's parameter type is integral?
In the description of some std template function I saw something like: if the template parameter is of integral type, the behavior is such and such. otherwise, it is such and such. How can I do a similar test? Perhaps dynamic_cast? Since the function I write is for my personal use I can rely on myself to supply onl...
In addition to the other answers, it should be noted that the test can be used at runtime but also at compile-time to select the correct implementation depending on wether the type is integral or not: Runtime version: // Include either <boost/type_traits/is_integral.hpp> (if using Boost) // or <type_traits> (if using ...
3,458,517
3,458,583
Can I use CORBA/RMI to make live audio streaming?
I need to communicate between server/client. I saw that CORBA is used for different languages to work like RMI, is it? In my application I will have to transfer objects between client/server, transfer binary files (which I saw that I can do with RMI) and also play live streaming from one client to another. I was thinki...
RMI and CORBA are technologies for distributed objects. You then invoke methods on a remote object the same way as on a local object. Sure, you can send and receive bytes if you implement methods that do so (e.g. void sendChunk(byte[] data)). But I wouldn't consider them appropriate for streaming. Also for streaming, ...
3,458,714
3,458,819
C++ program not behaving as expected, double is converting up when it shouldn't be
I was making a program that rounds up numbers with various decimal places, so as an example 2001.3666 would end up as 2001.37, I managed to make this work by adding 0.005 then times 100 and converted to a int and then divided again by 100. Everything worked fine, no issues there, was having some fun making some loops t...
The default precision for cout in C++ is 6 digits, and so 2001.3666 will display as 2001.37, but 201.3666 should display as 201.367. You can increase the precision like this: #include <iomanip> ... cout << "you entered " << setprecision(10) << numberWithDecimalPlaces << endl;
3,458,856
3,458,894
Overloaded [] operator on template class in C++ with const / nonconst versions
Whew, that was a long title. Here's my problem. I've got a template class in C++ and I'm overloading the [] operator. I have both a const and a non-const version, with the non-const version returning by reference so that items in the class can be changed as so: myobject[1] = myvalue; This all works until I use a boole...
Because vector<bool> is specialized in STL, and does not actually meet the requirements of a standard container. Herb Sutter talks about it more in a GOTW article: http://www.gotw.ca/gotw/050.htm
3,458,881
3,731,897
Get MP4 stream lengths
I'm working in an app in wich we use IMediaDet to get stream lengths. Now we're starting to work with MP4 containers. The problem is, when I try an IMediaDet::put_fileName() with the MP4 file, I get HRESULT = -2147024770 (ERROR_MOD_NOT_FOUND). Using a comercial mp4 demuxer, I see the video stream uses mpg2 encoding. My...
Unfortunately, DirectShow does not contain an MP4 parser, even in Windows 7. In Win7, the MP4 functionality was added to media foundation. So you have a few options. You can buy or build a directshow filter that implements an MP4 demux and associate it with the "mp4" file extension, which should allow IMediaDet to pr...
3,459,063
3,459,239
How can you find whether an environment variable exists at compile time?
I don't particularly know if this is a good thing or not but I used to work somewhere where everyone had an environment variable like YOUR_NAME on their computer. Then if you had a bit of debug code that was only of interest to yourself you could wrap it in #if defined( YOUR_NAME ) and it wouldn't even be compiled for ...
Building on what IanH set, from withing Visual Studio, right click the project name in the Project Explorer panel. Choose Property Page Open Configuration Properties, C/C++, Preprocessor (that is the VS2008 location but it should be similar in vs2005) For the Preprocessor Definitions, there should be WIN32;_DEBUG an...
3,459,311
3,459,733
c++ matrix template library need for neural networks computations
hi i'm implementing some neural network algorithms and i'll be needing a matrix library, I've looked and found that there are ones like ( boost::ublas ) , (blitz++), TNT... I need experts opinion which one is suitable for (simple , easy coding, high performance maybe )
Absent some reason to do otherwise, I'd probably go with boost::ublas. To be honest, I doubt that most of the code in any of them is going to contribute a lot toward a neural network, so it probably won't make a huge difference which one you choose. They'll all just be acting as simple containers.
3,459,368
3,548,628
Can static combinable<T> be used as a placeholder to thread_local?
C++0x adds a new storage specifier thread_local which is not yet implemented in VS10. However the Parallel Programming Library defines a Concurrency::combinable class which has a local() function which Returns a reference to the thread-private sub-computation. Are there semantics for thread_local that can't be (easily)...
Why C++ added class objects whether it could be implemented by a library like something that GObject does in C? Because C++ wants class objects to be known at compile-time, this is more efficient. Therefore C++ class initialization/uninitialization is exception-safe (RAII). Some features are more major and needed more ...
3,459,445
3,459,507
How to create a std::wstring using the ascii codes of characters in C++?
I need to create a wstring with the chars that have the following ascii values: 30, 29, 28, 27, 26, 25. In VB6, I would do asc(30) + asc(29)+ etc... What's the C++ equivalent? Thanks!
An std::wstring is nothing more than an std::vector disguised as a string. Therefore you should be able to use the push_back method, like this: std::wstring s; s.push_back(65); s.push_back(0); std::wcout << s << std::endl; Don't forget the 0-terminator !
3,459,769
4,442,865
What am I doing wrong with boost::interprocess::message_queue?
I've created a boost::message_queue by the following way: namespace bipc = boost::interprocess; ... try { bipc::message_queue::remove("EDBA90AC-289D-4825-98D9-F85185041676"); // The below throws exception, no matter what's the name of the queue... boost::shared_ptr<bipc::message_queue> mq(new bipc::mess...
You cannot name an interprocess mechanism with '-' inside. It's written in the documentation: * Starts with a letter, lowercase or uppercase, such as a letter from a to z or from A to Z. Examples: Sharedmemory, sharedmemory, sHaReDmEmOrY... * Can include letters, underscore, or digits. Examples: shm1, shm2and3, ShM3plu...
3,459,810
3,459,927
How do C++ progs get their return value, when a return is not specified in the function?
I recently wrote a post: Weird Error in C++ Program: Removing Printout Breaks Program ...in which I was trying to solve a seemingly baffling problem, in which removing a cout statement would break my program. As it turned out, my problem was that I forgot to return my true/false success flag that I was later using for ...
On x86 calling conventions, the return value for integers and pointers is on the EAX register. The following is an example of that: int func() { if(0) return 5; // otherwise error C4716: 'func' : must return a value } int main() { int a; a = func(); } Compiling with cl.exe /Zi, MSVC++10: push ebp mov ...
3,460,034
3,460,227
Declaring and initializing a static int in a header
If I have the following in a header file: Foo.h Foo { public: static const int BAR = 1234; ... }; Do I also need to define the variable in the .cpp, e.g.: Foo.cpp const int Foo::BAR; We have an issue where initializing a static in a header seems to work on MS compilers but with gcc on the Mac it seems to give lin...
You need both the declaration and the definition, just as you've written them. Since it is an integer, you can initialise it in the declaration as you've done, and the compiler should treat it as a compile-time constant when it can. But it still needs one (and only one) definition in a source file, or you'll get link e...
3,460,058
3,460,112
C++ How to loop dynamic arguments from function?
I need to loop all the dynamic arguments i have gave to my function, how? I mean this kind of code: void something(int setting1, int setting2, ...){ // loop somehow all the ... arguments and use setting1-2 values in that loop } setting1 and setting2 are not part of the dynamic argument list.
Use va_ functions. Here's an example: void PrintFloats ( int amount, ...) { int i; double val; printf ("Floats passed: "); va_list vl; va_start(vl,amount); for (i=0;i<amount;i++) { val=va_arg(vl,double); printf ("\t%.2f",val); } va_end(vl); printf ("\n"); } Your...
3,460,074
3,460,325
Initialize large two dimensional array in C++
I want to have static and constant two dimensional array inside a class. The array is relatively large, but I only want to initialize a few elements and others may be whatever compiler initializes them to. For example, if a class is defined like: class A { public: static int const test[10][10]; }; int const A::test[...
Any part of an array which is initialized, that is beyond the initialization, is initialized to 0. Hence: int const A::test[10][10]; // uninitialized int const A::test[10][10] = { {0} }; // all elements initialized to 0. int const A::test[10][10] = {1,2}; // test[0][0] ==1, test[0][1]==2, rest==0 That m...
3,460,264
3,461,131
handle management with boost::shared_ptr<>
I would like to use boost::shared_ptr<> to encapsulate the lifetime management of a handle. My handle and it's creation/destruction functions are declared like this: typedef const struct MYHANDLE__ FAR* MYHANDLE; void CloseMyHandle( MYHANDLE ); MYHANDLE CreateMyHandle(); Ideally, I would like to use the boost::shared...
Your shared_ptr type needs to be this: boost::shared_ptr< const MYHANDLE__ FAR> That way when shared_ptr makes a pointer out of it, it becomes: const MYHANDLE__ FAR* Which matches your MYHANDLE type exactly: #include <boost/shared_ptr.hpp> struct MYHANDLE__ {}; typedef const MYHANDLE__* MYHANDLE; void CloseMyHandle...
3,460,316
3,461,840
Boost autolinks libraries which are not built by Boost, but the intended ones are built
I am developing a Math application which can be extended by writing python scripts. I am using Qt 4.6.3 (built as static library, debug and release versions) and Boost 1.43.0 (built as static library, runtime-link also set to static, multi-threaded version, debug and release). Everything is built with MSVC++2008. Boost...
The problem is fixed, during the compilation of the boost libraries, I selected the link=static option. Which creates static libraries. I also selected runtime-link=static option, and this was wrong! The solution for this problem was compiling boost with runtime-link=shared. Now some extra libraries are added, with the...
3,460,352
3,524,272
Why is my paintBox Canvas being erased when my program is "Not Responding"?
I have written a small program using Borland's C++ builder, and along the way, everything seemed fine. My program has a map window and a table window, and when a user presses a button, a long process is started that reads in all the map and table information and then displays that. Every time i ran it through the debu...
Marcus Junglas wrote a detailed explanation of the problem, which affects both Delphi and C++Builder. When programming an event handler in Delphi (like the OnClick event of a TButton), there comes the time when your application needs to be busy for a while, e.g. the code needs to write a big file or compress...
3,460,355
3,460,498
Global Arrays in C++
Why the array is not overflowed (e.g. error alert) when the array is declared globally, in other why I'm able to fill it with unlimited amount of elements (through for) even it's limited by size in declaration and it does alert when I declare the array locally inside the main ? char name[9]; int main(){ int i;...
C++ does not have array bounds checking so the language never check to see if you have exceeded the end of your array but as others have mentioned bad things can be expected to happen. Global variables exists in the static segment which is totally separate from your stack. It also does not contain important information...
3,460,533
3,460,839
Why can't I use __declspec(dllexport) to export DllGetClassObject() from a COM DLL?
I am developing a COM dll and trying to export the DllGetClassObject() method with the __declspec(dllexport). Here is my declaration: extern "C" HRESULT __declspec(dllexport) __stdcall DllGetClassObject(REFCLSID rclsid, REFIID riid, void** ppv) But I kept ...
This problem occurs I think because a __stdcall function (for 32-bit builds) is normally decorated with a underscore prefix and an @count postfix. But if the function is also marked as __declspec(dllexport) additional decorations are added (__imp, I think). You might be able to avoid using a .def file with the follow...
3,460,559
3,460,625
c++ / gcc : segmentation fault at exit of main after catching a signal
The following code triggers a segmentation fault at exit. It seems to happen only if data is allocated on the stack between the 'sigaction' call and the loop : #include <signal.h> #include <unistd.h> bool end = false; void handler(int) { end = true; } int main() { struct sigaction sigs; sigs.sa_handler = handle...
You should initialize all members of your struct sigaction ,as to not risk having it contain garbage, there's flags/etc. in there that alter the behavior of sigaction() Do struct sigaction args = {}; or memset(&args,0,sizeof args);
3,460,880
3,460,964
Can a STL map be used with keys of varying sizes
Can a STL map be used for keys of varying sizes? I don't have code for this. I'm still trying to figure out if this can be done and hence my question. (I'm the type that can spend too much time on an impossible problem. I'm hoping to learn from your wisdom). I am working on a look up table that essentially has two keys...
std::map requires strict weak ordering for the keys. If you can enforce single order on your different key types with custom comparator then it shouldn't be a problem.
3,461,055
3,461,148
Factory pattern and class templates in C++
I have a hierarchy of class templates. At the top of the hierarchy is an abstract base class (interface). I won't know which concrete implementation to instantiate until runtime, so it seems like the perfect situation to use the factory pattern. However, virtual member function templates are not allowed in C++. How ...
Why can't you templatize IProductFactory on T as well? That would get rid of your error, and it's no less general. The client is still going to have to know what T is in order to call thecreateProduct method. Edit Re: comment In order to do this, you will need to just create a templatized function to create the facto...
3,461,247
3,461,326
C++ Project Structure
I'm now involved with a C++ project, and I've never developed in C++ before. The question I have is the structure of projects that are multi-platform. One developer is working in VC++ and another in XCode. XCode doesn't have literal directories, they're logical (groups) directories. Should big C++ projects have act...
Visual Studio will place all files in the project folder by default. It has 'filters' which I think are equivalent to XCode's groups; they're sort of like folders within the project, used to group files together, but not actual directories on the file system. Note the difference between your project and solution. Each ...
3,461,316
3,461,366
overloaded cast operator or single argument constructor
If a class has a single argument constructor my understanding is it is implicitly convertible by the constructor to the type of the argument in appropriate contexts. Defining a conversion operator also makes a class convertible to another type. Questions Does the conversion operator ever get called implicitly? If bo...
No, if a class has a single argument constructor is implicitly convertible from the type of its argument. As for your other questions: Does the cast operator ever get called implicitly? Yes, whenever it is needed. If both a single argument constructor and cast operator with the same type are defined for a class doe...
3,461,347
3,461,381
C++ doubles: dividing by 100 causes very small error
I'm having a problem with the specific set of values in this code snippet. double inputs[] = {0, -546543, 99015, 6750, 825, 2725, 70475, 50950, 42200, 6750, 26925, 16125, 134350, 10075, 79378}; double result = 0; for (int i = 0; i < 15; i++) { result += inputs[i]/100; } I expected the final value of result to...
I can't very easily add the numbers as integers and divide them later. Why not? That sounds like exactly the solution to your problem. Adding integers and dividing once is likely to much faster than adding floating-point numbers and dividing so much, too. You are just accumulating error every time you divide by 100...
3,461,444
3,461,629
Named namespace in implementation file to group const string literals - Good/Bad?
I've grouped several message strings into a named (non anonymous) namespace in the .cpp file for a class handling output as seen in the code below: namespace Messages { static const std::string AppTitle = "The Widgetizer - Serving all your Widget needs"; static const std::string SuccessMsg = "Great success! Widgets...
Is this a good practice generally or are there pitfalls to this that I'm not seeing? Grouping related objects in a namespace is good practice if it makes the code clearer; there aren't any particular pitfalls, but deeply nested namespaces can lead to excessively verbose code if you're not careful. Is the static keyw...
3,461,697
3,461,795
CString variable name prefix
Easy question for you vets out there: What is the accepted (assuming there is one...) prefix for a CString variable name? For clarification, I've seen the following for other data types: int iIndex; //integer int* pIndex; //pointer bool fFlag; //bool flag And there are countless others. Please feel free to let ...
Prefixes such as those are an abuse of the concept of Hungarian Notation. The idea of HN is that a variable is prefixed with a code describing its use. e.g., a variable holding the count of something would be prefixed cnt; a variable holding an index would be prefixed inx. A variable holding a flag would be prefixe...
3,461,718
3,461,759
Are tokens after #endif legal?
I currently do the following and the compiler (MSVC2008 / as well as 2010) doesn't complain about it but I'm not sure if it's a bad idea or not: #ifndef FOO_H_ #define FOO_H_ // note, FOO_H_ is not a comment: #endif FOO_H_ I used to always write it as #endif // FOO_H_ but I caught myself not doing that today and thou...
Strictly speaking (according to the grammar in the standard) no tokens are allowed following the #endif directive on the same line (comments are OK since they get removed at an earlier phase of translation than the preprocessing directives - phase 3 vs. 4). However, MSVC seems to allow it - I wouldn't go on a quest to ...
3,461,805
3,462,126
Is a WPF application managed code only?
I want to use WPF in an app. I want to write it in C++. Does the application have to be managed? I know that I can mix managed with unmanaged. I'm wondering if I can have the whole application be unmanaged.
You can easily develop 99% of your WPF application in unmanaged code, but making it 100% unmanaged is quite difficult. WPF classes don't have a Guid attribute, so they won't work with COM. So constructing WPF objects such as Button and Window with 100% unmanaged code requires one of the unmanaged CLR APIs. The Hostin...
3,461,809
3,461,880
Programmatically search + replace in a .doc
If I'm given a .doc file with special tags in it such as [first_name], how do I go about replacing all occurrences of it with something like "Clark"? A simple binary replacement only works if the replacement string is the exact same length. Haskell, C, and C++ answers would be best, but any compiled language would do. ...
You could use the Word COM component ("Word.Application") on Windows to open the file, do the replacements, save the file, and close it. However, this is Windows-only and can be buggy. Another thing you could do is use the OpenOffice.org command line interface to convert the file to the ODF format, unzip the file (ODF ...
3,461,976
3,462,042
Using a static initializer function
In this contrived example, I have a static initialization function that is run at construction time. I'd like to know if this a legal way to initialize a_, b_, and c_. Or, is it too early in the construction process to use them this way? DWORD SomeInitializationFunction( HANDLE*, DWORD*, DWORD* ); class MyClass { publ...
Members in a class are initialized in the order they are defined in the class. Thus if you have class A int t int u int v A() : v(0), u(1), t(2) {} Then despite the order in which you write the constructor arguments, first the value of t would be set, then the value of u and finally the value of v. So if y...
3,462,227
3,462,243
Weird output for bitwise NOT
I am trying to take one's complement of 0 to get 1 but I get 4294967295. Here is what I have done: unsigned int x = 0; unsigned int y= ~x; cout << y; My output is 4294967295 but I expect 1, why is this so? By the way, I am doing this in C++.
Why do you expect 1? Bit-wise complement flips all the bits. 00000000000000000000000000000000 = 0 | bitwise NOT | v 11111111111111111111111111111111 = 4294967295 Perhaps you are thinking of a logical NOT. In C++ this is written as !x.
3,462,264
3,466,263
Detect drive letter of SD card hardware
Is there a way to programatically detect the driver letter of an SD card(s) on Windows? Does the method support internal and external SD card hardware? Thank you for your time.
You can try GetLogicalDriveStrings to get the drive letters and then use GetDriveType to see, whether a drive is removable or not. Then you can get more device information like this (example is for cd-rom but should show you the idea): //handle to the drive to be examined HANDLE hDevice = CreateFile(TEXT("\\\\.\\G:"), ...
3,462,334
3,462,361
Getting image contents of obstructed window
Is it possible to get image contents of an obstructed window without bringing it to the front? Also, is it possible to send mouse clicks to a specific locations of such window using Windows API? Would the realization be different on Windows XP and Windows 7? What functions I would need and where can I read more about t...
Windows GDI can assist you on the screenshot task. There's some VB code here to get you started. There's a lot of material on how to simulate mouse clicks: http://tomicki.net/mouse.clicker.php Simulate Mouse move/click/keyPress in an application that is not active http://msdn.microsoft.com/en-us/library/ms171548.aspx
3,462,429
3,462,911
GLUTesselator for realtime tesselation?
I'm trying to make a vector drawing application using OpenGL which will allow the user to see the result in real time. The way I have it set up is with an edge flag callback so the glu tesselator only outputs triangles which I then pass to a VBO. I'v tried t make all my algorithms as fast as possible and this is not wh...
You might give poly2tri a try to see if it's any faster.
3,462,476
3,463,744
Access Cocoa and/or Carbon to automatically start on boot on OS X (on C++ also using QT)
I have a C++ application using the QT framework. I'm trying to add an option for the user to be able to set the program to start automatically on startup. My development machine is running OS X 10.6. As my main Mac reference, I'm using this Apple documentation. According to the documentation, there are two recommended ...
If you want to support 10.4 and up, you need to use the Carbon Apple Events API. The sample code you linked to worked on my OS X 10.6 box works without any problem, if you set the base SDK to 10.4u or 10.5. There are a few lines you need to remove if you want to compile it with 10.6 SDK, but if you want to support 10....
3,462,789
3,462,855
Can I default a function argument to the value of __FILE__ at the caller?
In C++, can I have a defaulted argument to a function which defaults to __PRETTY_FUNCTION___, ___FILE___, and ___LINE__ as defined at the point of the caller and not the point the defaults are supplied in a header file without using macros?
You can't, but you can acheive this behavior with an additional macro. For instance: #DEFINE THROW(e) throwException(e, __FILE__, __LINE__); On a side note, __PRETTY_FUNCTION__ is not standard.
3,462,831
3,462,976
How can I build VS 2010's C Runtime Library?
I need to modify the C runtime which ships with VS2010 because the 2010 CRT relies on functions released in Windows XP SP2, and I need to be able to deploy to Windows 2000. Specifically, I need to remove any and all calls to EncodePointer and DecodePointer. The source for the C runtime is included in C:\Program Files (...
Here's an MSDN link. It looks like you have to do it yourself in VS2010. You can use the following compiler and linker options to rebuild the MFC, CRT, and ATL libraries. Starting in Visual C++ 2010, scripts for rebuilding these libraries are no longer shipped.
3,462,917
3,463,007
C++/STL - Program crashes when accessing class pointer instance in a std::map
Okay, I have a function which reads a xml file and creates controls using new and stores them in public member variables of a class called Window: std::map<const char*, Button*> Buttons; std::map<const char*, TextBox*> TextBoxes; std::map<const char*, CheckBox*> CheckBoxes; The Button, TextBox and CheckBox classes are...
The problem likely is, that your map has const char* as keys - and that doesn't mean strings, but pointers. Which means it sees two different pointers to the same strings (eg. your string literal "Email" and characters "Email" you've read from the file) as different, hence it doesn't find the pointer to the textbox on ...
3,463,104
3,463,178
Linked list problems
Possible Duplicate: Copy a linked list Hello stackoverflow! I am trying to learn more about linked lists so I am trying to create a function that deep copies a linked list. I've got this under control. The hard part is that the input list is going to contain nodes that reference other random nodes within the list. F...
Use a std::map to store the conversion between the original and the new pointers. Walk the list two times: one time to create the new nodes (with pReference set to NULL) and to populate the map, a second time to fill in the pReference member by looking them up in the map. Untested code: Node* CopyNode(Node* src) { if...
3,463,236
3,463,253
C++ different -> and "."
Possible Duplicate: what is the difference between (.) dot operator and (->) arrow in c++ I'm trying to learn c++, but what I don't understand is the different between "->" and "." when calling a method. For example, I have seen something like class->method(), and class.method(). Thanks.
In a normal case, a->b is equivalent to (*a).b. If a is a pointer, -> dereferences it before accessing the element.
3,463,341
3,463,401
Hex editing with C++
Let's assume I want to change something in the 000F5344 address of an executable. How do I go about it?
@Pablo Santa Cruz provides an excellent way, but in C. If you prefer to go pure C++, here's how: Open file: fstream::open (remember to use the binary flag) Set the put pointer position: fstream::seekp Write data at the put pointer position: fstream::put Close file: fstream::close This is by no means better than the C...
3,463,471
3,463,529
How to set background color of window after I have registered it?
I am not using a dialog, I'm using my own custom class which I have registered and then used the CreateWindow call to create it, I have preset the background color to red when registering: WNDCLASSEX wc; wc.hbrBackground = CreateSolidBrush(RGB(255, 0, 0)); But now I want to change the background color at runtime, by e...
From Window Background comes: ...The system paints the background for a window or gives the window the opportunity to do so by sending it a WM_ERASEBKGND message when the application calls BeginPaint. If an application does not process the message but passes it to DefWindowProc, the system erases the b...
3,463,663
3,597,522
Threading newbie with issue with runaway threads
Ok, to you understand I will explain the problem: I am using a library called ClanLIB (not my choice), that library, SEEMLY (I am not certain, even reading the sourcE), creates a thread that handles sound. This thread, when the buffer is empty, tries to fetch more data, usually this cause a underrun when the data gener...
I actually, don't know what the issue was, it was fixed by accident... I had a related issue, this one was caused by race condition when deleting the thread... I moved some code around (I don't even needed to recode anything) and it went away too. Now the thing is perfectly stable! (well, still has underruns but they a...
3,464,578
3,464,596
When should we use method overloading vs method with different naming
Sometimes, I felt method overloading may create confusion. class a { public: void copy(float f); void copy(double d); }; a me; me.copy(1.2); // Not obvious at the first sight on which version we are calling. A workaround on this is. class a { public: void copyFloat(float f); void copyDouble(double d...
Overloading for sure. Okay, so it's not "obvious" which function gets called (arguable)...so what? You don't care that it can take different types of parameters, it just needs to do its thing. If you have different behavior based on different overloads, you've abused overloads, not pointed out a flaw in them. An exampl...
3,465,003
3,465,729
PostThreadMessage sets GetLastError to 1444
In PostThreadMessage my thread ID is correct, but I am getting the error 1444 ("Invalid thread identifier. "). Anyone know how to fix it?
The OS is the authority on whether thread IDs are valid, so if it's telling you your ID is invalid, then your ID is probably invalid. You have to trust the error codes until you can prove they're wrong, or else there's no use checking them at all. Before blaming the OS, make sure you've ruled out all other possibilitie...
3,465,042
3,466,125
pinch to zoom on windows mobile 6
Need to develop pinch-in pinch-out effect on HTC-HD2 with OS windows mobile 6.5. Is windows mobile 6.5 support this feature? If so can anyone provide me exposed APIs or sample code or any good links for doing it? So far I have implemented UI related stuff(zoom in-out using buttons etc) in C# .net using Windows Mobiles ...
I found a 3rd-party solution, SciLor's HD2 / Leo Multitouch .NET CF DLL, earlier, but have not used it myself yet...
3,465,302
3,466,223
Initializing C++ const fields after the constructor
I want to create an immutable data structure which, say, can be initialized from a file. class Image { public: const int width,height; Image(const char *filename) { MetaData md((readDataFromFile(filename))); width = md.width(); // Error! width is const height = md.height(); // Error! height is c...
You could cast away the constness in the constructor: class Image { public: const int width,height; Image(const char *filename) : width(0), height(0) { MetaData md(readDataFromFile(filename)); int* widthModifier = const_cast<int*>(&width); int* heightModifier = const_cast<int*>(&height)...
3,465,648
3,466,440
How to use gprof to profile a daemon process without terminating it gracefully?
Need to profile a daemon written in C++, gprof says it need to terminate the process to get the gmon.out. I'm wondering anyone has ideas to get the gmon.out with ctrl-c? I want to find out the hot spot for cpu cycle
Need to profile a daemon written in C++, gprof says it need to terminate the process to get the gmon.out. That fits the normal practice of debugging daemon processes: provision a switch (e.g. with command line option) which would force the daemon to run in foreground. I'm wondering anyone has ideas to get the gmon.o...
3,465,806
13,942,791
Create a desktop widget (like Yahoo Widgets or Google Gadgets) with Qt 4
How do I create with Qt 4 a window that remains anchored to the desktop as a widget ? (e.g. like Yahoo Widgets or Google Gadgets). I intend to give the same characteristics of a widget to a normal window: Remove the edges (easy to do) The window must not move (how ?) Must be displayed only when other windows are mini...
I think setting these flags will do what you are looking for: setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnBottomHint); Remove the edges ---> Qt::FramelessWindowHint will remove the edges The window must not move ---> (AFAIK) you can't move window when Qt::FramelessWindowHint flag is set Must be displaye...
3,465,809
31,262,958
how to interpret a freetype glyph outline when the first point on the contour is off curve
I'm actually working on a renderer that converts freetype glyphs into polylines to control a laser marking system. The problem I have is that I don't know how to handle correctly a contour beginning with an off curve point (99.9% begin with on curve points!). I've searched quite a while now for informations but I could...
FreeType uses three types of points: on-curve, quadratic control points (also known as 'conic') and cubic control points. The quadratic control points are grouped with on-curve points on either side of them to form the three points needed to define a quadratic Bézier spline. The cubic control points must occur in pairs...
3,465,976
3,465,990
What is the right way to typedef a type and the same type's pointer?
What is the right way to typedef a type and the same type's pointer? Here is what I mean. Should I do this: typedef unsigned int delay; typedef unsigned int * delayp; Or should I do this: typedef unsigned int delay; typedef delay * delayp; Or perhaps I should not typedef pointer at all and just use delay * instead of...
The right way is not to do it. Hiding the fact that something is a pointer is commonly seen as bad style.
3,466,309
3,466,990
What is the right way to allocate memory in the C++ constructor?
Which is the right way to allocate memory via new in the C++ constructor. First way in the argument list: class Boda { int *memory; public: Boda(int length) : memory(new int [length]) {} ~Boda() { delete [] memory; } }; or in the body of constructor: class Boda { int *memory; public: ...
I think the simplest way to do this would be to use a boost scoped array and let someone else's well tested library code handle it all for you. So: class Boda { boost::scoped_array<int> memory; public: Boda(int length) : memory(new int [length]) {} ~Boda() {} }; Moreover, scoped arrays cannot be...
3,466,337
3,466,381
What is better way to loop over two ranges - multiply them together and do it one loop, or loop over each range separately?
I can't decide how I should loop over ranges. This way: for (int i = 0; i < max_i; i++) { for (int j = 0; j < max_j; j++) { // first way - two loops } } Or this way: for (int k = 0; k < max_i*max_j; k++) { // second way - one loop } Thanks, Boda Cydo.
It depends on what you will be doing with the indices. If you're using two values separately (for example you're iterating over all permutations of the values in the two loops) then the two loop solution is more clear. The one-loop strategy is better if you don't care about the individual values but just their produc...
3,466,736
3,467,395
Render to FBO not working, gDEBugger says otherwise
I'm trying to render to a texture using an FBO. When trying to do so, gDEBugger shows the correct texture, but when drawing it on a quad its just "white" / the glColor4f. Here is the code to create the texture, fbo and renderbuffer: glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_T...
Your texture looks incomplete. You don't have mipmaps for it, and you did not select a filtering mode that would work-around that. Try: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); That said, you should still see the polygons, but without the proper texture, without this.
3,466,787
3,466,919
Inherited method with different type
i have something like this class A { virtual void doBla(A *a) = 0; }; class B : public A { virtual void doBla(B *b) { // do stuff ;}; }; and i want to do something like A* a = new B(); B* b = new B(); a->doBla(b); or: all children of A are supposed to have a method doBla which takes a parameter of the type...
You cannot overload functions across base/child classes, and doBla member function of class A must be public if you want to call it from outside: class A { public: virtual void doBla(A *a) = 0; }; class B : public A { virtual void doBla(A *a) { /*do stuff*/ } }; Edit: Note that the declaration of doBla func...
3,466,799
3,467,078
Getting the same memory again and again
In my program I am creating an object of a class in a loop and storing it in a vector. Then I print the address of the object and the member variable. After that I erase them . I see that every time I see the same address assigned to my object and the member variable which is a pointer. Can any one explain this behavi...
I think what you are looking for is storage based on a weak pointer. Your vector stores weak pointers to the connection objects. Your main application gets the shared pointers. The destructor for your connection object frees the resource. Periodically you can pack the vector by erasing all weak pointers with a use_coun...
3,466,984
3,467,210
Get current item from QMutableListIterator
I can't dereference a QMutableListIterator like an STL iterator - with *it. I'm trying to use QMutableListIterator::value() but my program crashes. What is the right way to do this? QFileInfoList files; // populate list QListIterator<QFileInfo> it(files); it.toFront(); QFileInfo = it_top.value(); // crash The error is...
I just checked the Qt documentation for "toFront" and it says: Moves the iterator to the front of the container (before the first item). http://doc.trolltech.com/latest/qmutablelistiterator.html#toFront The Qt Iterators are Java-style iterators which start before the items and end on the last item, the C++ style it...
3,467,059
3,469,323
preventing boost from making a copy of a my callback handler
I wrote a small tcp client using boost::asio, providing the following function: typedef boost::function<void(const bs::error_code& errCode, size_t bytesTransferred)> ReadHandler; void CTcpClient::AsyncRead2(std::vector<char>& data, size_t length, ReadHandler readCompletedCallback) { async_read(m_tcpData->socket, b...
The typical idiom I've used for completion handlers is boost::bind a member function using boost::shared_from_this to ensure the object in question does not go out of scope. This is prevalent in nearly all of the Boost.Asio examples as well. If you don't want to change your design you could try boost::ref, for example:...
3,467,097
3,467,645
Correctly getting sha-1 for files using openssl
I am trying to get an sha-1 for a number of files. What I currently do is cycle the files in a given path, open and read each file separately and load the contents in a buffer and then send it to openssl's SHA function to get the hash. The code looks something like this: void ReadHashFile(LPCTSTR name) { FILE * pF...
If you get trouble reading the file contents, prior to invoking the hash function code, then your problem is not related to hashing. You should use the standard fopen() function, rather than _tfopen(). In C, things which begin with an underscore character are often best avoided. Especially since _tfopen() seems to map ...
3,467,180
3,475,763
Direct C function call using GCC's inline assembly
If you want to call a C/C++ function from inline assembly, you can do something like this: void callee() {} void caller() { asm("call *%0" : : "r"(callee)); } GCC will then emit code which looks like this: movl $callee, %eax call *%eax This can be problematic since the indirect call will destroy the pipeline on o...
I got the answer from GCC's mailing list: asm("call %P0" : : "i"(callee)); // FIXME: missing clobbers Now I just need to find out what %P0 actually means because it seems to be an undocumented feature... Edit: After looking at the GCC source code, it's not exactly clear what the code P in front of a constraint means....
3,467,261
3,467,287
Can I trick access to private C++ class member variables?
Possible Duplicate: Accessing private members Is it possible to access private members of a class? Is there a good (yes I know this is ugly) way to hack to the private data members of a class? One brute force approach is to copy the header file and in my copy change private to public. But would there be a better way...
There are lots and lots of ways of doing this - all of them bad. Protection in C++ is there for a purpose, to prevent you from making mistakes. It is not there as a security measure. If you want public access, just make things public!
3,467,332
3,467,388
Where can I find a good Scope Guard implementation for my C++ projects?
I just recently learned about Scope Guard C++ idiom. Unfortunately I can't find any good implementation of it. Can anyone point me to some good and usable Scope Guard implementation in C++? Thanks, Boda Cydo.
ScopeGuard has been included in the Loki library (advertised in Modern C++ Design by Andrei Alexandrescu, I'm sure you've heard of this great book), and is mature enough to be used in production code, imo. Just to be clear: We're talking about writing exception safe code using RAII. Additional reading (on StackOverflow...
3,467,444
3,469,237
invalid cruntime parameter _itoa_s
I have experienced a strange behavior when using _itoa_s and _ultoa_s if I try to get a char array from an DWORD. The function returns zero(success) and my application continues, but I'm getting an exception window with error code 0xc0000417 (STATUS_INVALID_CRUNTIME_PARAMETER). ULONG pid = ProcessHandleToId(hProcess); ...
Yes, the safe CRT functions will abort your program with status code 0xc0000417 when they detect a problem. However, they will do this immediately, the function will not return. Which means that you are looking at the wrong source code for this problem. It isn't the _ultoa_s() call that's bombing your program. It's ...
3,467,672
3,468,085
Partially specialize template member function
I have a template class which looks like the following: template <template <class TypeT> class PoolT=pool_base> struct pool_map { public: template <typename U> struct pool { typedef PoolT<U> type }; public: template <typename T, size_t S=sizeof(T)> T& get( size_t index ); private: pool<uint8_t>::type pool8_;...
There is one easy solution (maybe you didn't think about it), which is: template <typename T> T& pool_map<PoolT>::get( size_t index ) { if (sizeof(T) * CHAR_BIT == 8) { // Dispatch to pool8_ } else if (sizeof(T) * CHAR_BIT == 16) { // Dispatch to pool16_ } else if (...) { ... } else { // Defa...
3,467,716
3,468,017
Safe c++ in mission critical realtime apps
I'd want to hear various opinions how to safely use c++ in mission critical realtime applications. More precisely, it is probably possible to create some macros/templates/class library for safe data manipulation (sealing for overflows, zerodivides produce infinity values or division is possible only for special "nonze...
For good rules on how to write C++ for mission critical real-time applications have a look at the Joint Strike Fighter coding standards. Many of the rules there are based on the MISRA C coding standards, which I believe are proprietary. PC-Lint is a C++ code checker with rule sets like what you want (including the MI...
3,467,798
3,467,960
Bit fields and endianness
I have defined the following struct to represent an IPv4 header (up until the options field): struct IPv4Header { // First row in diagram u_int32 Version:4; u_int32 InternetHeaderLength:4; // Header length is expressed in units of 32 bits. u_int32 TypeOfService:8; u_int32 TotalLength:16; //...
The most portable way to do it is one field at a time, using memcpy() for types longer than a byte. You don't need to worry about endianness for byte-length fields: uint16_t temp_u16; uint32_t temp_u32; struct IPv4Header header; header.Version = cIPHeaderSample[0] >> 4; header.InternetHeaderLength = cIPHeaderSample[...
3,467,805
3,467,875
How precise is Task Manager?
I have a C++ Application, when I observe Task Manager, it shows that applicaiton's memory usage increases gradually. I manually check my source code, and I used Visual Leak Detector for Visual C++ to find memory leak, but I couldn't find any. Is it 100% that there is a memory leak, and I couldn't find it or is there an...
It isn't. It has several options for memory statistics (use View + Columns) and the version matters but the default view shows the working set. How much of the virtual memory your program uses is actually in RAM. That's a statistical number that can change very quickly. Just minimize the main window of your app for...
3,467,997
3,468,024
Changing a classes member through an iterator
I'm learning C++ and can't get my head around this problem: I have a simple class A class A { private: int ival; float fval; public: A(int i = 0, float f = 0.0) : ival(i), fval(f) { } ~A(){ } void show() const { cout << ival << " : " << fval << "\n"; } void setVal(int i) { ...
The STL set does not let you change values it stores. It does that by returning a copy of the object through the iterator (not the actual one in the set). The reason that set does this is because it's using < to order the set and it doesn't want to remake the entire tree every time you dereference the iterator, which i...
3,468,309
3,469,651
What is the best way to create an rw pipe with c++?
I have a program A that needs to send commands to the stdin of a program B and reads back the output of this program B. (Programming in C++, not linux only) ProgramA -> send letter A -> ProgramB ProgramA <- output of B <- ProgramB I actually have the first part, send commands to B, working with popen(). I do know that ...
Using posix functionality (so, will work on linux and any system that complies with posix standard), you can use a combination of pipe/execl/dup. In short what happens is: create 2 pipes (one to read and one to write to the child) fork the current process. This keeps open the same fd close the current stdin/stdout. Th...
3,468,456
3,468,489
Dangling pointer example
In the following code, why does s1.printVal causes a dangling pointer error? Isn't the s1 object, i.e. its pointer, still accessible until it's destroyed? class Sample { public: int *ptr; Sample(int i) { ptr = new int(i); } ~Sample() { delete ptr; } void PrintVal() ...
The problem here is the copy that is done for argument of the SomeFunc(). That copy de-allocates your pointer when destroyed. You need to also implement a copy constructor, and copy assignment operator. See rule of three. Edit: Here's "expanded" pseudo-code, i.e. what the compiler does for you in the main() function: /...
3,468,502
3,468,561
Using AfxEnableMemoryTracking to detect Memory leaks
Has anybody personally used AfxEnableMemoryTracking function provided by MFC to detect memory leaks. How useful is it?
Memory tracking is enabled by default in MFC Debug builds. AfxEnableMemoryTracking is mostly used to temporary disable memory tracking in some code fragments, if it is necessary. To use MFC built-in memory leaks detection, ensure that every .cpp file contains the following code after all #include lines: #ifdef _DEBUG ...
3,468,958
3,469,335
Can static_cast turn a non-null pointer into a null pointer?
I need to write code for a callback function (it will be called from within ATL, but that's not really important): HRESULT callback( void* myObjectVoid ) { if( myObjectVoid == 0 ) { return E_POINTER; } CMyClass* myObject = static_cast<CMyClass*>( myObjectVoid ); return myObject->CallMethod(); } ...
static_cast can change the pointer value, if you cast between object parts on different offsets: class A{ int x; }; class B{ int y; }; class C : A,B {}; C *c=new C(); B *b=c; // The B part comes after the A part in C. Pointer adjusted C *c2=static_cast<C*>(b); // Pointer gets adjusted back, points to the beginni...
3,469,021
3,469,099
typedef function pointer inheritance
I can have a typedef function pointer in a class like this: template<typename T> class MyClass { public: typedef T (*fptr)(T); void doSomething(fptr my_fptr) { /*...*/ } }; and this works fine. but if I inherit from such a class, as below: template<typename T> class MyClass { public: typedef T (*fptr)(T); v...
You should be able to inherit public typedefs like that. Did you try something like this to make sure the compiler know it's a parent type: void doSomething(typename MyClass<T>::fptr my_fptr) { /*...*/ }
3,469,463
3,476,222
Boost Filesystem: recursive_directory_iterator constructor causes SIGTRAPS and debug problems
I want to use the recursive_directory_iterator offered by boost::filesystem to delete a directory. But at construction time the debugger stops with the message Signal Received: Sigtrap . I can choose to continue ( have to do it several times because multiple Sigtraps are caught ) and the program will work as expected, ...
After a lot of searching and asking around I solved the problem. This question (or rather the answer) gave me a hint: Does getting random SIGTRAP signals (in MinGW-gdb) is a sign of memory corruption? It seems to be a matter of trying to access corrupted memory, which is caused by using an uninitialized dynamic library...
3,469,588
3,469,630
Pedantic: What Is A Source File? What Is A Header?
For the purposes of this question, I am interested only in Standard-Compliant C++, not C or C++0x, and not any implementation-specific details. Questions arise from time to time regarding the difference between #include "" and #include <>. The argument typically boils down to two differences: Specific implementations...
Isn't this saying that a header may be implemented as a source file, but there again may not be? as for "what is a source file", it seems very sensible for the standard not to spell this out, given the many ways that "files" are implemented.
3,469,683
3,472,246
Naming throw-away identifiers of global scope
Sometimes, when using macros to generate code, it is necessary to create identifiers that have global scope but which aren't really useful for anything outside the immediate context where they are created. For example, suppose it's necessary to compile-time-allocate an array or other indexed resource into chunks of va...
Is there any normal convention for naming such identifiers to minimize the likelihood of conflicts, and also to minimize any confusion they might generate? It all boils down to the prefix you want to use. Ideally, one would want all the symbols to be easily associated with the list (HP_LIST) they are related to. So w...
3,469,734
3,469,929
The letter near a digit constant in C++?
What does the letter near the digit constant mean? Just for example: int number = 0; float decimal = 2.5f; number = decimal; What's difference betweet 2.5f and f2.5 ? I have already looked in manuals, but I really cant understand it. Explaine it me please in a simple format.
Purely as additional information (not really a direct answer to the question) I'd note that to specify the type of a character or string literal, you use a prefix (e.g., L"wide string"), whereas with a numeric literal you use a suffix (e.g., 2L or 3.5f). C++0x adds quite a few more of both prefixes and suffixes to spec...
3,470,003
3,470,137
Wrapping #include directives with other preprocessor commands
I'm working on a project that uses lots of external libraries. Now, I like my projects to compile with the highest warning level available, which on MSVC is /W4. I'm also using -Wall on GCC for this project, which needs to be cross-platform. With /W4, I'm hitting a problem: I'm often including the headers of the other ...
I'm not aware of a single line solution like the one you want but MSVC does have a __pragma keyword that you can use inside a preprocessor macro. So you can do something like this: #if defined(_MSC_VER) # define SET_LOWER_WARNING_LEVEL __pragma(warning(push, 3)) # define RESET_DEFAULT_WARNING_LEVEL __pragma(war...
3,470,047
3,470,097
template specialization inside class namespace
How to specialize a template defined in some external namespace in the body of my class? Concrete example using BGL which doesn't compile: class A { namespace boost { template <class ValueType> struct container_gen<SomeSelectorS, ValueType> { typedef std::multiset<ValueType,MyClass<ValueType> > ty...
You cannot create namespaces inside classes, and you cannot specialize a template in a namespace scope inside a class.
3,470,189
3,470,308
Why can't templates take function local types?
In C++ it's OK to have a funcction that takes a function local type: int main() { struct S { static void M(const S& s) { } }; S s; S::M(s); } but not OK to have a template that does: template<typename T> void Foo(const T& t) { } int main() { struct S { } s; Foo(s); // Line 5: error: no matching function f...
I'm guessing it is because it would require the template to be effectively instantiated within the scope of the function, since that is where such types are visible. However, at the same time, template instantiations are supposed to act as if they are in the scope in which the template is defined. I'm sure this it's ...
3,470,200
3,470,241
Auto detaching objects?
I have a mother class that stores the pointers to some objects in a list. I want these objects to detach themselves from the list when they are destroyed. Can anyone suggest some good ways to do this please?
The crude way is to store the container reference (or pointer) in the objects in the list and remove themselves in their destructors: class Contained; class Container { std::list<Contained*> children; public: ... void goodbye(Contained*); }; class Contained { Container& c; // you set this in the constructor pub...