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
2,824,442
2,824,490
Killing a thread while deleting an object
I have an application which does some socket communication with some hardwares. Assume for the particular hardware i have an object and this object initiates a thread which listens on a particular port number say 5001 infinitely until a connection is established. Now if i delete this obect is there anyway by which i ca...
In Windows you could use WaitForSingleObject function to check whether thread exited (you can pass thread's handle to is as an argument). And you probably want to create event which will initiate thread's exit.
2,824,451
2,824,467
Convert string to GUID with sscanf
I'm trying to convert a string to GUID with sscanf: GUID guid; sscanf( "11111111-2222-3333-4455-667788995511", "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", &guid.Data1, &guid.Data2, &guid.Data3, &guid.Data4[0], &guid.Data4[1], &guid.Data4[2], &guid.Data4[3], &guid.Data4[4], &guid.Data4[5]...
Where does "Error: Command failed" come from? It's not a standard error message... You can use the UuidFromString function to do it in native C++.
2,824,508
2,826,347
What is so great about STL?
I am a Java developer trying to learn C++. I have many times read on the internet (including Stack Overflow) that STL is the best collections library that you can get in any language. (Sorry, I do not have any citations for that) However after studying some STL, I am really failing to see what makes STL so special. Wou...
What is so great about the STL ? The STL is great in that it was conceived very early and yet succeeded in using C++ generic programming paradigm quite efficiently. It separated efficiently the data structures: vector, map, ... and the algorithms to operate on them copy, transform, ... taking advantage of templates to ...
2,824,510
2,824,535
C++ casted realloc causing memory leak
I'm using a function I found here to save a webpage to memory with cURL: struct WebpageData { char *pageData; size_t size; }; size_t storePage(void *input, size_t size, size_t nmemb, void *output) { size_t realsize = size * nmemb; struct WebpageData *page = (struct WebpageData *)output; page->pag...
The code you have posted (as far as I can tell) is correct. If it's leaking, I suspect that you are forgetting to free() the memory block at some point. realloc is allowed to create an entire new memory block if it can't simply expand the existing one, and this is of interest to you. It is also of course allowed to all...
2,824,579
2,824,654
what if i keep my class members are public?
In c++ instance variables are private by default,in Python variables are public by default i have two questions regarding the same:- 1: why Python have all the members are public by default? 2: People say you should your member data should be private what if i make my data to be public? what are the disadvantag...
You can use a leading underscore in the name to tell readers of the code that the name in question is an internal detail and they must not rely on it remaining in future versions. Such a convention is really all you need -- why weigh the language down with an enforcement mechanism? Data, just like methods, should be p...
2,824,952
2,832,498
Setting up separate ctags db's for C/C++ standard libs, boost, and third party libs
I want to set up separate ctags databases for various libraries in /usr/include/ for use with OmniCppComplete. The idea is to be able to pull in only the libraries needed for a particular project in the target language - C or C++. For example, I'd like to have one database for the standard C libraries, one for system...
apt-file is your friend on Ubuntu. The following command will give you a list of all include files for Boost: apt-file list -x "^libboost" | grep '/include/' | cut -f2 -d: I'll leave the rest as an exercise for the reader! Update: For completeness, call apt-file update if you have never used apt-file before.
2,824,973
2,825,704
Read/Write file metadata using C/C++
Searched through net, could't find a way to read/write file metadata using C or C++, however, there are tools available for this, and also there are API's in C# and Java to do this. But I want to do it from scratch in C or C++. For example, read/write image metadata. Have found out that there are three formats in which...
Why would you want to do it from scratch? Anyway, you need documentation and you may also want to look at an existing library for helps, expecially if you have no experience in the field. Have you tried Exiv ? Exiv2 is a C++ library and a command line utility to manage image metadata. It provides fast and easy rea...
2,825,165
2,825,208
how to use replace_regex_copy() from boost::algorithm library?
This is my code: #include <string> #include <boost/algorithm/string/regex.hpp> string f(const string& s) { using namespace boost::algorithm; return replace_regex_copy(s, "\\w", "?"); } This is what compiler says: no matching function for call to ‘replace_regex_copy(const std::basic_string<char, std::char_t...
replace_regex_copy takes a boost::regex as its second argument, not a std::string. There is an explicit conversion from std::string to boost::regex, but no implicit conversion exists, so you can fix your code by changing it to... string f(const string& s) { using namespace boost::algorithm; return replace_r...
2,825,424
2,825,479
Comparing objects and inheritance
In my program I have the following class hierarchy: class Base // Base is an abstract class { }; class A : public Base { }; class B : public Base { }; I would like to do the following: foo(const Base& one, const Base& two) { if (one == two) { // Do something } else { // Do something else } } I hav...
class Base // Base is an abstract class { virtual bool equals(const Base& b) = 0; }; class A : public Base { virtual bool equals(const Base& base) { if (const A* a = dynamic_cast<const A*>(&base)) { // Return true iff this and a are equal. } return false; } }...
2,825,464
3,883,032
Generating a reasonable ctags database for Boost
I'm running Ubuntu 8.04 and I ran the command: $ ctags -R --c++-kinds=+p --fields=+iaS --extra=+q -f ~/.vim/tags/stdlibcpp /usr/include/c++/4.2.4/ to generate a ctags database for the standard C++ library and STL ( libstdc++ ) on my system for use with the OmniCppComplete vim script. This gave me a very reasonable 4M...
I know this post is a little old, but I just ran into the same problem. I looked into it a little further and it seems it is one folder in boost that is causing the problem: typeof. I am using boost 1.37 and my tags file was 1.5G, typeof was 1.4G of that. So I just created a tags file without that directory included...
2,825,824
2,826,401
What's the best replacement for timeGetTime to avoid wrap-around?
timeGetTime seems to be quite good to query for system time. However, its return value is 32-bit only, so it wraps around every 49 days approx. It's not too hard to detect the rollover in calling code, but it adds some complexity, and (worse) requires keeping a state. Is there some replacement for timeGetTime that woul...
Nope, tracking roll-over requires state. It can be as simple as just incrementing your own 64-bit counter on each callback. It is pretty unusual to want to track time periods to a resolution as low as 1 millisecond for up to 49 days. You'd have to worry that the accuracy is still there after such a long period. The ...
2,825,847
2,825,889
Fast dot product for a very special case
Given a vector X of size L, where every scalar element of X is from a binary set {0,1}, it is to find a dot product z=dot(X,Y) if vector Y of size L consists of the integer-valued elements. I suggest, there must exist a very fast way to do it. Let's say we have L=4; X[L]={1, 0, 0, 1}; Y[L]={-4, 2, 1, 0} and we have to ...
This really would require profiling but an alternative you might want to consider: int result=0; int mask=1; for ( int i = 0; i < L; i++ ){ if ( X & mask ){ result+=Y[i]; } mask <<= 1; } Typically bit shifting and bitwise operations are faster than multiplication, however, the if statement might be...
2,826,128
2,828,263
Variadic functions and arguments assignment in C/C++
I was wondering if in C/C++ language it is possible to pass arguments to function in key-value form. For example in python you can do: def some_function(arg0 = "default_value", arg1): # (...) value1 = "passed_value" some_function(arg1 = value1) So the alternative code in C could look like this: void some_function...
Here's a C99 solution using compound literals and variadic macros: #include <stdio.h> #define some_func(...) some_func_((struct some_func_args_){ __VA_ARGS__ }) struct some_func_args_ { const char *arg1; const char *arg2; }; static void some_func_(struct some_func_args_ args) { if(!args.arg1) args.arg1 =...
2,826,308
2,827,092
How to align C++ class member names in one column in emacs?
I would like to align all C++ class member names ( do not confuse with member types ) in one column. Lets look at the example of what we have at entrance: class Foo { public: void method1( ); int method2( ); const Bar * method3( ) const; protected: float m_member; }; and...
Select the region with the method declarations M-x align-regexp Enter the string [^ ]+\((\|;\) and press Enter Edited to add the ; in the matching, which aligns the member variable as well.
2,826,431
2,826,448
STL Rope - when and where to use
I was wondering under what circumstances you would use a rope over another STL container?
Ropes are a scalable string implementation: they are designed for efficient operation that involve the string as a whole. Operations such as assignment, concatenation, and substring take time that is nearly independent of the length of the string. Unlike C strings, ropes are a reasonable representation...
2,826,469
2,826,588
Correct use of boost lambda
Consider the following piece of C++0x code: a_signal.connect([](int i) { if(boost::any_cast<std::string>(_buffer[i]) == "foo") { base_class<>* an_object = new derived_class(); an_object->a_method(_buffer[i]); }}); How would it correctly look in Boost Lambda (since this C++0x feature can't be used in GCC ...
I think this should work: a_signal.connect(if_then( bind((std::string(*)(any&))&any_cast, var(_buffer)[_1]) == "foo", bind(&base_class<>::a_method, ll_static_cast< base_class<>* >( new_ptr<derived_class>() ), ...
2,826,589
2,826,757
empty base class optimization
Two quotes from the C++ standard, §1.8: An object is a region of storage. Base class subobjects may have zero size. I don't think a region of storage can be of size zero. That would mean that some base class subobjects aren't actually objects. How do these statements co-exist?
A philosophical argument over the definition of "region" is unnecessary. 1.8/5 says, "Unless it is a bit-field, a most derived object shall have a non-zero size ... Base class sub-objects may have zero size". So the standard is quite clear what objects (and hence what "regions of storage") can have zero size. If you di...
2,827,299
2,827,353
C code compiled with C++: undefined reference
I have a small program that I can compile with GCC and ICC without any difficulties, but I would also like the code to work with G++ and ICPC. I tried to add this: #ifdef __cplusplus extern "C" { #endif at the beginning and this: #ifdef __cplusplus } #endif at the end of all the header files, but I still get seve...
I think you're getting it wrong... The extern C is for disabling the function mangling; so if you do it just for the header files, when you try to link your mangled object code, the declared function names won't match with the function names in the object file. Anyway, the extern C won't add any portability if the whol...
2,827,422
2,827,761
How to reduce compile time with C++ templates
I'm in the process of changing part of my C++ app from using an older C type array to a templated C++ container class. See this question for details. While the solution is working very well, each minor change I make to the templated code causes a very large amount of recompilation to take place, and hence drastically...
I think the general rules apply. Try to reduce coupling between parts of the code. Break up too large template headers into smaller groups of functions used together, so the whole thing won't have to be included in each and every source file. Also, try to get the headers into a stable state fast, perhaps testing them o...
2,827,426
2,827,613
How to implement tail calls in a custom VM
How can I implement tail calls in a custom virtual machine? I know that I need to pop off the original function's local stack, then it's arguments, then push on the new arguments. But, if I pop off the function's local stack, how am I supposed to push on the new arguments? They've just been popped off the stack.
I take it for granted that we're discussing a traditional "stack-based" virtual machine here. You pop off the current function's local stack preserving the still-relevant parts in non-stack "registers" (where the "relevant parts" are, clearly, the argument for the forthcoming recursive tail call), then (once all of the...
2,827,511
2,827,854
Is there an equivalent of Mac OS X "open" command that can be called from C++/Objective-C code?
On Mac OS X there is a very useful "open" command which launches an application suitable for opened file type. Is there some C++/Objective-C function on Mac which does the same? Note: I know I could launch an "open" process. I'm just not sure if it's the best option.
That is done by NSWorkspace. See -[NSWorkspace openFile:]. All you have to do is [[NSWorkspace sharedWorkspace] openFile:@"file.txt"] If you want more fine-grained control (e.g. getting all applications which can open a given file,) you use Launch Services. See the document and the reference.
2,827,553
2,828,794
Creating a new window that stays on top even when in full screen mode (Qt on Linux)
I'm using Qt 4.6.3, and ubuntu linux on an embedded target. I call dlg->setWindowState(Qt::WindowFullScreen); on my windows in my application (so I don't loose any real-estate on the touch screen to task bar and status panel on the top and bottom of the screen. This all works fine and as expected. The issue comes in w...
Qt doesn't seem to have a way to bring other, non-Qt process in front. You may need to get the native, platform process ID from QProcess by calling QProcess::pid() and call the underlying OS API to do it.
2,827,688
2,827,703
error C2440: '=' : cannot convert from 'const char [2]' to 'char'
I am learning c++, and I am having issues doing some newbie things. I am trying to create a very small application that takes the users input and stores it into a char array. I then parse through that array and remove all parenthesis and dases and display it. like the following (325)858-7455 to 3258587455 But I am get...
The problem is here, I believe: phoneNum[i] = "i"; You want to assign a single character, so you need to use single quotes for your literal: phoneNum[i] = 'i'; There may well be other problems - I've only tried to fix the one mentioned in the title :)
2,827,964
2,828,021
Dizzy-like game level representation (format)
How would you store game level for a Dizzy-like adventure game? How would you specify walkable areas and graphics? Is it tile-based, pixel-based or walkable surfaces can be described by vectors?
Very old adventure games (like Sierra's quests from the 80s) used to actually maintain a separate bitmap of the entire screen that represented z-depth and materials to determine where your character could go and where it would be hidden. They would use pixel sampling to check where their small sprites would go. Though ...
2,828,280
2,828,320
'friend' functions and << operator overloading: What is the proper way to overload an operator for a class?
In a project I'm working on, I have a Score class, defined below in score.h. I am trying to overload it so, when a << operation is performed on it, _points + " " + _name is printed. Here's what I tried to do: ostream & Score::operator<< (ostream & os, Score right) { os << right.getPoints() << " " << right.scoreGet...
Note: You might want to look at the operator overloading FAQ. Binary operators can either be members of their left-hand argument's class or free functions. (Some operators, like assignment, must be members.) Since the stream operators' left-hand argument is a stream, stream operators either have to be members of the ...
2,828,637
2,828,673
C++: How do I correctly register and unregister file type associations for our application (programatically)
Time was when you set file associations in: HEY_CLASSES_ROOT\<.ext> However, that seems to be possible, but an incomplete solution anymore. There are additional associations throughout the registry. For example: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Explorer\KindMap HKEY_LOCAL_MACHINE\Software\...
Alas, this documentation still seems current, and it's all about the registry: MSDN Maybe someone's created a nice wrapper for this? Time to hit Google...
2,828,765
2,828,790
Getting the compiler to perceive << as defined for a specific class
I edited a post of mine with this question, yet got no answers. I overloaded << for a class, Score (defined in score.h), in score.cpp. ostream& operator<< (ostream & os, const Score & right) { os << right.getPoints() << " " << right.scoreGetName(); return os; } (getPoints fetches an int attribute, getName a string o...
Perhaps you didn't declare your operator<< in score.h? It should normally contain something like: ostream& operator<< (ostream & os, const Score & right); Edit: More accurately, that should be: std::ostream &operator<<(std::ostream &os, const Score &right); You definitely should not have a using namespace std; in a h...
2,828,877
2,828,926
Boost Multithreading
Can anyone tell what's going on here? When I try debug the code and when the control is in thread() function at Line 15, it skips over the Line 16 move to Line 17 and goes back Line 16. Why wouldn't it move Line by Line? 1. #include <boost/thread.hpp> 2. #include <iostream> 3. 4. void wait(int seconds) 5. { 6. bo...
Possibly your debugger is actually stepping several threads in parallel which is why it appears to jump back and forth. Try printing the thread ID from your debugger and you'll probably see different numbers at each stop. Another reason for weird jumping in debug is if the code is optimized. If so, the source code ord...
2,828,992
2,829,118
Can anybody explain to the meaning of this expression?
void* GetData() { return reinterpret_cast<unsigned char*>(this); } Is there a case of automatic type coercion happening in this case ??? How could I convert the object of my class to an unsigned char* ??
I agree with the other posts: this is almost certainly not what you intend to do. However, IIRC, you are guaranteed by the C++ standard to be able to convert a pointer of any type (not including function or member pointers) to an unsigned char * or a void * and back without entering the realm of undefined behavior. Add...
2,829,123
2,829,182
Help with enum values in registry c++
DWORD type = REG_NONE; int i = 0; size = sizeof(ValueName); size2 = sizeof(ValueData); BOOL bContinue = TRUE; do { lRet = RegEnumValue(Hkey , i , ValueName , &size , 0 , &type , ValueData , &size2); switch(lRet) { case ERROR_SUCCESS: print_values(ValueName , type , ValueData , size2); i++; size...
I suspect it's related to this: size2 = sizeof(ValueData); Although I don't see a declaration for ValueData, it's apparent that it is a pointer, not an array. Therefore, sizeof will give you the size of a pointer rather than the size of the buffer it points to. You'll need to keep track of the size yourself. The sa...
2,829,157
2,829,257
Why only random-access-iterator implements operator+ in C++?
I'd like get far next value for STL list iterator but it doesn't implement operator+, vector has it though. Why and how can I get the value where I want? I think I can do that if I call operator++ several times, but isn't that a little bit dirty? What I want to do is the following: list<int> l; ...omitted... list<int>:...
You can also use std::next (and prev) or the equivalents provided by Boost if you don't have access to C++11. list<int>::iterator itr = std::next(l.begin(), 3); Rationale: std::advance is awkward to use (it works by side-effect, not by returning a copy).
2,829,523
2,829,629
upgrading boost version
I'm using RHEL 5.3, shipped with gcc 4.1.2 and boost 1.33. So, there's no boost::unorded_map, no make_shared() factory function to create boost::shared_ptr and other features available in newer releases of boost. Is there're a newer version of boost compatible with the version of gcc? If yes, how the upgrade is perform...
Download the latest version (1.43.0) of the Boost libraries from the Boost website and follow the steps in the getting started guide, which explains how to build Boost on a number of platforms, including Linux.
2,829,563
2,829,609
inheriting from a class declarations in c++
When you want to inherit from a class in C++, is it illegal to have std declared in the first line below? #ifndef HWEXCEPTION_H #define HWEXCEPTION_H #include <stdexcept> class HWException : public std::run_time_error { void testException(int num); }; #endif vs using std::run_time_error class MyClass : public ...
Both are legal. But assuming this is in a header file, you should not use the using directive version, as it places the name in the global namespace, which may cause problems for users of your header. Edit: Just noticed that you have the class name wrong: #include <stdexcept> class MyClass : public std::runtime_error {...
2,829,637
2,829,712
SOCKS in C/C++ or another language?
How do i add SOCKS support to my application? and where can i get the libs? any help appreciated thanks
You could try Boost.Asio library. It contains an example with SOCKS4 protocol implementation.
2,829,966
2,830,580
error C2109: subscript requires array or pointer type
I am trying to debug some homework but I am having trouble with these lines of code #include "stdafx.h" #include<conio.h> #include<iostream> #include<string> using namespace std; int main() { char word; cout << "Enter a word and I will tell you whether it is" << endl << "in the first or last half of the alphabe...
Another suggestion: declare output text as one entity, then block write. This may make your programs easier to debug, read and understand. int main(void) { static const char prompt[] = "Enter a word and I will tell you whether it is\n" "in the first or last half of the alphabet.\n" "Please begin the...
2,829,972
2,830,140
Help configuring the log4cplus configuration file (properties file)
I created a new Logger object like this: log4cplus::Logger m_WebAccessLogger; //a class member Then in the constructor initialization list I do: m_WebAccessLogger(log4cplus::Logger::getInstance("WebAccess") This works fine, it logs as expected. What I'm having trouble with is, I want to configure the log4cplus.prop...
I figured it out by guessing. log4cplus.rootLogger=DEBUG, ROLLING log4cplus.appender.STDOUT=log4cplus::ConsoleAppender log4cplus.appender.STDOUT.layout=log4cplus::PatternLayout log4cplus.appender.STDOUT.layout.ConversionPattern=%d{%m/%d/%y %H:%M:%S} [%t] %-5p %c{2} %%%x%% - %m [%l]%n log4cplus.appender.STDOUT.layout.Co...
2,830,015
2,830,075
not able to use g++ from Fedora
$ yum list | grep gcc arm-gp2x-linux-gcc.i686 4.1.2-11.fc12 @fedora arm-gp2x-linux-gcc-c++.i686 4.1.2-11.fc12 @fedora gcc.i686 4.4.3-4.fc12 @updates libgcc.i686 4.4.3-4.fc12 ...
gcc-c++ is not installed. The yum list command shows all packages, not just the installed packages. The packages that are installed are prefixed with an ampersand or "@" sign. The packages that are not installed (but are available to be installed) lack the ampersand. To see what is installed try the command rpm -qa. ...
2,830,149
2,830,360
How to track the memory usage in C++
I have a C++ program running under linux. Is it possible to track its memory usage from the code? I am allocating new objects and running out of memory, so I want to keep track of how quickly I am using memory. Thanks
Valgrinds module massif is exactly what you are looking for. http://valgrind.org/docs/manual/ms-manual.html
2,830,272
2,830,600
Critique my heap debugger
I wrote the following heap debugger in order to demonstrate memory leaks, double deletes and wrong forms of deletes (i.e. trying to delete an array with delete p instead of delete[] p) to beginning programmers. I would love to get some feedback on that from strong C++ programmers because I have never done this before a...
Instead of doing intrusive note-keeping you could keep a list of all allocations made. Then you can free the memory without destroying your own data, and keep track of how many times a particular address is "deleted", and also find places where the program tries to delete a non-matching address (i.e. not in the list).
2,830,468
2,830,508
Need help with map (c++, STL)
Actually I'm new to C++. I tried something out (actually the map container) but it doesn't work the way I assumed it will... Before posting my code, I will explain it shortly. I created 3 classes: ClassA ClassDerivedA ClassAnotherDerivedA The two last ones are derived from "ClassA". Further I created a map: map<s...
The problem is slicing. You are storing ClassA values in your map. When you store derived class instances into the map, the get sliced into ClassA objects. You'll need to store pointers in your map instead of values. See this for more info on slicing: What is object slicing?
2,830,587
2,830,606
Vector of pointers to base class, odd behaviour calling virtual functions
I have the following code #include <iostream> #include <vector> class Entity { public: virtual void func() = 0; }; class Monster : public Entity { public: void func(); }; void Monster::func() { std::cout << "I AM A MONSTER" << std::endl; } class Buddha : public Entity { public: void func(); }; void Bu...
You need to allocate the objects from the heap with 'new'. What's happening here is that you're creating temporary objects, taking the pointer to those objects, and then those objects are being destroyed. Yes, this is differerent from many other languages. :) Instead, try: int main() { const int num = 5; // How ...
2,830,622
2,836,732
How can I create a Base64-Encoded string from a GDI+ Image in C++?
I asked a question recently, How can I create an Image in GDI+ from a Base64-Encoded string in C++?, which got a response that led me to the answer. Now I need to do the opposite - I have an Image in GDI+ whose image data I need to turn into a Base64-Encoded string. Due to its nature, it's not straightforward. The crux...
Got it std::string RotateImage(const std::string &Base64EncodedImage) { // Initialize GDI+. GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); std::string decodedImage = base64_decode(Base64EncodedImage); DWORD imageSize ...
2,830,698
2,830,756
Will the template argument's destructor to a templated class be called on deletion?
If you have a templated base class as in the following example: class A{ public: A(); virtual ~A(); }; template <class T> class B : public T { public: B(); virtual ~B(); }; typedef B<A> C; class D : public C { public: D(); virtual ~D(); }; When you delete an instance of D, will the de...
When you delete an instance of D, will the destructor of A be called? Yes. Nothing special here (except you have private access on everything, which means it probably won't compile).
2,830,708
2,830,723
Java Equivalent of C++ .dll?
So, I've been programming for a while now, but since I haven't worked on many larger, modular projects, I haven't come across this issue before. I know what a .dll is in C++, and how they are used. But every time I've seen similar things in Java, they've always been packaged with source code. For instance, what would...
Java .jar library is the Java equivalent of .dll, and it also has "Jar hell", which is the Java version of "dll hell" http://en.wikipedia.org/wiki/JAR_(file_format)
2,830,941
2,830,992
Speed comparison - Template specialization vs. Virtual Function vs. If-Statement
Just to get it out of the way... Premature optimization is the root of all evil Make use of OOP etc. I understand. Just looking for some advice regarding the speed of certain operations that I can store in my grey matter for future reference. Say you have an Animation class. An animation can be looped (plays over and o...
(1) Not that the size of the generated assembly matters anymore these days, but this is what it generates (approximately, assuming MSVC on x86): mov eax, [ecx+12] ; 'this' pointer stored in ecx, eax is scratch cmp eax, 0 ; test for 0 jz .somewhereElse ; jump if the bool isn't set The optimizing compiler ...
2,830,954
2,831,047
Boost thread synchronization in release build
when I try to run the following code in debug and release mode in VS2005. Each time I see different output in console and It doesn't seem like the multithreading is achieved in release mode. 1. #include <boost/thread.hpp> 2. #include <iostream> 3. 4. void wait(int seconds) 5. { 6. boost::this_thread::sleep(boost:...
If you uncomment the call to wait(), it is evident that both threads are running at the same time. Likewise, if you increase the number of times the loop is run to 1,000, you can see the threads are interleaved (well, 1,000 on my computer; it might take more or less). Remember that a release build is optimized, so tas...
2,831,039
2,831,061
Visual Studio 2008 awful performance
I have ported a piece of C++ code, that works out of core, from Linux(Ubuntu) to Windows(Vista) and I realized that it works about 50times slower on VS2008! I removed all the out of core parts and now I just have a piece of code that has nothing to do with the hard disk. I set compiler parameters to O2 in Project Prope...
Do you use a lot of the standard C++ library? If so, you might want to turn off the "checked iterators" feature that is on by default in Visual C++ (even in Release mode). Put this before including any standard headers: #define _SECURE_SCL 0 More info here.
2,831,247
2,831,354
C++ using typedefs in non-inline functions
I have a class like this template< typename T > class vector { public: typedef T & reference; typedef T const & const_reference; typedef size_t size_type; const_reference at( size_t ) const; reference at( size_t ); and later in the same file template< typename T > typename vector<T>::co...
Yes, in out-of-class member function definition you have to use a fully-qualified name for the nested return type. This, BTW, has nothing to do with templates. It is that way with non-template classes as well. In your case it is a template class and, as a consequence of that, since you are using a qualified name to ref...
2,831,253
2,831,302
Using boost::asio::async_read with stdin?
short question: I have a realtime-simulation which is running as a backround process and is connected with pipes to the calling pogramm. I want to send commands to that process using stdin to get certain information from it via stdout. Now because it is a real-time process, it has to be a non blocking input. Is boost::...
Look at boost::asio::posix::stream_descriptor http://www.boost.org/doc/libs/release/doc/html/boost_asio/example/cpp03/chat/posix_chat_client.cpp
2,831,257
2,831,570
Why would the assignment operator ever do something different than its matching constructor?
I was reading some boost code, and came across this: inline sparse_vector &assign_temporary(sparse_vector &v) { swap(v); return *this; } template<class AE> inline sparse_vector &operator=(const sparse_vector<AE> &ae) { self_type temporary(ae); return assign_temporary(temporary); } It se...
why did C++ ever opt to make them do different things? Because assignment works on a fully constructed object. In resource managing classes, this means that every member pointer already points to a resource. Contrast this to a constructor, where the members don't have any meaning prior to executing it. By the way, in...
2,831,280
2,831,307
Only compiles as an array of pointers, not array of arrays
Suppose I define two arrays, each of which have 2 elements (for theoretical purposes): char const *arr1[] = { "i", "j" }; char const *arr2[] = { "m", "n" }; Is there a way to define a multidimensional array that contains these two arrays as elements? I was thinking of something like the following, but my compiler dis...
No. First, this char const *combine[][2] = { arr1, arr2 }; cannot work, because arr1 and arr2 cannot be used to initialize an array. But this: char const *arr1[] = { "i", "j" }; char const *arr2[] = { "m", "n" }; char const *(*combine[])[2] = { &arr1, &arr2 }; works as well as this char const *arr1[] = { "i", "j" };...
2,831,323
2,831,366
STL list - how to find a list element by its object fields
I have a list: list<Unit *> UnitCollection; containing Unit objects, which has an accessor like: bool Unit::isUnit(string uCode) { if(this->unitCode == uCode) return true; else return false; } How do I search my UnitCollection list by uCode and return the corresponding element (preferably and ...
You could have a look at find_if as jpalecek suggests, and then use distance to find the distance between the iterator returned from find_if and UnitCollection.begin(), and that distance should be the index of the element in the list. And as for the predicate, you could write a function object like this: struct predica...
2,831,438
2,831,452
Using mem_fun_ref with boost::shared_ptr
Following the advice of this page, I'm trying to get shared_ptr to call IUnknown::Release() instead of delete: IDirectDrawSurface* dds; ... //Allocate dds return shared_ptr<IDirectDrawSurface>(dds, mem_fun_ref(&IUnknown::Release)); error C2784: 'std::const_mem_fun1_ref_t<_Result,_Ty,_Arg> std::mem_fun_ref(_Result (__...
Isn't the calling convention specifier a problem? Would this be OK? void iUnk_delete(IUnknown* u) { u->Release(); } return shared_ptr<IDirectDrawSurface>(dds, iUnk_delete);
2,831,465
2,831,533
Can two separate pointers reference the same address? If so, can I change the value at that address with either pointer?
So, I have this code fragment: int * iPtr ; int * jPtr ; int i = 5, k = 7; iPtr = &i; jPtr = iPtr ; I have just started learning about pointers, and need to get some doubts cleared. is jPtr now essentially also pointing at i? I know I can change the value of i by using *iPtr, but how can I change the value of the obj...
1000 1001 1002 1004 --> address location ( note: just indicative) ---------------------------- | 5 | 7 | 1000 | 1000 | | i | j | iPtr | jPtr | ----------------------------- ^^ | | ||________| | |_________________| iPtr=&i; --> iPtr points to i ==> address of i is stored in iPtr ==> *iPt...
2,831,505
2,831,753
Swapping values using pointers
I have this code fragment int i = 5; int k = 7; int * iPtr; int * jPtr; int * kPtr; iPtr = &i; kPtr = &k; I am required to swap i and k using the pointers. This is how I'm doing it: *jPtr = *kPtr ; *kPtr = *iPtr ; *iPtr = *jPtr ; Is this the best way to do it, or is there a better way?
The best way to do that in C++, in my opinion, is with std::iter_swap(): #include<algorithm> // ... int *iPtr = &i, *kPtr = &k; std::iter_swap(iPtr, kPtr); You may think that's an overkill, but I'd disagree if you include <algorithm> anyway. Of course, in the case of a homework this answer only holds if the instructo...
2,831,841
2,831,868
How to get the time in milliseconds in C++
In Java you can do this: long now = (new Date()).getTime(); How can I do the same but in C++?
There is no such method in standard C++ (in standard C++, there is only second-accuracy, not millisecond). You can do it in non-portable ways, but since you didn't specify I will assume that you want a portable solution. Your best bet, I would say, is the boost function microsec_clock::local_time().
2,831,978
2,832,880
Performing full screen grab in windows
I am working on an idea that involves getting a full capture of the screen including windows and apps, analyzing it, and then drawing items back onto the screen, as an overlay. I want to learn image processing techniques and I could get lots of data to work with if I can directly access the Windows screen. I could use...
I solved my original question about the incredible speed up of switching to 16 bit color mode. Turns out it was causing the Aero theme to be disabled, which accounts for most of it. With Aero off in 32bit it is just about as fast. Link to other topic with a good answer.
2,832,018
2,832,025
Multiple inclusion of header file c++
I have a problem regarding multiple inclusion of header file in C++ code. Say for example, I have three classes X, Y, Z. X and Y are derived from base class Z. And I want to create an instance of X in Y. The code will go like this. class Z { …some code… }; class X: public Z { …some code… }; //here #include header of...
Using "include guards" (Wikipedia link) #ifndef MYHEADER_H #define MYHEADER_H // header file contents go here... #endif // MYHEADER_H This is idiomatic code, easily recognizable by any seasoned C and C++ programmer. Change MYHEADER_H to something specific to you, for example if the header defines a class named Custo...
2,832,023
2,832,511
C++ map performance - Linux (30 sec) vs Windows (30 mins) !
I need to process a list of files. The processing action should not be repeated for the same file. The code I am using for this is - using namespace std; vector<File*> gInputFileList; //Can contain duplicates, File has member sFilename map<string, File*> gProcessedFileList; //Using map to avoid linear search costs v...
In the Microsoft Visual Studio, there's a global lock when accessing the Standard C++ Library to protect from multi threading issue in Debug builds. This can cause big performance hits. For instance, our full test code runs on Linux/gcc in 50 minutes, whereas it needs 5 hours on Windows VC++2008. Note that this perform...
2,832,088
2,832,119
how to call operator () in c++
in c++ i have following code class Foobar{ public: Foobar * operator()(){ return new Foobar; }; My quesion is how to call the (); if i do Foobar foo() the constructor gets called i am confused about behaviour of () can some explain me
While GMan's answer is factually correct, you should never overload an operator to do something unexpected - this goes against all good-practice programming rules. When a user reads code he expects operators to behave in some way, and making them behave differently is good only for obfuscating coding competitions. The ...
2,832,263
2,832,282
In game programming are global variables bad?
I know my gut reaction to global variables is "badd!" but in the two game development courses I've taken at my college globals were used extensively, and now in the DirectX 9 game programming tutorial I am using (www.directxtutorial.com) I'm being told globals are okay in game programming ...? The site also recommends...
The trouble with games and globals is that games (nowadays) are threaded at engine level. Game developers using an engine use the engine's abstractions rather than directly programming concurrency (IIRC). In many of the highlevel languages such as C++, threads sharing state is complex. When many concurrent processes sh...
2,832,485
2,837,660
zlib gzgets extremely slow?
I'm doing stuff related to parsing huge globs of textfiles, and was testing what input method to use. There is not much of a difference using c++ std::ifstreams vs c FILE, According to the documentation of zlib, it supports uncompressed files, and will read the file without decompression. I'm seeing a difference from 1...
I guess you are using zlib-1.2.3. In this version, gzgets() is virtually calling gzread() for each byte. Calling gzread() in this way has a big overhead. You can compare the CPU time of calling gzread(gzfp, buffer, 4096) once and of calling gzread(gzfp, buffer, 1) for 4096 times. The result is the same, but the CPU tim...
2,832,714
2,832,754
Header files inclusion / Forward declaration
In my C++ project when do I have to use inclusion (#include "myclass.h") of header files? And when do I have to use forward declaration of the class (class CMyClass;)?
As a rule try the forward declaration first. This will reduce compile times etc. If that doesn't compile go for the #include. You have to go for the #include if you need to do any of the following: Access a member or function of the class. Use pointer arithmetic. Use sizeof. Any RTTI information. new/delete, copy etc....
2,832,818
2,833,651
Class destructor memory handling in C++
What potential memory leaks won't an implicit destructor handle? I know that if you have anything stored on the heap it won't handle it, and if you have a connection to a file or a database, that needs to be handled manually. Is there anything else? What about, say, non-base data types like vectors? Also, in an explici...
What potential memory leaks won't an implicit destructor handle? I know that if you have anything stored on the heap it won't handle it, and if you have a connection to a file or a database, that needs to be handled manually. Is there anything else? What about, say, non-base data types like vectors? To put it simply,...
2,832,932
2,834,122
how to rebuilt a specific dependent library with /MD mode in c++ VS2005?
One of my specific dependent library is built with /ML. How to rebuil it with /MD? Thanks in advance!
Rebuild it: You need the source code and Visual C++ projects/solution used to build the library, and change the setting in the project settings. If you don't have the VC++ projects, you can create them and configure them by hand. More work. The worst is the case when you don't have the source code of that library... t...
2,833,011
2,833,071
How to check number?
Could anyone please tell me how to check what number I've got from a * b? Which is I would like to know every part of this number so for example if the result from this expression would be 25 I would like to know that first digit is two and second digit is five.
perhaps a little overkill... but even works with doubles #include <sstream> #include <iostream> int main() { double a = 5.2; double b = 7; double z = a*b; std::stringstream s; s << z; for (int i = 0; i < s.str().length(); i++) std::cout << i << ": " << s.str()[i] << std::endl; re...
2,833,039
2,833,078
Can't Display Bitmap of Higher Resolution than CDC area
Hi there dear gurus and expert coders. i am not gonna start with im a newbie and don't know much about image programming but unfortunately those are the facts :( I am trying to display an image from a bitmap pointer *ImageData which is of resolution 1392x1032. I am trying to draw that at an area of resolution or size 6...
StretchBlt is your friend :) Edit: OK how do you get pDC? When is your function called? Form OnPaint or DrawItem? This is a StretchBlt I do from a DrawItem call in an overriden CStatic. HDC hBitmapDC = CreateCompatibleDC( pDrawItemStruct->hDC ); HBITMAP hBitmap = GetBitmap(); HGDIOBJ hOld = SelectObject( hBitma...
2,833,153
2,834,135
Floating point comparison in STL, BOOST
Is there in the STL or in Boost a set of generic simple comparison functions? The one I found are always requiring template parameters, and/or instantiation of a struct template. I'm looking for something with a syntax like : if ( is_equal(x,y) ) { ... } Which could be implemented as : template <typename T> bool i...
I don't know of any library that does it, perhaps because it is as simple as a one-liner or perhaps because it was forgotten... As generality goes though, are you sure you'd like to set up the epsilon for one given type at a given value... throughout the application ? Personally I'd like to customize it depending on th...
2,833,257
2,833,268
How to call a method via a vector?
How do I call a method of an object which is stored within a vector? The following code fails... ClassA* class_derived_a = new ClassDerivedA; ClassA* class_another_a = new ClassAnotherDerivedA; vector<ClassA*> test_vector; test_vector.push_back(class_derived_a); test_vector.push_back(class_another_a);...
The things in the vector are pointers. You need: (*it)->printOutput(); which dereferences the iterator to get the pointer from the vector, then uses -> on the pointer to call the function. The syntax you show in your question would work if the vector contained objects rather than pointers, in which case the iterator ...
2,833,682
2,833,747
Contents changed(cleared?) when access the pointer returned by std::string::c_str()
I have to maintain some legacy codes,parts of it look like the following: /* this class reads a ini file which looks like this: key = value */ class Config{ // .. public: string conf(const char* key) { vector<string> v; //.. v = func(); //this function returns a vector<string> ...
the string object will be alive as a auto var so the pointer should be valid till the end of this function,right? Wrong. The temporary returned by the conf() function call lives as long as the full expression it is part of, not for the length of the function containing the call.
2,833,730
2,833,761
Calling template function without <>; type inference
If I have a function template with typename T, where the compiler can set the type by itself, I do not have to write the type explicitly when I call the function like: template < typename T > T min( T v1, T v2 ) { return ( v1 < v2 ) ? v1: v2; } int i1 = 1, i2 = 2; int i3 = min( i1, i2 ); //no explicit <type> But ...
Overload resolution is done only based on function arguments; the return value is not used at all. If the return type cannot be determined based on the arguments, you will have to specify it explicitly. I would not go down the path of "returning" a value through a reference parameter; that makes the calling code unclea...
2,834,131
2,834,152
Automatic creation of method definitions from declarations
Is there a tool, macro or plugin that can generate a method or function body automatically from a declaration in a header file? I have tried Intellisense and Refactor! 3.0.5 which both only seem to work with C#.
You could use Visual Assist. But it is a commercial tool.
2,834,139
2,834,157
Declaring a data type dynamically in C++
I want to be able to do the following: I have an array of strings that contain data types: string DataTypeValues[20] = {"char", "unsigned char", "short", "int"}; Then later, I would like to create a variable of one of the data types at runtime. I won't know at compile time what the correct data type should be. So for...
The simple answer is that you can't - types need to be known at compile time in C++. You can do something like it using things like boost::any or unions, but it won't be pretty.
2,834,362
2,834,394
C++ STL map.find() not finding my stuff
I have constructed a map and loaded it with data. If I iterate over all the elements I see they are all valid. However, the find method doesn't find my item. I'm sure it's something stupid I am doing. Here is snippet: // definitions // I am inserting a person class and using the firstname as the key typedef std::map<c...
Since the key is char*, they will be compared by address, not by value, e.g. char* a = "123"; char* b = new char[4]; memcpy(b, a, 4); assert(a != b); You should use a std::string, which has an overloaded < for comparison by value. typedef std::map<std::string, Person*> mapType; ... (And probably you want to use a Per...
2,834,414
2,834,451
Is private member hacking defined behaviour?
I have the following class: class BritneySpears { public: int getValue() { return m_value; }; private: int m_value; }; Which is an external library (that I can't change). I obviously can't change the value of m_value, only read it. Even deriving from BritneySpears won't work. What if I define the follow...
This is undefined behaviour. The members within each access-qualifier section are guaranteed to be laid out in the order they appear, but there is no such guarantee between acccess qualifiers. For instance, if the compiler chooses to place all private members before all public members, the above two classes will have a...
2,834,491
2,834,532
destroying object in vector when new object added
When push_back method of vector is called the previous object in the vector is getting destroyed what might be the reason for this. template<typename type> void SomeList<type>::AddElement(type &inObject) { pList.push_back(inObject);// pList is member of my class Vector SomeList }
The vector doesn't destroy the object. It replaces it. For example: vector< A> myVector; // Do some initialization, etc. A myNewObject; myVector[0] = myNewObject; // Replace the object. That means the assignment operator (A& A::operator=( const A&)) will be called for myVector[0]. There is no destruction there. The de...
2,834,566
2,834,631
Beginner C++ - Opening a text file for reading if it exists, if it doesn't, create it empty
I am writing a high-score sub-routine for a text-based game. Here's what I have so far. void Game::loadHiScores(string filename) { fstream hiscores(filename.c_str()); // what flags are needed? int score; string name; Score temp; if (hiscores.is_open()) { for (size_t i = 0; i < TOTAL_HIS...
Wrong logic I would say. I think you want: Try to open an ifstream (not an fstream) containing scores if it opened read high scores into array close stream else set array to zero endif Play Game - adjust high scores in array, then on exit Try to open scores ofstream (not an fstream) for writing if it opened ...
2,834,737
2,834,927
Creating new folders if they don't exist for fopen
I have a C++ program that takes user input for fopen in order to initiate a file write. Could someone help me find a function which will return a FILE* and use the Windows specific version of mkdir in order to create the folder structure for fopen to never fail to open a new file in the specified location because one o...
there's a method MakeSureDirectoryPathExists in the windows API, declared in dbghelp.h. It recursively creates directories, so I guess that's what you are after. However, there is NO way of making sure this 'never fails' as you ask, as it also depends on privileges etc if you have write access to a certain directory. e...
2,834,922
2,834,943
template function roundTo int, float -> truncation
according to this question: Calling template function without <>; type inference the round function I will use in the future now looks like: template < typename TOut, typename TIn > TOut roundTo( TIn value ) { return static_cast<TOut>( value + 0.5 ); } double d = 1.54; int i = rountTo<int>(d); However it make...
Assuming you want the closest integer value, cast to TOut, static_cast<TOut>( static_cast<long long>(value + 0.5) ); floor should also work as an alternative to the inner cast. The point is not to rely on the cast to an unknown type to perform any truncation -- ensure the truncation explicitly, with a floor or a cast...
2,835,030
2,835,049
Representing a 16 byte variable
I have to represent a 16 byte field as part of a data structure: struct Data_Entry { uint8 CUI_Type; uint8 CUI_Size; uint16 Src_Refresh_Period; uint16 Src_Buffer_Size; uint16 Src_CUI_Offset; uint32 Src_BCW_Address; uint32 Src_Previous_Timestamp; /* The field below should be a 16...
Anything wrong with uint8 Data[16];?
2,835,092
2,835,322
C++ Beginner - Best way to read 3 consecutive values from the command line?
I am writing a text-based Scrabble implementation for a college project. The specification states that the user's position input must be read from single line, like this: Coordinates of the word's first letter and orientation (<A – P> <1 – 15> <H ou V>): G 5 H G 5 H is the user's input for that particular example. Th...
getline and parsing doesn't necessarily have to add much work. Since you already know how to read (correct) data from a stream, just read a line with getline, then create an istringstream from the line and read from there. The one thing I'd add would be that it might very well make sense to create a class to hold the d...
2,835,094
2,835,228
Calculating free disk space
What is the best method for calculating free disk space using C++ only. My target platform is WinCE but most of the file operations are the same as normal Windows.
You mean usage as in how much space is left? then try GetDiskFreeSpace() Or do you mean, number of reads/writes/current files open, speed etc?
2,835,626
2,835,645
C++0x lambda capture by value always const?
Is there any way to capture by value, and make the captured value non-const? I have a library functor that I would like to capture & call a method that is non-const but should be. The following doesn't compile but making foo::operator() const fixes it. struct foo { bool operator () ( const bool & a ) { return ...
Use mutable. auto bar = [=] () mutable -> bool .... Without mutable you are declaring the operator () of the lambda object const.
2,835,716
2,838,044
How do I call functions inside C++ DLL from Lua?
I have a DLL written in C++ that is legacy code and cannot modify the source code. I want to be able to call some of the functions inside of the DLL from Lua. For example, I'd like to do something like this: -- My Lua File include(myCppDll.dll) function callCppFunctionFromDll() local result = myCppFunctionFromDl...
If Alien doesn't meet your needs, and it might not be easy to use if the DLL has a strongly object oriented interface where you need to get at the members and methods of objects as well as just call exported functions, then you should look at generating a wrapper DLL that interfaces the legacy API from the DLL to Lua. ...
2,835,746
2,835,761
How do you specify a 64 bit unsigned int const 0x8000000000000000 in VS2008?
I read about the Microsoft specific suffix "i64" for integer constants. I want to do an UNsigned shift to a ULONGLONG. ULONGLONG bigNum64 = 0x800000000000000i64 >> myval; In normal C, I would use the suffix "U", e.g. the similar 32 bit operation would be ULONG bigNum32 = 0x80000000U >> myval; I do NOT want the 2's com...
You can use the suffix ull, which is the standard (C99 and C++0x) way to specify an unsigned long long integer literal, and a long long is at least 64 bits.
2,835,847
2,835,875
C++ stack for multiple data types (RPN vector calculator)
I have designed a quick and basic vector arithmetic library in C++. I call the program from the command line when I need a rapid cross product, or angle between vectors. I don't use Matlab or Octave or related, because the startup time is larger than the computation time. Again, this is for very basic operations. I am ...
The simplest way would be just to create an Operand struct that contains a double for the scalar and a Vector object for the vector: struct Operand { double scalar_; Vector vector_; bool isVector_; }; (you can set isVector_ to true if it is a vector operand, and false if it is a scalar operand) For the act...
2,835,910
2,835,937
C++ - How to efficiently find out if any string in a vector can be assembled from a set of letters
I am implementing a text-based version of Scrabble for a college project. I have a vector containing around 400K strings (my dictionary), and, at some point in every turn, I'm going to have to check if there's still a word in the dictionary which can be formed with the pieces in the player's hand. I'm checking if the p...
Without giving you any specific code (since this is homework after all), one general approach to consider is to map from the sorted letters in the word to the actual legal words. That is to say, if your dictionary file had only the words ape, gum, and mug, your data structure would look like: aep -> ape gmu -> gum, mug...
2,836,033
2,839,053
Suggestion for chkstk.asm stackoverflow exception in C++ with Visual Studio
I am working with an implementation of merge sort. I am trying with C++ Visual Studio 2010 (msvc). But when I took a array of 300000 integers for timing, it is showing an unhandled stackoverflow exception and taking me to a readonly file named "chkstk.asm". I reduced the size to 200000 and it worked. Again the same co...
Problem solved. Thanks to Kotti for supplying the code. I got the problem while comparing with that code. The problem was not about too much recursion. Actually I was working with a normal C++ array which was being stored on stack. Thus the problem ran out of stack space. I just changed it to a dynamically allocated a...
2,836,396
2,836,724
How to simulate inner exception in C++
Basically I want to simulate .NET Exception.InnerException in C++. I want to catch exception from bottom layer and wrap it with another exception and throw again to upper layer. The problem here is I don't know how to wrap the catched exception inside another exception. struct base_exception : public std::exception { ...
You should also take a look at boost exception for an alternative solution to wrapping.
2,836,473
2,836,499
Developing Android applications with Visual Studio 2008
I've recently obtained an HTC Desire and I'm interested in porting my 3D engine to the device. I have a slight annoyance however. I'd love to be able to do development under Visual Studio 2008. Am I to assume I'm going to need to re-process my SLN files to do GCC builds? Its not a vast issue as I already have an a...
You will need to use your own or the NDK supplied build system. I believe Visual Studio can be set up to call external commands to build. You can of course use Visual Studio as the code editor, and call the NDK supplied make on the Makefile to build your application. You can't use Visual Studio as a debugger.
2,836,743
2,836,764
C++, class as parameter to a method, not template
So, I came across an interesting method signature that I don't quite understand, it went along the lines of: void Initialize(std::vector< std::string > & param1, class SomeClassName * p); what I don't understand is the "class" keyword being used as the parameter, why is it there? Is it necessary to specify or it is pu...
It is a forward declaration of the class. It is the effectively the same as class SomeClassName; void Initialize(std::vector< std::string > & param1, SomeClassName * p); There are many situations in which a forward declaration is useful; there's a whole list of things that you can and can't do with a forward declarat...
2,836,863
2,836,891
Is there long long defined?
Where to check if type long long is defined? I wanna do something like this: #ifdef LONGLONG #define long_long long long #else #define long_long long #endif
LLONG_MAX gives the maximum value representable by a long long; if your implementation doesn't support long long, it shouldn't define LLONG_MAX. #include <limits.h> #ifdef LLONG_MAX #define long_long long long #else #define long_long long #endif This isn't a perfect solution. long long isn't standard in C++03, and l...
2,836,939
2,836,985
Purpose of Explicit Default Constructors
I recently noticed a class in C++0x that calls for an explicit default constructor. However, I'm failing to come up with a scenario in which a default constructor can be called implicitly. It seems like a rather pointless specifier. I thought maybe it would disallow Class c; in favor of Class c = Class(); but that d...
This declares an explicit default constructor: struct A { explicit A(int a1 = 0); }; A a = 0; /* not allowed */ A b; /* allowed */ A c(0); /* allowed */ In case there is no parameter, like in the following example, the explicit is redundant. struct A { /* explicit is redundant. */ explicit A(); }; In some C++...
2,836,956
2,836,973
how to templatize partial template specializations?
I'm not even sure what title to give this question; hopefully the code will demonstrate what I'm trying to do: #include <string> #include <list> using namespace std; template<typename A> class Alpha { public: A m_alpha_a; }; template<typename B> class Bravo { public: B m_bravo_b; }; template<> class Alpha<string> { p...
Just replace template<typename B> template<> class Alpha<Bravo<B> > with template<typename B> class Alpha<Bravo<B> > i.e. remove template<> here.
2,836,978
2,837,113
GCC, -O2, and bitfields - is this a bug or a feature?
Today I discovered alarming behavior when experimenting with bit fields. For the sake of discussion and simplicity, here's an example program: #include <stdio.h> struct Node { int a:16 __attribute__ ((packed)); int b:16 __attribute__ ((packed)); unsigned int c:27 __attribute__ ((packed)); unsigned int d:3 __a...
If you want to get technical, the minute you used __attribute__ (an identifier containing two consecutive underscores) your code has/had undefined behavior. If you get the same behavior with those removed, it looks to me like a compiler bug. The fact that a 3-bit field is being treated as 7 means that it's being treat...
2,837,222
10,542,678
Is Perforce's C++ P4API thread-safe?
Simple question - is the C++ API provided by Perforce thread-safe? There is no mention of it in the documentation. By "thread-safe" I mean for server requests from the client. Obviously there will be issues if I have multiple threads trying to set client names and such on the same connection. But given a single connect...
Late answer, but... From the release notes themselves: Known Limitations The Perforce client-server protocol is not designed to support multiple concurrent queries over the same connection. For this reason, multi-threaded applications using the C++ API or the derived APIs (P4API.NET, P4Perl, e...
2,837,241
2,837,277
C++ Returning Pointers/References
I have a fairly good understanding of the dereferencing operator, the address of operator, and pointers in general. I however get confused when I see stuff such as this: int* returnA() { int *j = &a; return j; } int* returnB() { return &b; } int& returnC() { return c; } int& returnC2() { int *d =...
In returnA() I'm asking to return a pointer; just to clarify this works because j is a pointer? Yes, int *j = &a initializes j to point to a. Then you return the value of j, that is the address of a. In returnB() I'm asking to return a pointer; since a pointer points to an address, the reason why returnB() works is ...
2,837,346
2,837,361
Variable Scoping in a method and its persistence in C++
Consider the following public method that adds an integer variable to a vector of ints(private member) in a class in C++. KoolMethod() { int x; x = 10; KoolList.Add(x); } Vector<int>KoolList; But is this a valid addition to a vector ??? Upon calling the method, it creates a local variable. The scope of this loca...
But is this a valid addition to a vector? Yes, a (standard library) vector stores copies. Is there a need for creating an int in heap storage using "new" operator If you don't want the objects to be copied or to work with polymorphic objects (see object slicing) you'd use pointers. In that case you should preferabl...
2,837,469
2,837,499
C++ Preprocessor string literal concatenation
I found this regarding how the C preprocessor should handle string literal concatenation (phase 6). However, I can not find anything regarding how this is handled in C++ (does C++ use the C preprocessor?). The reason I ask is that I have the following: const char * Foo::encoding = "\0" "1234567890\0abcdefg"; where enc...
The language (C as well as C++) has no "preprocessor". "Preprocessor", as a separate functional unit, is an implementation detail. The way the source file(s) is handled if defined by so called phases of translation. One of the phases in C, as well as in C++ involves concatenating string literals. In C++ language standa...
2,837,584
2,876,466
Rakefile rule output generation problem
i have a Rakefile with a rule like this : rule '.so' => '.cc' do |t| puts "@ Compiling #{t.source}" output = t.source.ext("so") output['stdlib'] = 'build' sh "mkdir -p #{File.dirname(output)}" sh "#{CXX} #{t.source} -o#{output} #{STDLIB_CFLAGS} #{STDLIB_LFLAGS}" end As you can see, it generates man...
You can either use the pathmap syntax or an explicit proc to change the output filename/path into the input filename/path. The pathmap syntax will look something like this (untested): rule '.so' => '%{build,stdlib}X.cc' do |t| puts "@ Compiling #{t.source}" sh "mkdir -p #{File.dirname(t.name)}" sh "#{CXX} #{t....