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
749,520
749,538
How to write my own wrapper in C#?
In my other question, I've been trying to find someone who knows where to find free open source OCR library for C#. However, it seems there is only C++ library and obviously, C++ is not C#. One of the responds suggested to write my own wrapper in C#. I have pretty much no idea how to do it, where to learn to do it, or ...
You can get a good start here: Call Unmanaged Code. Part 1 - Simple DLLImport
749,632
749,642
Thoughtworks Cruise: Unit Testing?
I'm evaluating Cruise (NOTE! Not CruiseControl but Cruise (commercial)) for doing CI with an unmanaged MSVC++ 2008 project. I use GoogleTest framework for my unit test. I know that GTest can output its result as an JUnit XML or XML format. My question is, does Cruise support JUnit/XML format? How would Cruise know whet...
According to the documentation, yes it does support the JUnit xml format. See the bottom of the page. Second to last section called "Publishing tests" http://studios.thoughtworks.com/cruise-continuous-integration/1.2/help/managing_artifacts_and_reports.html
749,757
749,842
C++ Class Serialization
I quite recently learned about the C++ classes friend keyword and the uses in serialization and now I need some help in getting it to work. I have no problem serializing my class to a file, it's working great, however i'm having a hard time trying to read this file into a vector container. I'm sure I need a loop in my ...
It looks like you pretty much have all the code you need already! I copied your code and compiled it with some changes to read the SalesPeople in from a file in a loop. I will include the changes below, but since this is for your homework, you may just want to read and think about the following hints before looking a...
749,865
754,496
C++ mutable appropriate in this case?
I would like to ask if the use of mutable is appropriate here: #include <iostream> class Base { protected: int x; public: virtual void NoMod() const { std::cout << x << std::endl; } void Draw() const { this->NoMod(); } }; class Derive : public Base { private: mutable int y; public: void ...
As 'head geek' described, the answer to your question depends on how your data member is used. I distinguish two types of data members in a class. I use the common term 'attribute' to refer to data members that are the logical state or 'value' of the object. Typically attributes are rarely declared as mutable. I have c...
750,087
750,171
Structure for hierarchal Component storage
I've been batting this problem around in my head for a few days now and haven't come to any satisfactory conclusions so I figured I would ask the SO crew for their opinion. For a game that I'm working on I'm using a Component Object Model as described here and here. It's actually going fairly well but my current storag...
You should think about how often you need to do the following: traverse the tree add/remove elements from the tree how many objects do you need to keep track of Which is more frequent will help determine the optimum solution Perhaps instead of make a complex tree, just have a list of all types and add a pointer to th...
750,178
750,197
Is it a good idea to typedef pointers?
I looked through some code and noticed that the convention was to turn pointer types like SomeStruct* into typedef SomeStruct* pSomeStruct; Is there any merit to this?
This can be appropriate when the pointer itself can be regarded as a "black box", that is, a piece of data whose internal representation should be irrelevant to the code. Essentially, if your code will never dereference the pointer, and you just pass it around API functions (sometimes by reference), then not only does ...
750,336
750,350
Is STL vector a better version of realloc?
In C++, I believe, a better way of dealing with reallocation is to use a STL vectors, as it guarantees the contiguous storage locations. I have couple question to understand the difference: Is there any scenario in which I need to prefer realloc over vector ? Is there anything else ( apart from vector ) which is equi...
It is only vector, which is guaranteed to have contiguous memory. Not the others. realloc is a C memory management function. It's use is not encouraged in C++ code. Here's Stroustrup telling you why: Why doesn't C++ have an equivalent to realloc()? However, realloc() is only guaranteed to work on arrays allocated by ...
750,464
750,480
Comments in source code
How to keep the source code well documented/commented? Is there a tool to generate a skeleton for comments on the Unix platform for C++? In general, how many lines of comments is recommended for a file with around 100 lines of code?
Generally, it's best to let the code itself explain what it does, whereas the comments are there to describe why it's like that. There is no number to stick to. If your 100 lines speak for themselves, don't comment at all or just provide a summary at the beginning. If there is some knowledge involved that's beyond what...
750,635
750,662
dsn less connection using text driver
I am trying to do ODBC import with DSN-Less connection(using text driver). Is there any way to tell SQLDriverConnect to set COLNAMEHEADER=yes/no? OR I need to use schema.ini to do it? Actually i don't want to create schema.ini manually, Can I use SQLConfigDataSource for dsn less connection? I haven't found any docs r...
Create the schema.ini programatically before you open the text file via SQLDriverConnect. I don't see how SQLConfigDataSources can help you here, as it is specifically intended for manipulating DSNs and you don't have one.
750,941
750,973
double.Epsilon vs. std::numeric_limits<double>::min()
Why double.Epsilon != std::numeric_limits<double>::min()? On my PC: double.Epsilon == 4.9406564584124654E-324 and is defined in .NET std::numeric_limits<double>::min() == 2.2250738585072014e-308 Is there a way to get 2.2250738585072014e-308 from .NET?
They're different because double.Epsilon returns the smallest representable value. numeric_limits<double>::min() returns the smallest normalized value. Basically double.Epsilon is the equivalent to numeric_limits<double>::denorm_min(). The easiest way of getting the equivalent in .NET is probably to work out the bit pa...
751,100
751,111
Checking if a particular device driver is loaded
I'm trying to work out if I can check if a particular video card device driver is loaded in Windows Server 2003 using C++. Can anyone give me pointers on how I might achieve this? Thanks
Use EnumDeviceDrivers - there's an example here.
751,119
751,147
Case Sensitive Partial Match with Boost's Regex
From the following code, I expect to get this output from the corresponding input: Input: FOO Output: Match Input: FOOBAR Output: Match Input: BAR Output: No Match Input: fOOBar Output: No Match But why it gives "No Match" for input FOOBAR? #include <iostream> #include <vector> #include <fstream> #include <s...
Your regular expression has to account for characters at the beginning and end of the sub-string "FOO". I'm not sure but "FOO*" might do the trick match_partial would only return true if the partial string was found at the end of the text input, not the beginning. A partial match is one that matched one or more cha...
751,136
751,165
How do you pass a reference when using a typename as a function argument in C++?
I have some weird problem with templates. When trying to pass a parameterised iterator it complains that no function can be found. The code snippet is here, forget about the functionality, it's using the reference to the templatized iterator what interests me #include <list> #include <iostream> template<typename T> vo...
g++ can't figure out which template overload of print_list_element it should use. If you explicitly specify the template parameter it works: print_list_element<int>(it);
751,840
752,458
How do I make textures transparent in OpenGL?
I've tried to research this on Google but there doesn't appear to me to be any coherent simple answers. Is this because it's not simple, or because I'm not using the correct keywords? Nevertheless, this is the progress I've made so far. Created 8 vertices to form 2 squares. Created a texture with a 200 bit alpha value...
So the other answer which was here but was deleted mentioned this - Generally, for alpha blending to work correctly you need to sort the objects from far to near in the coordinate system of the camera. This is why your polygons are blended with the background. You can confirm that this is indeed the problem by disablin...
751,878
751,891
Determine array size in constructor initializer
In the code below I would like array to be defined as an array of size x when the Class constructor is called. How can I do that? class Class { public: int array[]; Class(int x) : ??? { } }
You can't initialize the size of an array with a non-const dimension that can't be calculated at compile time (at least not in current C++ standard, AFAIK). I recommend using std::vector<int> instead of array. It provides array like syntax for most of the operations.
751,940
751,961
problem with containers: *** glibc detected *** free(): invalid pointer: 0x41e0ce94 ***
I have a C++ program on Linux that crashes after some time with the message: *** glibc detected *** free(): invalid pointer: 0x41e0ce94 *** Inside the program I make extensive use of containers. They have to store objects of a simple class. EDIT 2009-4-17: In the meantime it seems clear that the error has nothing to d...
Consider using a std::string to hold the string value instead of a raw char pointer. Then you won't have to worry about managing the string data in your assignment, copy, and destruction methods. Most likely your problem lies there. Edit: There's no issue with the newer class you posted, and no problem with the first...
751,966
751,970
What are the negative consequences of including and/or linking things that aren't used by your binary?
Let's say that I have a binary that I am building, and I include a bunch of files that are never actually used, and do the subsequent linking to the libraries described by those include files? (again, these libraries are never used) What are the negative consequences of this, beyond increased compile time?
A few I can think of are namespace pollution and binary size
751,994
752,024
C++ compression (zip) library for closed-source app
Please recommend a C++ compression (zip) library for a commercial, closed-source application. So, not a GPL license. This is for my day job...
I know you said C++, but zlib is a very permissively licensed C library that you could use directly from a C++ app. If I recall correctly, there are various "iostream-like" wrappers around zlib available, too.
752,006
752,098
What's the recommended way to get winhttp.h?
Our application uses libcurl for HTTP, and we want to get access to Internet Explorer's proxy settings. An earlier Stack Overflow question recommends that we use WinHttpGetIEProxyConfigForCurrentUser and WinHttpGetProxyForUrl. Unfortunately, the winhttp.h header does not appear to be included with our copies either Vis...
The best, well-supported way to access the WinHTTP 5.1 APIs from C++ is via the Windows SDK (new name for the Platform SDK) and using those APIs you mentioned. The article you linked to suggests that installing the SDK is difficult - the good news is its an old article from 2006 and things are much easier these days. J...
752,166
752,305
Splitting up a utility DLL into smaller components in C++
We have a core library in the form of a DLL that is used by more than one client application. It has gotten somewhat bloated and some applications need only a tiny fraction of the functionality that this DLL provides. So now we're looking at dividing this behemoth into smaller components. My question is this: Can a...
Without having all the details it is a little hard to help but here is what I would do in your situation provide both static and dll versions of whate3ver you release - for MT and single threaded. try to glean from the disparate clients which items should be grouped together to provide reasonable segmentation - with...
752,309
752,984
Ensuring C++ doubles are 64 bits
In my C++ program, I need to pull a 64 bit float from an external byte sequence. Is there some way to ensure, at compile-time, that doubles are 64 bits? Is there some other type I should use to store the data instead? Edit: If you're reading this and actually looking for a way to ensure storage in the IEEE 754 format, ...
An improvement on the other answers (which assume a char is 8-bits, the standard does not guarantee this..). Would be like this: char a[sizeof(double) * CHAR_BIT == 64]; or BOOST_STATIC_ASSERT(sizeof(double) * CHAR_BIT == 64); You can find CHAR_BIT defined in <limits.h> or <climits>.
752,479
752,498
Am I initializing my C++ reference variables correctly?
I've tried to Google this issue, and I can't find anything that I see as relevant. So I must be looking for the wrong thing; none the less, I'd appreciate some advice... Foobar &foobar = *new Foobar(someArg, anotherArg); Is it just me or does that seem smelly? I understand that the new keyword is designed for use with...
Why do you think you need to use new and references at all? Why not: Foobar foobar(someArg, anotherArg); For your function - return a value: Foobar helloWorld() { Foobar foobar(someArg, anotherArg); foobar.HelloWorld(); return foobar; } or a pointer: Foobar * helloWorld() { Foobar * foobar = new Foob...
752,492
763,478
Replying to a client over sockets (UDP) from a different process
I have a server than is a "command handler" process. It receives messages over UDP, and delegates the work to do to a different process by communicating to that process through it's published API (whatever IPC mechanism that process employes). Our system has several cooperating processes. The result of that API call...
Your client (or a firewall in between) will likely get confused by receiving the response from a different source port than it sent the request to (as the OS will just pick a random source port for the new socket). One way around this is to use the SO_REUSEADDR socket option in the server and explicitely bind to the co...
752,658
752,699
Is the practice of returning a C++ reference variable evil?
This is a little subjective I think; I'm not sure if the opinion will be unanimous (I've seen a lot of code snippets where references are returned). According to a comment toward this question I just asked, regarding initializing references, returning a reference can be evil because, [as I understand] it makes it easie...
In general, returning a reference is perfectly normal and happens all the time. If you mean: int& getInt() { int i; return i; // DON'T DO THIS. } That is all sorts of evil. The stack-allocated i will go away and you are referring to nothing. This is also evil: int& getInt() { int* i = new int; return ...
752,762
752,773
Is it good to have all the setter functions return a reference to the object in c++?
Is it good to have all the setter functions return a reference to the object in c++?
It's a usable enough pattern if there's a lot of things that need to be set on an object. class Foo { int x, y, z; public: Foo &SetX(int x_) { x = x_; return *this; } Foo &SetY(int y_) { y = y_; return *this; } Foo &SetZ(int z_) { z = z_; return *this; } }; int main() { Foo foo; ...
752,793
752,875
Should C++ eliminate header files?
Many languages, such as Java, C#, do not separate declaration from implementation. C# has a concept of partial class, but implementation and declaration still remain in the same file. Why doesn't C++ have the same model? Is it more practical to have header files? I am referring to current and upcoming versions of C++...
I routinely flip between C# and C++, and the lack of header files in C# is one of my biggest pet peeves. I can look at a header file and learn all I need to know about a class - what it's member functions are called, their calling syntax, etc - without having to wade through pages of the code that implements the class....
753,312
753,461
Returning Large Objects in Functions
Compare the following two pieces of code, the first using a reference to a large object, and the second has the large object as the return value. The emphasis on a "large object" refers to the fact that repeated copies of the object, unnecessarily, is wasted cycles. Using a reference to a large object: void getObjData(...
The second approach is more idiomatic, and expressive. It is clear when reading the code that the function has no preconditions on the argument (it does not have an argument) and that it will actually create an object inside. The first approach is not so clear for the casual reader. The call implies that the object wil...
753,440
753,541
Should network packet payload data be aligned on proper boundries?
If you have the following class as a network packet payload: class Payload { char field0; int field1; char field2; int field3; }; Does using a class like Payload leave the recipient of the data susceptible to alignment issues when receiving the data over a socket? I would think that the class would eith...
You should look into Google protocol buffers, or Boost::serialize like another poster said. If you want to roll your own, please do it right. If you use types from stdint.h (ie: uint32_t, int8_t, etc.), and make sure every variable has "native alignment" (meaning its address is divisible evenly by its size (int8_ts are...
753,564
753,631
Templated namespaces and typedefs are illeagal -- workarounds?
I have a templated function fct that uses some complex data structure based on the template parameter. It also calls some helper functions (templated on the same type) that are in a separate helpers namespace and use the same complex data structure. Now it gets really ugly because we cannot make one typedef for the com...
Are there other solutions/workaround that make the "templated typedef" / "templated namespace" possible? GOTW #79: Template Typedef The New C++ Typedef Templates (See Section 1: The Problem and Current Workarounds)
753,764
754,668
Problem clearing Listview Header image on Vista
I'm having a problem on Vista with the Listview control, in particular setting custom icons on the header. Normally under XP or any of the previous version of Windows, if I added an icon (in C++), I could do so with the following: HeaderItem.mask = HDI_FORMAT | HDI_IMAGE; Header_GetItem(HeaderHWND, Column, &Header...
If you read the documentation http://msdn.microsoft.com/en-us/library/bb775247(VS.85).aspx, if you indicate HDI_IMAGE in mask then iImage should be a valid index, you have to set it to I_IMAGENONE in order to remove it. If you want to remve an image you have to do something like this: HeaderItem.mask = HDI_FORMAT | HDI...
754,065
795,722
Is there any way to prevent Boost.Build from recursively scanning header files for #include directives?
Is there a way to limit the header files that Boost.Build recursively scans for #include directives to a particular directory or set of directories? I.e. I'd like it to recursively scan the header files within my project only. I know that they external dependencies are not going to change (and being Boost and Qt they'r...
This question was also posted on the Boost mailing list and we got an answer to it here: http://lists.boost.org/boost-build/2009/04/21734.php. So it seems so far that the answer is that, at least out of the box, Boost.Build doesn't have this feature, and the solution is to customise Boost.Build to your needs, which mak...
754,355
754,533
Cross-Platform Generic Text Processing in C/C++
What's the current best practice for handling generic text in a platform independent way? For example, on Windows there are the "A" and "W" versions of APIs. Down at the C layer we have the "_tcs" functions (like _tcscpy) which map to either "wcscpy" or "strcpy". And in the STL I've frequently used something like: typ...
There is no support for a generic (variable-width) chararacter like TCHAR in standard C++. C++ does have wchar_t, but the encoding isn't guaranteed. C++1x will much improve things once we have char16_t and char32_t as well as UTF-{8,16,32} literals. I personally am not a big fan of generic characters because they lead ...
754,729
754,754
Copy constructor initialization lists
I know that if you leave a member out of an initialization list in a no-arg constructor, the default constructor of that member will be called. Do copy constructors likewise call the copy constructor of the members, or do they also call the default constructor? class myClass { private: someClass a; someOtherC...
Explicitly-defined copy constructors do not call copy constructors for the members. When you enter the body of a constructor, every member of that class will be initialized. That is, once you get to { you are guaranteed that all your members have been initialized. Unless specified, members are default-initialized in th...
754,865
754,894
View Compiler Mangled Names in C++
How do I view the compiler-generated mangled names for overloaded functions in C++? I'm using VC9 but answers for other compilers are welcome too. Edit: I find all the answers useful here. Accepting the one I liked best.
You could look in the map file. Assuming you have map file generation turned on.
755,028
755,055
Overloading a method on default arguments
Is it possible to overload a method on default parameters? For example, if I have a method split() to split a string, but the string has two delimiters, say '_' and "delimit". Can I have two methods something like: split(const char *str, char delim = ' ') and split(const char *str, const char* delim = "delimit"); O...
How about implementing as 2 different methods like split_with_default_delimiter_space split_with_default_delimiter_delimit Personally I'd prefer using something like this (more readable.. intent conveying) over the type of overloading that you mentioned... even if it was somehow possible for the compiler to do that....
755,164
755,964
COM API - could not pass "NULL" for a pointer argument
I have a COM API foo, the IDL looks like: foo([in] unsigned long ulSize, [in, size_is(ulSize)] unsigned char* pData) when I consume this function with foo(0,NULL); I get an error - NULL argument passed. Is there a way to workaround this?
Don't use char* in COM APIs -- use BSTR instead. Then pass an empty string. foo([in] unsigned long ulSize, [in] BSTR pData) ... foo(1, _bstr_t(""));
755,196
755,206
Deleting a pointer to const (T const*)
I have a basic question regarding the const pointers. I am not allowed to call any non-const member functions using a const pointer. However, I am allowed to do this on a const pointer: delete p; This will call the destructor of the class which in essence is a non-const 'method'. Why is this allowed? Is it just to sup...
It's to support: // dynamically create object that cannot be changed const Foo * f = new Foo; // use const member functions here // delete it delete f; But note that the problem is not limited to dynamically created objects: { const Foo f; // use it } // destructor called here If destructors could not be called o...
755,347
755,354
Are const_iterators faster?
Our coding guidelines prefer const_iterator, because they are a little faster compared to a normal iterator. It seems like the compiler optimizes the code when you use const_iterator. Is this really correct? If yes, what really happens internally that makes const_iterator faster?. EDIT: I wrote small test to check cons...
If nothing else, a const_iterator reads better, since it tells anyone reading the code "I'm just iterating over this container, not messing with the objects contained". That's a great big win, never mind any performance differences.
755,372
755,386
Spawned processes becoming defunct
I use posix_spawnp to spawn child processes from my main process. int iRet = posix_spawnp(&iPID, zPath, NULL, NULL, argv, environ); if (iRet != 0) { return false; } Sometimes, after a child process is spawned without errors, it suddenly becomes defunct. How could this occur? I use...
This: kill(oProcID, SIGKILL); signal (SIGCHLD, SigCatcher); looks like a race condition. You need to install the signal handler before killing the child process, otherwise you risk missing the signal.
755,575
757,530
Is there a way to group a set of soap methods logically in a "class" type entity?
For our large C++ based project we now have a method to automatically generate code to expose our code as SOAP methods. This works really well, and we are planning to start implementing an RIA based application using Adobe AIR / Flex based on the API's we have exposed. The question I have is about organizing SOAP we...
I've spent the afternoon looking into this and it seems I have two options, both of which I have mocked up, and both of which work: I'm just unsure which is best now! Separate the methods in different "services" grouped logically dependent on the class they came from. It is possible to include multiple SOAP "services"...
755,726
755,757
error C2664: in c++?
for (int v = 0; v <= WordChosen.length();v++) { if(Letter == WordChosen[v]) { WordChosenDuplicate.replace(v,1,Letter); } } I get this error "Error 4 error C2664: 'std::basic_string<_Elem,_Traits,_Ax> &std::basic_string<_Elem,_Traits,_Ax>::replace(__w64 unsigned int,__w64 unsigned int,c...
Or WordChosenDuplicate.replace(v,1,std::string(Letter, 1));
755,783
755,880
What's the use of .map files the linker produces?
What is the use of .map files VC++ linker produces when /MAP parameter or "Generate map file" project setting is used? When do I need them and how do I benefit from them?
A nice article on how to use map files for finding crashes. http://www.codeproject.com/KB/debug/mapfile.aspx Manually doing all this is very uninteresting. I am not aware of any tools which can read map file and help in finding the crash location. If anybody knows please update us.
755,835
755,845
How to add element to C++ array?
I want to add an int into an array, but the problem is that I don't know what the index is now. int[] arr = new int[15]; arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = 4; arr[4] = 5; That code works because I know what index I am assigning to, but what if I don't know the index... In PHP, I can just do arr[]=22;, which ...
There is no way to do what you say in C++ with plain arrays. The C++ solution for that is by using the STL library that gives you the std::vector. You can use a vector in this way: #include <vector> std::vector< int > arr; arr.push_back(1); arr.push_back(2); arr.push_back(3);
756,109
756,188
How does delete deal with pointer constness?
I was reading this question Deleting a const pointer and wanted to know more about delete behavior. Now, as per my understanding: delete expression works in two steps: invoke destructor then releases the memory (often with a call to free()) by calling operator delete. operator delete accepts a void*. As part of a tes...
const_cast doesn't really do anything – it's a way to suppress compiler moaning about const-ness of the object. delete keyword is a compiler construct, the compiler knows what to do in this case and doesn't care about const-ness of the pointer.
756,439
756,487
What are the drawbacks to compiling C++ projects with /clr:safe to enable unit testing?
I would like to introduce unit testing to our C++ product and wanted to investigate the pros and cons of trying to use the CLR-based unit tests. I've read that if you compile with the /clr:safe option, you can call your existing C++ code. I'm strictly a .NET developer, so I'm at a loss for how this would affect our co...
It's not going to work, at all. The C++ code will not compile under /clr:safe; pretty much every line will give an error. /clr:safe gets you a language that basically shares no datatypes with C++.
756,549
756,553
Checking real variable type in polymorphism (C++)
Suppose we have a class A and class B and C inherit from it. Then we create an array of references to A's, and fill it with B's and C's. Now we decided that we want to eliminate all the C's. Is there a way to check what type each field of the array really holds without doing something redundant like a returnType() fu...
You can't create an array of As and fill it with Bs and Cs - they will be sliced down to As. You can create a n array of pointers to A , wich you can populate with pointers to B and pointers to C. To check the type of something in this situation - use dynamic cast: // create B or C randomly A * a = rand() % 2...
756,611
760,535
midl error 2025 when compiling idl file on win32 (midl doesn't like string<40>)
The idl files I have compile fine with linux tools, but when I try to compile using midl I get an error error MIDL2025 : syntax error : expecting a declarator or * near "<" the line is: typedef string<40> somestring; Is this non-standard idl, or am I missing something? Is there a switch for midl to allow this?...
My mistake. It is ACE/TAO specific. there is a tao_idl.exe idl compiler/processor. I will tag this question with ACE TAO
756,848
756,866
Do templated classes inherit the members of the classes passed to them? (Specificly std::vector)
I have a question regarding vectors: If I have a std::vector<MyClass> will this vector "inherit" the MyClass member functions or not? If not, then would be the best way to handle individually the MyClass members inside a loop? Would I have to create a new class object on each iteration and assign the current vector ite...
No, the instance std::vector doesn't inherit your member variables. However the objects in the vector do have those member which you can access via operator[]. for (size_t i = 0; i < vector.size(); i++) { cout << "Vector #" << i << endl; cout << "mystring is: " << vector[i].printString() << endl; cout << "...
756,906
756,912
Can you resize a C++ array after initialization?
I'm learning to program, and C++ is my first language. Don't bother using pointers to show me - I don't understand them yet, and won't bother until I have more free time to dedicate to this. int mergeSort() { const int n = 9; int originalarray[n] = {1, 3, 5, 7, 9, 2, 4, 6, 8}; const int halfelements =...
C++ arrays are fixed in size. If you need a "resizable array", you'll want to use std::vector instead of an array.
756,984
757,046
What can be done in VC++ (native) that can't be done with VC#?
What can be done in VC++ (native) that can't be done with VC#? From what I can tell the only thing worth using VC++ native for is when you need to manage memory yourself instead of the CLR garbage collector, which I haven't seen a purpose in doing either (but thats for another question to be asked later).
I'm not sure if you're talking about language features or applications. My answer though is for applications / components. Really there are only 2 things you cannot do in C# that you can do in C++. You cannot use C#, or any other .Net language, to write a component for a system that only accepts native components ...
757,059
757,266
Position of least significant bit that is set
I am looking for an efficient way to determine the position of the least significant bit that is set in an integer, e.g. for 0x0FF0 it would be 4. A trivial implementation is this: unsigned GetLowestBitPos(unsigned value) { assert(value != 0); // handled separately unsigned pos = 0; while (!(value & 1)) {...
Bit Twiddling Hacks offers an excellent collection of, er, bit twiddling hacks, with performance/optimisation discussion attached. My favourite solution for your problem (from that site) is «multiply and lookup»: unsigned int v; // find the number of trailing zeros in 32-bit v int r; // result goes here sta...
757,153
757,328
Concatenating C++ iterator ranges into a const vector member variable at construction time
I have a class X, which I provide a snippet of here: class X { public: template <typename Iter> X(Iter begin, Iter end) : mVec(begin, end) {} private: vector<Y> const mVec; }; I now want to add a new concatenating constructor to this class, something like: template <typename Iter1, typename Iter2> X(I...
Nice problem. I would try to implement a particular iterator wrapper type that turns the two ranges into a single range. Something in the lines of: // compacted syntax for brevity... template <typename T1, typename T2> struct concat_iterator { public: typedef std::forward_iterator_tag iterator_category; typedef t...
757,234
757,290
I'm concerned this code isn't doing what I want it to because of the way objects are used
I have the following code and I was wondering if someone could look at it for me. I have a multi-threaded application that all share an object and operate on it. I've created a pointer to a certain element of it, just so I don't have to type in the long path every time, but I'm concerned it might simply be modifying a...
Depends on the type of member _rpcThread. If it's simply RPCThread[] or *RPCThread then I don't think you have a problem. If it's a class type then you need to know the return type of its operator[]. If the relevant definition is returning a value rather than a reference, you probably have a copy. Unless, of course,...
757,241
757,254
In which order should classes be declared in C++?
Say I got this C++ code: class class1{ class2 *x; } class class2{ class1 *x; } The compiler would give an error in line 2 because it couldn't find class2, and the same if i switched the order of the classes. How do I solve this?
Two things - one, you need semicolons after class declarations: class class1{ class2 *x; }; class class2{ class1 *x; }; Two, you can create a declaration in front of the definitions of the classes. That tells the compiler that this class exists, and you have yet to define it. In this case, put a class2 declar...
757,270
757,385
Is making a function template specialization virtual legal?
In C++, a function template specialization is supposed to act exactly like a normal function. Does that mean that I can make one virtual? For example: struct A { template <class T> void f(); template <> virtual void f<int>() {} }; struct B : A { template <class T> void f(); template <> virtual void f<i...
Nice compiler error. For this type of checks I always fallback to the Comeau compiler before going back to the standard and checking. Comeau C/C++ 4.3.10.1 (Oct 6 2008 11:28:09) for ONLINE_EVALUATION_BETA2 Copyright 1988-2008 Comeau Computing. All rights reserved. MODE:strict errors C++ C++0x_extensions "Come...
757,298
757,431
Loading Managed C++ DLL from plain C++ Program via LoadLibrary
I'm trying to get a simple mixture between Managed C++ and plain C++ working. I'm using Visual Studio 2005 but keep hitting a problem. Here's my setup. First, I have a simple DLL built from the code #using "mscorlib.dll" #include "windows.h" __declspec(dllexport) void sayHello() { OutputDebugStringA( "Hello from ...
I just found out why loading the Managed C++ DLL from my vanilla C++ program didn't work. Thanks once again to jdigital for pointing me to a useful tool: The source of the error was that the MSVC8 runtime library was not found. I thought that the manifest which is generated when building via cl /CLR /LD dllcode.cpp is...
757,418
757,537
Should I compile with /MD or /MT?
In Visual Studio, there's the compile flags /MD and /MT which let you choose which kind of C runtime library you want. I understand the difference in implementation, but I'm still not sure which one to use. What are the pros/cons? One advantage to /MD that I've heard, is that this allows someone to update the runtime, ...
By dynamically linking with /MD, you are exposed to system updates (for good or ill), your executable can be smaller (since it doesn't have the library embedded in it), and I believe that at very least the code segment of a DLL is shared amongst all processes that are actively using it (reducing the total amount of...
757,465
757,490
Why doesn't auto_ptr construction work using = syntax
I ran into a compiler error that didn't make much sense to me: #include <memory> using namespace std; auto_ptr<Table> table = db->query("select * from t"); error: conversion from 'Table*' to non-scalar type 'std::auto_ptr< Table>' requested However, the following line does work: auto_ptr<Table> table(db->query("selec...
It's the "explicit" keyword. template <typename T> struct foo { explicit foo(T const *) { } }; template <typename T> struct bar { bar(T const *) { } }; int main(int argc, char **argv) { int a; foo<int> f = &a; // doesn't work bar<int> b = &a; // works } The "explicit" keyword prevents the constru...
757,556
758,215
Determine if device is connected/disconnected to RS232 port without opening the port
I"m working on a C++ Win32 application for which I'm trying to essentially "auto detect" if a device has been plugged into one of the RS232 ports and then if it has been disconnected. The checking for a connected device is easy enough because my use case allows me to assume that this particular thread will be the first...
It depends on the connected hardware whether there will be a change in the modem state registers when you disconnect the hardware, but if there is then you could check the state of for example the CTS or DSR line using the GetCommModemStatus() function. There is however the problem that you need a file handle to the CO...
757,698
757,715
Increment/decrement versus assignment?
I'm recording some statistics in my application. One of the statistics is the size of BigDataStructure. I have two options: Create a counter and increment / decrement the counter each time there is an add/remove from the BigDataStructure. Each time there is an add/remove from the BigDataStructure, set the counter to...
.size() would probably be the less error prone of the 2 options because it is idempotent. If you want to get into threading/synchronization issues, .size() is safer here. Also, today you have only 1 place that adds entries, and 1 place that removes entries. But maybe in the future that won't be the case.
757,913
758,003
Black and White graphics context
I'm working in Quartz/Core-graphics. I'm trying to create a black and white, 1b per pixel graphics context. I currently have a CGImageRef with a grayscale image (which is really black and white). I want to draw it into a black and white BitmapContext so I can get the bitmap out and compress it with CCITT-group 4. (For...
Even if 1-bit bitmaps were supported, if pixelsWide is not a multiple of 8, then the number of bytes per row is not an integer: for example, if your image is 12 pixels wide, then the number of bytes per row is one and a half. Your division expression will truncate this to one byte per row, which is wrong. But that's if...
757,933
757,978
How do you change the filename extension stored in a string in C++?
Alright here's the deal, I'm taking an intro to C++ class at my university and am having trouble figuring out how to change the extension of a file. First, what we are suppose to do is read in a .txt file and count words, sentences, vowels etc. Well I got this but the next step is what's troubling me. We are then suppo...
There are several approaches to this. You can take the super lazy approach, and have them enter in just the file name, and not the .txt extension. In which case you can append .txt to it to open the input file. infile.open(filename + ".txt"); Then you just call outfile.open(filename + ".code"); The next approach woul...
758,014
758,053
Value of a variable using WinDbg
Question: How to display the value of a C++ iterator using WinDbg, illustrated below: for (vector<string>::iterator i = args.begin(); i != args.end(); i++) //omitted //for instance: } else if (*i == "-i") {//attempting to display the value of *i ++i; if (!::PathFileExistsA(i->c_str())) { Note: ...
Try: dt -r i Which will recursively dump the iterator. One of the members should be the info you seek. Verbose, but effective.
758,017
758,113
VC++ compiler and type conversion?
When I moved a program from a Mac to this Windows PC, the VC++ 2008 compiler is giving me errors for passing unsigned ints to the cmath pow() function. As I understand, this function is not overloaded to accept anything but floating-point numbers. Is there some compiler flag/setting that will ignore these errors? Also ...
Regarding other answers here, it is not a good idea to tell the question author to turn off this warning. His code is broken - he's passing an unsigned int instead of a float. You should be telling him to fix his code! This isn't a warning, it's an error. However, for me it's not an issue since my program is only d...
758,023
758,448
What is the preferred method for creating a wxWidget application: using a GUI tool or procedurally in code?
I use wxWidgets to create test tools at work. I have always created the GUI by creating the widgets in code. I haven't tried any of the tools available that help to do this. How do other users of wxWidgets typically create their interface? If you use a tool, which tool do you use? If you use a tool, what advantage...
I've used wxFormBuilder for two reasons: It's cross-platform and I needed something that would work on Linux. I'm new to wxWidgets and I didn't want to spend lots of time futzing about with building the GUI. I think it works quite well, and being familiar with similar GUI building tools (Borland C++ Builder, Jigloo f...
758,041
758,072
How can I recursively search a list of lists for an item, getting the "closest" match
I have a class "Class" which has a member std::list, I want to search that list/tree for an item, specifically an item with a specific name. A basic representation of my class is as follows: #include <list> #include <string> class Class { std::string _name; std::list<Class*> _members; public: Class(const st...
Use a breadth-first search. As you access a node that isn't equal to the query value, you push that node onto the back of the queue. Process nodes from the front of the queue first. The first match you find will be the one closest to the root. Class* Class::findItem(const std::string& n) const { std::list<Class>::c...
758,045
758,143
How to be able to extract comments from inside a function in doxygen?
I'm interested to know if it is possible to have some comments in a function (c, c++, java) in a way that doxygen could put them in the generated html file. for example: function(...) { do_1(); /** * Call do_2 function for doing specific stuff. */ do_2(); }
No, doxygen does not support comments blocks inside function bodies. From the manual: Doxygen allows you to put your documentation blocks practically anywhere (the exception is inside the body of a function or inside a normal C style comment block). Section: Doxygen documenting the code
758,118
758,125
C++ vector literals, or something like them
I'm writing some code against a C++ API that takes vectors of vectors of vectors, and it's getting tedious to write code like the following all over the place: vector<string> vs1; vs1.push_back("x"); vs1.push_back("y"); ... vector<string> vs2; ... vector<vector<string> > vvs1; vvs1.push_back(vs1); vvs1.push_back(vs2); ...
In C++0x you will be able to use your desired syntax: vector<vector<vector<string> > > vvvs = { { {"x","y", ... }, ... }, ... }; But in today's C++ you are limited to using boost.assign which lets you do: vector<string> vs1; vs1 += "x", "y", ...; vector<string> vs2; ... vector<vector<string> > vvs1; vvs1 += vs1, ...
758,151
758,848
Equivalent of OnFinalMessage for MFC windows?
ATL CWindow class has a useful virtual method OnFinalMessage which is called after the last window message for the window is processed - at this point it is safe to destroy or deleted any objects associated with the window. Is there any equivalent for windows derived from the MFC CWnd class?
This answer describes how I eventually solved my problem. I'll note that while the answer by John Dibling was helpful, this was not the final solution to my problem. This is because the WM_NC_DESTROY message is sent as the final message to the window, but this can be handled before the last message to the window has fi...
758,182
758,196
How to check if a NULL character is in a string when debugging with WinDbg
For instance: 0:000> ?? testFile //check this variable char * 0x009c6758 "e:\TEST\example.FOO" Question: How can I check for a NULL-terminated character in above?
It's clearly there since you are seeing a valid string and not several junk characters afterwards. db poi(testFile) Will dump the raw bytes in the string to the console and you'll be able to see a 0 byte at the end. You can also use the memory window to see the zero byte at the end of the string as well.
758,673
758,722
Uses for multiple levels of pointer dereferences?
When does using pointers in any language require someone to use more than one, let's say a triple pointer. When does it make sense to use a triple pointer instead of just using a regular pointer? For example: char * * *ptr; instead of char *ptr;
each star should be read as "which pointed to by a pointer" so char *foo; is "char which pointed to by a pointer foo". However char *** foo; is "char which pointed to by a pointer which is pointed to a pointer which is pointed to a pointer foo". Thus foo is a pointer. At that address is a second pointer. At the ...
759,274
759,294
What is the lifetime and validity of C++ iterators?
I'm planning to implement a list of Things in C++ where elements might be removed out of order. I don't expect that i'll need any kind of random access (i just need to sweep the list periodically), and the order of items isn't important either. So I thought of std::list<Thing*> with this->position = insert(lst.end(), t...
In list all iterators remain valid during inserting and only iterators to erased elements get invalid during erasing. In your case keeping iterator should be fine even when other elements deleted ahead and after the inserted Thing*. EDIT: Additional details for vector and deque: Vector: inserting --- All iterators ...
759,315
759,359
Does const_cast ever cause actual code emission?
Is it true that const_cast is just a way to tell the compiler "stop moaning, treat this as a non-const pointer"? Are there any cases when const_cast itself is translated into actual machine code?
Conceivably,there could be architectures where a const pointer had a different representation to a non-const one, in which case the compiler would have to emit some code. I'm not aware of any such architectures, however.
759,341
759,349
Programatically opening and closing a console
I'm writing a windowed program in C++, but I would like to have the option to pop up a console to output to from inside the program (such as various things that go on behind the scenes of my program, to see that everything is acting correctly). Is there an easy way to do this? EDIT: In this particular case I'm using sf...
If you are talking about MS Windows, which your question does not make clear, you can use the AllocConsole API to create a console. for your app. Edit: You say that it could be any platform, but this is not so as many platforms have no concept of a console. For this reason, a cross-platform solution is not possible.
759,366
760,216
Spawned child exits with state = 127
I use posix_spawnp to execute different processes and I check the status (with waitpid) to make sure the child was created properly int iRet = posix_spawnp(&iPID, zPath, NULL, NULL, argv, environ); if (iRet != 0) { return false; } int iState; waitpid(static_cast<pid_t>(iPID), &i...
Check this link. For example: EINVAL The value specified by file_actions or attrp is invalid. The error codes for the posix_spawn and posix_spawnp subroutines are affected by the following conditions: If this error occurs after the calling process successfully returns from the posix_spawn or posix_spawnp function...
759,512
759,536
Internal typedefs in C++ - good style or bad style?
Something I have found myself doing often lately is declaring typedefs relevant to a particular class inside that class, i.e. class Lorem { typedef boost::shared_ptr<Lorem> ptr; typedef std::vector<Lorem::ptr> vector; // // ... // }; These types are then used elsewhere in the code: Lorem::vector lorems; Lore...
I think it is excellent style, and I use it myself. It is always best to limit the scope of names as much as possible, and use of classes is the best way to do this in C++. For example, the C++ Standard library makes heavy use of typedefs within classes.
759,584
759,609
c++ #define a macro with brackets?
Instead of doing the following everytime start(); // some code here stop(); I would like to define some sort of macro which makes it possible to write like: startstop() { //code here } Is it possible in C++?
You can do something very close using a small C++ helper class. class StartStopper { public: StartStopper() { start(); } ~StartStopper() { stop(); } }; Then in your code: { StartStopper ss; // code here } When execution enters the block and constructs the ss variable, the start() function will be call...
759,728
761,959
Problem nesting boost::lambda::bind-s
I have a generic function: void ImageAlbum::ExpressButtonPressed( boost::function< void ( thumb::PhotoPrintThumbnail*, thumb::PhotoPrintFormat, thumb::PhotoPrintQuantity ) > memberToCall ) { ... BOOST_FOREACH(thumb::PhotoPrintThumbnail *pThumbnail, m_...
Do you happen to #include boost/bind.hpp in your lambda-using code? This would cause unqualified use of the placeholders (_1, _2, etc) to resolve to those defined by Boost.Bind, and these don't mix well with Boost.Lambda. Rewriting your code to explicitly use boost::lambda::_[1,2,3] instead of the unqualified names com...
759,920
759,943
Need user to input string /check string length (C++)
I'll need to accept a string of 5 numbers from the user (only 5). Should I use istringstream for the same ? Can't I get away with something like this ? int main() { char *InputMain; InputMain=(char *)malloc(5+1); cout << "Enter the number : " <<endl; cin.getline ( InputMain, 5, '\n' ); /...
Unfortunately there is no portable way to restrict the number of characters input in C++. But whatever platform you are using will provide some mechanism: for example on Windows, look up Console functions. If you do go with plain old C++ iostreams input from cin, it's a good idea to read the initial text into a std::s...
760,030
760,037
What does the suffix #DEN mean on the value of a variable
When debugging in VS2005 I have a float in the Locals window whose values is: 1.744e-039#DEN What does the #DEN signify/stand for?
This is for "denormalized number".
760,114
760,631
What would you use to implement a fast and lightweight file server?
I need to have as part of a desktop application a file server which should respond as fast as possible to file transfer requests (from remote clients, usually located on the same LAN). There will be many file requests for small sized files. The server should be able to provide both upload and download services. I am no...
For frequent uploads of small files, the fastest way would be to implement your own proprietary protocol, but that would require a considerable amount of work - and also it would be non-standard, meaning future integration would be difficult unless you are able to implement your protocol in any client you'll support. I...
760,221
760,234
Breaking in std::for_each loop
While using std::for_each algorithm how do I break when a certain condition is satisfied?
You can use std::find_if algorithm, which will stop and return the iterator to the first element where the predicate condition applied to returns true. So your predicate should be changed to return a boolean as the continue/break condition. However, this is a hack, so you can use the algorithms. Another way is to use B...
760,301
760,350
Implementing a no-op std::ostream
I'm looking at making a logging class which has members like Info, Error etc that can configurably output to console, file, or to nowhere. For efficiency, I would like to avoid the overhead of formatting messages that are going to be thrown away (ie info messages when not running in a verbose mode). If I implement a c...
To prevent the operator<<() invocations from doing formatting, you should know the streamtype at compile-time. This can be done either with macros or with templates. My template solution follows. class NullStream { public: void setFile() { /* no-op */ } template<typename TPrintable> NullStream& operator<<(T...
760,522
761,143
ACE vs Boost vs Poco vs wxWidgets
I have a considerable amount of experience with ACE, Boost and wxWidgets. I have recently found the POCO libraries. Does anyone have any experience with them and how they compare to ACE, Boost and wxWidgets with regard to performance and reliability? I am particularly interested in replacing ACE with POCO. I have be...
I have used parts of POCO now and again and found it to be a very nice lib. I largely abandoned ACE a number of years ago but POCO contains some of the same patterns - Task, Reactor, etc. I have never had any problems with it so I have to assume it is stable. Some aspects that I like: it is a pretty well integrated ...
760,578
760,593
Const reference to temporary
After reading this article on Herb Sutter's blog, I experimented a bit and ran into something that puzzles me. I am using Visual C++ 2005, but I would be surprised if this was implementation dependent. Here is my code: #include <iostream> using namespace std; struct Base { //Base() {} ~Base() { cout << "~Base...
This IS implementation dependent. The standard allows a copy to occur when binding a temporary to a const reference. In your case, VC++ performs a copy only when the constructor is implicitly defined. This is unexpected, but permitted. C++1x will fix this.
760,777
760,801
C++ getters/setters coding style
I have been programming in C# for a while and now I want to brush up on my C++ skills. Having the class: class Foo { const std::string& name_; ... }; What would be the best approach (I only want to allow read access to the name_ field): use a getter method: inline const std::string& name() const { return nam...
It tends to be a bad idea to make non-const fields public because it then becomes hard to force error checking constraints and/or add side-effects to value changes in the future. In your case, you have a const field, so the above issues are not a problem. The main downside of making it a public field is that you're lo...
760,790
760,796
Is it legal to write to std::string?
In std::string there are only const members to fetch the data like c_str(). However I can get a reference to the first element of the string via operator[] and I can write to it. For example, if I have function: void toupper(char *first,char *last_plus_one); I can write directly to vector getting a pointer to the firs...
std::string will be required to have contiguous storage with the new c++0x standard. Currently that is undefined behavior.
761,256
761,289
How do you "refactor" ant build.xml files?
I'm working on a large C++ system built with ant+cpptasks. It works well enough, but the build.xml file is getting out of hand, due to standard operating procedure for adding a new library or executable target being to copy-and-paste another lib/exe's rules (which are already quite large). If this was "proper code", ...
you may be interested in: <import> <macrodef> <subant> Check also this article on "ant features for big projects".
761,616
761,642
XML Serialization of DOM Portions with Xerces C++
I've been struggling quite a bit with Xerces C++ and my unfamiliarity with all that is XML, but I need to use XML for a project I'm working on. My question is how do I serialize portions of a DOM tree that I have already parsed and created of out of a XML instance document (validated against a schema I wrote) so that I...
Does this article (Section: XML Schema validation using serialization of grammars to disk) help? We have successfully used the MemBufFormat described here.
761,655
761,694
What is the naming convention when typdef complex STL maps?
1) What is the convention used in practice when typedef'ing something like typedef std::map<SomeClass*, SomeOtherClass> [SomeStandardName>] typedef std::map<SomeClass*, std<SomeOtherClass> > <[SomeStandardName] 2) Where do you usually put typedef: header files globally, local to the class? 3) Do you typedef iterato...
I prefer the following convention: typedef std::map< Foo, Bar > FooToBarMap I purposely avoid typedef'ing the iterators, I prefer explicitly referring to them as: FooToBarMap::const_iterator Since the iterators are already a de facto standard typename. And FooToBarMapConstIter is actually less clear to read when ski...
761,791
761,811
Converting Between Local Times and GMT/UTC in C/C++
What's the best way to convert datetimes between local time and UTC in C/C++? By "datetime", I mean some time representation that contains date and time-of-day. I'll be happy with time_t, struct tm, or any other representation that makes it possible. My platform is Linux. Here's the specific problem I'm trying to solv...
You're supposed to use combinations of gmtime/localtime and timegm/mktime. That should give you the orthogonal tools to do conversions between struct tm and time_t. For UTC/GMT: time_t t; struct tm tm; struct tm * tmp; ... t = timegm(&tm); ... tmp = gmtime(t); For localtime: t = mktime(&tm); ... tmp = localtime(t); ...
761,893
761,915
error: cast from 'const prog_uchar*' to 'byte' loses precision?
The error is at this line : dataArray[iLedMatrix][iRow] |= (byte)(bufferPattern[iRow]) & (1<<7); dataArray is : byte dataArray[NUMBER_LED_MATRIX][NUMBER_ROW_PER_MATRIX]; bufferPattern is : const patternp * bufferPattern; patternp is a typedef of the type : typedef prog_uchar patternp[NUM_ROWS]; I can see in the Refe...
The problem is in this sub expression (byte)(bufferPattern[iRow]) The variable bufferPattern is of type const patternp * so when the indexer is applied the result is patternp. The type "patternp" is typedef to prog_uchar[]. So in actuality this expression is saying Cast a prog_uchar* to a byte Byte is almost certa...
761,917
763,451
Handling a class with a long initialization list and multiple constructors?
I have a (for me) complex object with about 20 data member, many of which are pointer to other classes. So for the constructor, I have a big long, complex initialization list. The class also has a dozen different constructors, reflecting the various ways the class can be created. Most of these initialized items are unc...
How about refactor the common fields into a base class. The default constructor for the base class would handle initialization for the plethora of default fields. Would look something like this: class BaseClass { public: BaseClass(); }; class Object : public BaseClass { Object(); Object(const string &N...
761,930
762,012
Getting Object Functionality out of C++ code in C#
I have have a function in wrote in C++ that calls some functions in a old lib. This function creates some memory makes the calls and destroys the memory. To optimize this I would create an object that would keep the memory allocated until the object was destroyed. However I'm going to be calling this function from C# a...
I prefer to write a managed wrapper in C++/CLI (formerly Managed C++), as it makes it much easier to explicitly do what you want with managed/unmanaged interoperability on the C++ side, and your C# doesn't get polluted with P/Invoke style code. Edit Just noticed your comment "However I'm going to be calling this functi...
762,736
762,850
Server Design and Implementation
I've work in embedded systems and systems programming for hardware interfaces to date. For fun and personal knowledge, recently I've been trying to learn more about server programming after getting my hands wet with Erlang. I've been going back and thinking about servers from a C++/Java prospective, and now I wonder...
for C++ I've used boost::asio, it's very modern C++, and quite plesant to work with. Also the C++0x network libraries will be based on ASIO's implementation, so it's valuable knowledge. As for designs 1thread per client, doesn't work, as you've already learned. And for high performance multithreading the best number of...
762,852
762,942
C/C++ replacement/redefinition rules?
I am not particularly new to C/C++ but today I discovered some things that I didn't expect. This compiles in gcc: /* test.c */ #include <stddef.h> // ! typedef unsigned long int size_t; // NO ERROR typedef unsigned long int size_t; // NO ERROR int main(void) { typedef unsigned long int size_t; // NO ERROR return...
Using GCC 4.0.1 on MacOS X 10.4.11 (ancient - but so's the computer), the example with "test.h" works - or my adaptation of it does. It appears you can have as many (identical) global typedefs of 'size_t' as you like - I had 5 with the version in stddef.h. The first typedef inside main is 'obviously' legal; it is a ne...
763,213
763,218
What would this code do? (memory management)
char *p = new char[200]; char *p1 = p; char *p2 = &p[100]; delete [] p1; Btw this is not a test or anything i actually need to know this :)
// allocate memory for 200 chars // p points to the begining of that // block char *p = new char[200]; // we don't know if allocation succeeded or not // no null-check or exception handling // **Update:** Mark. Or you use std::no_throw or set_new_handler. // what happens next is not guranteed // p1 now poi...
763,429
763,798
For boost-asio network programming whats the best approach for processing the response?
Im new to network programming and in particular to async-processes. Start also new with the boost-lib Im implementing a class, to access an imap-server. I can send and receive the commands and the response, in general The response is queued in a dequeue inside the class. I put simple the response lines in the queue, fo...
Each time a new entries is pushed to the queue make some callback? How can I implement and integrate this callback? I assume you are working with single thread synchronous connection. Do something like that: class worker { deque<message> messages; bool is_writing_; push_message(message msg) { ...
763,520
763,523
Deleting a char array
This question is related to this one. Given this code: char *p = new char[200]; delete[] p; what would happen if you set p[100] = '\0' before deleting p? I had some code where I got a debug error when I tried to delete a not null-terminated char array, something about deleting heap memory that's not assigned. It seem...
The code: char *p = new char[200]; p[100] = '\0'; delete[] p; is perfectly valid C++. delete does not know or care about null-terminated strings, so your error must have had some other cause.
763,573
763,580
C++ / Eclipse undefined reference question
I'm having trouble with what is apparently a linker error ("undefined reference") in Eclipse / C++. All the classes shown below compile fine, except for one, PlayGame.cpp, which is giving the "undefined reference" error (also shown below). Below are the relevant classes and pieces of code. PlayerFactory.h PlayerFacto...
The default visibility for class declarations is private. So all the member functions of both Player and PlayerFactory classes are private -- not accessible by clients. You need to make them public. Player.h #ifndef PLAYER_H #define PLAYER_H class Player { public: virtual ~Player() { cout << "Player d...