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
5,547,212
5,548,987
Fences in C++0x, guarantees just on atomics or memory in general
The C++0x draft has a notion of fences which seems very distinct from a CPU/chip level notion of fences, or say what the linux kernel guys expect of fences. The question is whether the draft really implies an extremely restricted model, or the wording is just poor and it actually implies true fences. For example, under...
Fences provide ordering on all data. However, in order to guarantee that the fence operation from one thread is visible to a second, you need to use atomic operations for the flag, otherwise you have a data race. std::atomic<bool> ready(false); int data=0; void thread_1() { data=42; std::atomic_thread_fence(st...
5,547,664
5,547,677
What C++0x Headers are supposed to define nullptr?
Now that C++0x is almost here, I've been experimenting with it, and in particular using nullptr. I haven't been able to figure out what standard header files one is supposed to include if one needs to use it. Any help is appreciated.
No headers should be required. It is a built-in keyword (§[lex.nullptr]). 2.14.7 Pointer literals                 [lex.nullptr] pointer-literal:         nullptr The pointer literal is the keyword nullptr. It is a prvalue of type std::nullptr_t. [ Note: std::nullptr_t is a distinct type that is neither a ...
5,547,751
5,547,793
Work in DEBUG mode but fail in RELEASE mode
Why does program work in debug mode, but fail in release mode? Thanks...
You're probably using uninitialised memory somewhere. In DEBUG mode memory is initialised to special values. Make sure you're initialising all your variables.
5,547,771
5,548,642
Scala strict type system vs C++ type system
For fans of Scala's strict type system, but fans of C++: Is it possible to force yourself to program C++ with the same strictness? (not using void*, not casting a lot, boxing simple value type ie struct Month {int value;}; ). Or is C++ by default even stricter then Scala (if you do not try hard with casts)? Despite th...
Short answer: yes, you can reach the same level of type safety, but it will place a burden on the programmer. It's not simply a question of providing the same safety, the type system must also be powerful and flexible enough to facilitate typesafe programming and in this regard Scalas type system is superior to C++. C+...
5,547,852
5,548,016
String literals not allowed as non type template parameters
The following quote is from C++ Templates by Addison Wesley. Could someone please help me understand in plain English/layman's terms its gist? Because string literals are objects with internal linkage (two string literals with the same value but in different modules are different objects), you can't use them as templa...
Your compiler ultimately operates on things called translation units, informally called source files. Within these translation units, you identify different entities: objects, functions, etc. The linkers job is to connect these units together, and part of that process is merging identities. Identifiers have linkage†: i...
5,547,911
5,548,450
SEGFAULT - On C++ pure virtuals. Why?
I am passing a pure-virtual base class pointer arround through C code as a void *. When I dereference the base class in C++, the debugger is able to access all of its members. However, when I attempt to access a pure virtual function it SEGFAULTs/Access Violation. "Cannot access memory at 0xc" says the debugger (when I...
delete this; // Is dangerous, use with care What I was doing is delete this; in the pure virtual function, returning immediately, and then calling another pure virtual function on the already deleted object. Pure virtual vtable will fail when object has already been deleted
5,548,273
5,548,309
How close pipe handle in windows? (fclose() of _pclose())?
If I create pipe in windows this way: CreatePipe(hRead, hWrite, &sec_atr, NULL) Then make FILE * from hRead this way: int fd = _open_osfhandle((intptr_t)hRead, _O_RDONLY|_O_TEXT); FILE *pipe_read = _fdopen(fd, "rt"); Then how should I close this file (pipe_read)? fclose(pipe_read) _pclose(pipe_read) CloseHandle((HAN...
From the example here, use fclose. The documentation for fclose further clarifies with: When these functions are used to close a stream, the underlying file descriptor and OS file handle (or socket) are closed, as well as the stream. Thus, if the file was originally opened as a file handle or file descriptor and is c...
5,548,364
5,548,410
How close pipe handle in unix? (fclose() of pclose())?
If I create pipe in unix this way: int fds[] = {0, 0}; pipe(fds); Then make FILE * from fds[0] this way: FILE *pipe_read = fdopen(fds[0], "rt"); Then how should I close this file (pipe_read)? fclose(pipe_read) pclose(pipe_read) close(fileno(pipe_read))
fdopen returns a FILE* so you should fclose it. This will also close the underlying file descriptor as well. The pclose call is meant for closing a handle created with popen, a function you use for running a command and connecting to it with pipes. The close call will close the underlying file descriptor but, unfortuna...
5,548,451
5,548,473
Creating new structs on the fly
I am (very) new to C++, and am having some issues understanding structs. I'm using example code from a course, so I have: struct Point { int x; int y; } In another bit of code, I want to write the following: drawLine(point1, new Point(x, y)); This does not work, and I understand that I am trying to declare a st...
The problem isn't that you're trying to declare a struct as if it were a class (in fact, there's very little difference between the two in C++). The problem is that you're trying to construct a Point from two ints, and there ins't a suitable constructor. Here is how you can add one: struct Point { int x; int y; ...
5,548,636
5,548,797
What are Unrestricted Unions proposed in C++11?
I gather unrestricted unions as one of the functionality being put forth in C++11. Can anyone please explain the semantics behind this and the advantages it provides?
There is an explaination on Wikipedia : http://en.wikipedia.org/wiki/C%2B%2B0x#Unrestricted_unions Search there first before asking about C++0x features explainations. Unrestricted unions In Standard C++ there are restrictions on what types of objects can be members of a union. For example, unions cannot contai...
5,548,639
5,548,850
What can "new_handler" be used for in C++ besides garbage collection?
C++ programs can define and set a new_handler() that should be called from memory allocation functions like operator new() if it's impossible to allocate memory requested. One use of a custom new_handler() is dealing with C++ implementations that don't throw an exception on allocation failure. Another use is initiating...
In a similar vein to the garbage collection application, you can use the new handler to free up any cached data you may be keeping. Say that you're caching some resource data read from disk or the intermediate results of some calculation. This is data that you can recreate at any time, so when the new handler gets call...
5,548,670
5,548,688
%llx format specifier: invalid warning?
Edited to remove the first warning The following code works as expected in g++ 4.4.0 under mingw32: #include <cstdio> int main() { long long x = 0xdeadbeefc0defaceLL ; printf ("%llx\n", x) ; } But if I enable all warnings with -Wall, it says: f.cpp: In function 'int main()': f.cpp:5: warning: unknown convers...
long long x = 0xdeadbeefc0defaceLL; // note LL in the end And there is no ll length specifier for printf. The best you can get is: printf ("%lx\n", x); // l is for long int I've tested your sample on my g++, it compiles without errors even without -std=c++0x flag: ~$ g++ -Wall test.cpp ~$ g++ --version g++ (Ubuntu 4...
5,548,763
5,548,798
Size-Of C-Array as a function?
Possible Duplicate: How does this “size of array” template function work? Is there any possibility to implement NARR without a macro in C++ (C++0x)? const static pair<string,int> data[] = { {"Montag",1}, {"Dienstag",2}, {"Mittwoch",3}, {"Donnerstag",4}, {"Freitag",5}, {"Samstag",6}, {"Sonntag",7} }; #define ...
It is possible in C++: template< typename T, std::size_t Size > std::size_t size(const T (&)[Size]) { return Size; } The advantage of this over the macro solution is that the compiler will cough up a nasty error message if you try to pass a pointer to this.
5,549,028
5,550,981
Nested boost (preprocessor) sequence
Why can't i call BOOST_PP_SEQ_FOR_EACH from inside a macro like this: #define MAP_KEY_TYPES (int)(double)(std::string) #define MAP_VAL_TYPES (int)(double)(std::string)(std::vector<int>) #define DECLARE_MAP_VARIANTS(r, K, V) \ void toJson( Json::Value &j, const std::map< K, V >& v);\ void fromJson(const ...
Unfortunately, I suppose this cannot be done only with BOOST_PP_SEQ_FOR_EACH. If BOOST_PP_SEQ_FOR_EACH_PRODUCT is allowed instead, probably the following macro will meet the purpose: #define DECLARE_MAP_VARIANTS_(r, KV) \ DECLARE_MAP_VARIANTS(r, BOOST_PP_SEQ_ELEM(0, KV), BOOST_PP_SEQ_ELEM(1, KV)) BOOST_PP_SEQ_FOR_...
5,549,448
5,549,495
how to store the output of system() call?
I am using system(3) on Linux in c++ programs. Now I need to store the output of system(3) in an array or sequence. How I can store the output of system(3). I am using following: system("grep -A1 \"<weakObject>\" file_name | grep \"name\" | grep -Po \"xoc.[^<]*\" | cut -d \".\" -f5 "); which gives output: changi...
system spawns a new shell process that isn't connected to the parent through a pipe or something else. You need to use the popen library function instead. Then read the output and push each string into your array as you encounter newline characters. FILE *fp = popen("grep -A1 \"<weakObject>\" file_name | grep \"name\" ...
5,549,515
5,550,488
cmake / c++ : which package contains `-lOpenGLSupport`
/usr/bin/ld: cannot find -lOpenGLSupport The above error occurs when linking. I have googled, to no avail. Where can I obtain this library (package / build from source)? (If this question is more at home/ appropriate on superuser.com, mods feel free to move it) Thanks! OS is Ubuntu Karmic.
-lOpenGLSupport appears to be from the bulletphysics library. More details: I had built this from source, however, had not specified that it should build shared libraries. Doing this appears to have rectified the problem. For future reference: Build bulletphysics using these commands cmake -DBUILD_SHARED_LIBS=ON -DCM...
5,549,524
5,549,918
How do I initialize a member array with an initializer_list?
I'm getting up to speed with C++0x, and testing things out with g++ 4.6 I just tried the following code, thinking it would work, but it doesn't compile. I get the error: incompatible types in assignment of ‘std::initializer_list<const int>’ to ‘const int [2]’ struct Foo { int const data[2]; Foo(std::initiali...
You can use a variadic template constructor instead of an initializer list constructor: struct foo { int x[2]; template <typename... T> foo(T... ts) : x{ts...} { // note the use of brace-init-list } }; int main() { foo f1(1,2); // OK foo f2{1,2}; // Also OK foo f3(42); // OK; x[1...
5,550,110
5,550,152
enums declaration in class C++, problem getting to enum in class
I have problem with the declaration of enum in my class. I had tried to declare it on private, public, outside, in the main, nothing works. I need to call function in the class from outside and use the enums in the function here is my code. class Algoritem { public: enum Optimization { W , A , D }; enum Fen...
You have to specifiy which class the enums are defined in. So, e.g. call the function like this: OptimalPatrol(N, K, VS, T, Algoritem::W, Algoritem::OF, Algoritem::BR, Imax, P); That way, your compiler knows in which class to look for the enum declarations.
5,550,549
5,550,789
Getting Qt to work in Fedora 12
Qt is installed by default in Fedora 12. Tried the hello world program: #include </usr/include/QtGui/QApplication> #include </usr/include/QtGui/QPushButton> int main(int argc, char *argv[]) { QApplication app(argc, argv); QPushButton hello("Hello world!"); hello.show(); return app.exec(); } With norma...
The problem is that /usr/include/QtGui/ is "protected". (You do not have write permissions to that directory) Move your helloworld.cpp to a directory that you have write access to. For example /home/yourusername/helloworld/helloworld.cpp Change: #include </usr/include/QtGui/QApplication> #include </usr/include/QtGui/QP...
5,550,690
5,550,716
C++ debug release version
Very basic question. I want to debug release version of my exe. My debug version is working fine. But release version crashing as usual. Any tool or debugger available for this would be a great help.
You can still enable debug information in release mode, and use a debugger as usual. Nothing particular here, except that the order of instructions will sometimes look weird when debugging due to optimizations. Good luck, debugging release-mode-only bugs is tedious.
5,550,838
5,550,849
How to convert CString to ofstream?
I have a few CString variables that I wish to output to an ofstream, but I can't seem to figure out how to do so. Here's some example code. I have unicode enabled in VS 2005 CODE: ofstream ofile; CString str = "some text"; ofile.open(filepath); ofile << str; // doesn't work, gives me some hex value such as 00...
If you just want plain ACP encoded ANSI text: ofile << CT2A(str); ofstream formatted output functions expect narrow/ansi strings. CStrings represent TCHAR strings. The CT2A macro Converts TCHAR 2 Ansi. http://msdn.microsoft.com/en-us/libr...8VS.80%29.aspx
5,550,843
5,551,050
Adding Resources in Microsoft Visual C++ 2010 Express
Possible Duplicate: visual c++ 2010 can't add resource file To add bitmap I should add it as a resource (that's what I read in some tutorial). So when I right-click on a project name in Visual C++, and then find 'Add' submenu, I find that adding resource button is inactive (grey). How can I add bitmap then? Or how d...
Visual C++ Express editions don't have a resource editor. That is one of its limitations. However, maybe this will help: http://www.suite101.com/content/vc-express-external-res-editor-a21264.
5,551,018
5,551,065
Should I put classes in separate files in C++?
I am asking this question to organize my code.
C and C++ convention is one header file per library, or section of a library, rather than one header file per class. Try to group related classes together. So for example in the standard libraries <set> contains both std::set and std::multi_set, but then those are templates that do very similar things. There isn't any ...
5,551,071
6,474,838
Understanding types in SystemC
I am a beginner in SystemC programming and there is one thing I noticed (looking in the SystemC official documentation): all types that I used to deal with in VHDL simulations have not been "ported" to SystemC. I mean: Consider std_logic in the VHDL standard library, there is not an equivalent in SystemC, however, in ...
Consider std_logic in the vhdl standard library, there is not an equivalent in SystemC, however, in the sysc documentation, I see many examples using bool. Consider std_logic_vector, I see no equivalent in sysc. Instead I can see, in many examples, usage of sc_int. It's not all that correct. In SystemC you can use ...
5,551,118
5,552,892
How to connect to Teradata with C++ on linux
Simple Problem: I want to connect my linux based C++ program to a Teradata database. How do I accomplish this? I searched the web but I only found some ADO and ODBC based solutions for .net or JDBC drivers. Is there any lib out there that can do the job on linux without ODBC and .net? Greetings, Lars
Teradata Call-Level Interface Version 2 Reference for Network Attached Systems - Documentation Teradata Developer Exchange - Downloads - You can download the CLI for Linux, Windows, Solaris, HP-UX, and AIX from there. You can also find links to other developer resources to download as well. Including VMware images of T...
5,551,441
5,551,462
need to call the base destructor method from a derived class in c++?
Please consider the following: class base{ base(); ~base(); }: class derived : public base{ }; Does a base class destructor get automatically invoked when a derived object is destructed when the derived class has no destructor defined? Otherwise, if I DO have a destructor in the derived class too, do I have ...
The base class destructor is automatically invoked in this case; you do not need to call it. However, note that when destroying an object through delete on a base class pointer and the destructor is not virtual, the result is going to be undefined behavior (although you might not get a crash). Always declare the destru...
5,551,640
5,551,673
C++ Design Pattern for Passing a Large Number of Parameters
I have a reasonably-sized class that implements several logically-related algorithms (from graph theory). About 10-15 parameters are required as input to the algorithm. These are not modified by the algorithm, but are used to guide the operation of it. First, I explain two options for implementing this. My question is ...
This is called the "Parameter object" pattern, and it's generally a good thing. I don't like the member version, especially calling it "XGlobals" and implying that it's shared all over the place. The Parameter Object pattern instead generally involves creating an instance of the Parameter Object and passing it as a par...
5,551,767
5,554,204
how to do cryptography (digital signature)in linux
I have done PKCS_7_ASN_ENCODING | X509_ASN_ENCODING in windows using wincrypt and I have to verify signature in linux. Can anyone tell by about good light crypto api on linux. On searching I found http://home.gna.org/cryptodev-linux/ and on compiling it i am getting this error crypto/hash.h: No such file or direct...
This error occurs because you don't have the kernel headers for your system/kernel, therefore when you try to compile, it's unable to find those headers. More on your end goal, do you want to validate whether a certificate is signed by someone else's certificate? If so, and if you're open to use OpenSSL, take a look at...
5,551,811
5,551,862
What does the () at the end of dynamic array allocate mean?
I have see some example like below in a different question which I have not seen before. new int[m_size](); ^^ I have seen and used the version new int[m_size] all the time but not one with the () at the end.
Two words : Value Initialization new int[m_size](); array elements would be zero-initialized by writing () because () implies value initialization.1 (zero initialization for a primitive type) 1: An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized. ( $8.5/7 )
5,551,961
5,572,174
How to reexport CLR c++ static library
I have these files: foo.dll foo.lib foo.exp bar.il bar.netmodule "foo" defines functions in its export directory. I also have a Visual Studio 2010 C++ project which will create a managed "bar.dll" I want to "bar" to statically link to "foo" and reexport all functions from "foo". In the end I want bar to export the fu...
I have figured it out. Instead those files will be required: foo.obj bar.cpp bar.obj The C++/CLI compiler cl.exe will be able to compile bar, reference unmanaged and managed worlds. In a later step linker will be used to merge obj files into one mixed mode assembly containing: unmanaged exports from foo unmanaged e...
5,552,160
5,552,223
How can I determine which C++ compiler is used if I only can alter the C++ code and inspect console output?
Suppose there's a system like codepad.org - a black box that can accept C++ code, compile it, run it and present the console output. How could I determine what C++ compiler such system uses?
You could have an ifdef fest to detect what the compiler is, using all the information compiled in this page.
5,552,163
5,560,859
Using it++ with cmake ( QT )
I have a IT++ Project for implementing Turbo Codes which works fine with the Makefile. I have another C++ project which I am developing in QT. I plan to integrate both. What changes I need to make in the *project.pro file. What additional FLAGS or VARIABLES need to be set ? Thanks
Check if links below would be helpful: Using CMake to Build Qt Projects cmake for Qt 4 hope this helps, regards
5,552,282
5,565,599
How to close an opened serial port?
suppose an application (not me!) has opened a Serial port (COM1) , and i do not have access to it's handle (or something like that) and i don't know... now, how can i close and release it by C# or C++? thanks.
There's a Windows API function called CloseHandle(HANDLE hObject). if we have the handle of file / port opened , then we can close it. thanks everyone...
5,552,455
5,554,093
Priority of template selection in C++
I just written the following piece of code template<typename T> inline bool contains(T haystack,typename T::key_type needle) { return haystack.find(needle) != haystack.end(); } template<typename T> inline bool contains(T haystack,typename T::value_type needle) { return find(haystack.begin(),haystack.end(),need...
If you are willing to do it, you can, with some metaprogramming help to aid you. Basically you would need to write a template metafunction that determines the condition under which you want to call one or the other functions, and use that in an enable_if_c clause: template <typename T> inline typename enable_if_c< has_...
5,552,473
5,552,532
Pointer to inline __asm block in c++
So I've been screwing around with the __asm block in VS2010 and I haven't been able to find a better way to get the pointer to the start of the assembly block. The only way I know how to do this, is to declare a void function. One problem with this is that the void function will have its own assembly before and after m...
You basically want to enable __declspec(naked) on your function, to avoid the compiler-generated prologue and epilog. See also: http://msdn.microsoft.com/en-us/library/h5w10wxs(v=vs.80).aspx
5,552,543
5,552,640
Does pthread_cond_signal function unlock the mutex the calling thread locked?
When i call 'pthread_cond_signal' during my thread's function, does this call unlock the mutex i currently use? (Not the one the pthread_cond_wait is waiting for).
Only the mutex given to pthread_cond_(timed_)wait() is unlocked to give other threads the chance to change the condition. At the end of pthread_cond_wait, the mutex is locked again. No other functions lock/unlock mutexes.
5,552,689
5,552,882
Calling/instantiating function explicitly with 'templatized template'
Following code works fine: template<typename T> struct Wrap {}; template<template <class> class OUT, typename IN> void Extract (OUT<IN> *obj) { /* only class 'IN' is used in some way */ } int main () { Wrap<int> obj; Extract(&obj); } But, I am passing a pointer argument to extract the outer type and inner type. ...
How about Extract<Wrap, int> (&obj);? But why do you want to specify it explicitly? Most of the time you'd rather have the compiler deduce the types for you automatically for simplicity. EDIT: Have you considered just specializing for Wrap<U>? #include <iostream> template<typename T> struct Wrap {}; template <class T...
5,552,796
5,552,907
Restarting a game and reinstantiate objects
Introduction I am creating a small game in C++ and would like to create a function to restart the game. First I am creating the object player. Then I have an if statement to determine when a certain key is pressed to call the New() method. My goal In that method I would like to reinstantiate an object of the Player cl...
You're confusing pointer and non-pointer variables. new Player() returns the address of a dynamically allocated Player object. You cannot assign this address to the non-pointer variable player; you'd need to declare player as a pointer: Player* player = new Player(); You also need to remember to release the memory pre...
5,552,806
5,553,004
Const char * vs const wchar_t* (concatenation)
which is the best way to concat? const char * s1= "\nInit() failed: "; const char * s2 = "\n"; char buf[100]; strcpy(buf, s1); strcat(buf, initError); strcat(buf, s2); wprintf(buf); It gives error. What should be the correct way? Thanks.
I think the correct way is: std::string msg = std::string("Init() Failed ") + initError + "\n"; std::cout<<msg; or std::cout<<"Init() Failed "<<initError<<"\n";
5,552,981
5,553,795
RVO/NRVO and public undefined copy constructor
I'm fighting the following proposal now, and I want to know legal and for lesser extent moral arguments against it or for it. What we had: #include <vector> class T; class C { public: C() { } ~C( ) { /*something non-trivial: say, calls delete for all elements in v*/ } // a lot of member functions that mod...
This compiles and links (and works) using recent g++ (which is the only target compiler) both 4.1.2 and 4.4.5 -- because of (N)RVO the copy-constructor is never called; destructor is called at the end of main() only. While it may work with GCC, your code really has undefined behavior because it references a function ...
5,553,103
5,553,209
g++ -Wall not warning about double-> int cast
In the following snippet no warnings are produced. g++4.4.3 -Wall -pedantic //f is void f(int ); f(3.14); double d = 3.14; int i = d+2; I have a strong recollection of this being a warning, something along the lines of "Possible loss of precision". Was it removed or is my memory playing tricks on me? How can i turn t...
$ gcc -Wconversion test.c test.c: In function ‘main’: test.c:3: warning: conversion to ‘int’ from ‘double’ may alter its value
5,553,174
5,553,262
C++ generic container with linked list
I want to design a generic container for use with linked lists (for example). I tried using void* as an element but this fails when I provide the following. list.insert(5); list.insert("Hello"); If I allocate the member on the heap and pass the address it works, but how can I handle the case of using stack variables i...
You need to add the size in bytes somehow. int x = 5; insert (&x, sizeof(int)); insert ("Hello", 6); etc. The insert method could then for example look like this: void insert (void* data, size_t size) { node_t node = malloc ... node.data = malloc ... node.size = size; memcpy(node.data, data, size); }
5,553,734
5,575,484
Does Awesomium allow me to call/use C++ variables/methods in JS?
Awesomium easily allows for C++ code to call Javascript methods, but I haven't found a definite answer as to if it can do the opposite. This site seems to say that you can, but looking through the text and examples doesn't enlighten me. So, I'm looking for a definite answer: can I call C++ variables/methods in my Javas...
You definitely can-- you'll just need to build an extra layer on top of WebView::setObjectCallback and WebViewListener::onCallback using delegates/function-pointers. I wrote a quick JSDelegate.h class (view it here) that you can use to hookup "onCallback" events directly to C++ member functions. The basic idea is to ma...
5,553,811
5,555,707
Searching a multimap in reverse order
Is there a method for searching a multimap (C/C++ STL) in reverse order in logarithmic complexity ?
Your question can be interpreted two ways. If you mean that you've inserted a bunch of elements with the same key and you want to find the last-inserted element with that key, then you can try equal_range(key), which returns a pair of iterators (one pointing to the first element, the other the last). However I don't ...
5,553,850
5,553,931
Is there any penalty/cost of virtual inheritance in C++, when calling non-virtual base method?
Does using virtual inheritance in C++ have a runtime penalty in compiled code, when we call a regular function member from its base class? Sample code: class A { public: void foo(void) {} }; class B : virtual public A {}; class C : virtual public A {}; class D : public B, public C {}; // ... D bar; bar.fo...
There may be, yes, if you call the member function via a pointer or reference and the compiler can't determine with absolute certainty what type of object that pointer or reference points or refers to. For example, consider: void f(B* p) { p->foo(); } void g() { D bar; f(&bar); } Assuming the call to f is no...
5,554,148
5,554,260
Shapes in C++ Programs
If I recall correctly, I saw some ungodly C++ library that let you type ASCII-art shapes in C++ programs and treat them as objects. Something like this: int area = someFreakyClass(o-----o | | o-----o).area(); What was this library called?
Analog Literals by Eelis.
5,554,484
5,554,616
What hardware / software do I need to port my C++/wxWidgets app to the MAC?
I have a C++/wxWidgets codebase and I'm starting to think about porting it across to Linux and the Mac OS X. What hardware / software do I need (or is recommended) to code on the Mac platform? Currently I use Visual Studio to develop in and Innosetup to do my packaging.
For Mac development, the simplest and easiest solution is to use Xcode on Mac OS X. You might be able to virtualize that on your Windows box, or install it as second OS depending on your hardware, but the path of least resistance is to develop with an actual Mac in front of you.
5,554,725
5,554,758
Which value is better to use? Boolean true or Integer 1?
Does it make any sense or not?
A boolean true is, well, a boolean value. Use it whenever you want to express that a certain binary condition is met. The integer literal 1 is a number. Use it, whenever you are counting something. Don't use integers for booleans and vice versa. They are different. Consider a variable int isEnabled. Of course, I can ...
5,554,786
5,554,818
How to use POSIX select()
Shoud I make file descriptors non-blocking before using them in select()?
Doesn't matter. select tells you which sockets are readable/writable/closed/have state that you're interested in. Blocking/non-blocking affects how e.g. a recv or send call acts. These are independent of each other.
5,554,822
5,554,940
Performance issues with C++ (using VC++ 2010): at runtime, my program seems to randomly wait for a while
I'm currently trying to code a certain dynamic programming approach for a vehicle routing problem. At a certain point, I have a partial route that I want to add to a minmaxheap in order to keep the best 100 partial routes at a same stage. Most of the program runs smooth but when I actually want to insert a partial rout...
Preempting. Your program may be preempted by the operating system, so some other program can run for a bit. Also, it's not 16 ms. It's 16 clock ticks: http://www.cplusplus.com/reference/clibrary/ctime/clock/ If you want ms, you need to do: cout << "Inserting an expanded state into the heap takes " << (insert_fi...
5,554,844
5,554,880
NonTemplate Function Friend of Template Class
Can somebody explain me what I am doing wrong? This is teh error I get from the compiler. Many Thanks 1>------ Build started: Project: Ch16, Configuration: Release Win32 ------ 1> p643_inclusion.cpp 1> p643_inclusion_main.cpp 1> p643_print.cpp 1>p643_print.cpp(5): error C2065: 'T1' : undeclared identifier 1>p643_pri...
Your function is not actually a non-template function. void print (const Car<T1, T2> &c1) { cout << c1.Wheels << endl; cout << c1.DriversName << endl; } This is wrong. Can you ask yourself what exactly is T1? and T2? You should implement this as: template<class T1, class T2> void print (const Car<T1, T2> &c...
5,554,972
5,555,169
Segmentation fault in std::less<char>
I have the following code (C++0x): const set<char> s_special_characters = { '(', ')', '{', '}', ':' }; void nectar_loader::tokenize( string &line, const set<char> &special_characters ) { auto it = line.begin(); const auto not_found = special_characters.end(); // first character special case if( it !=...
Another guess is that line.append(" ") will sometimes invalidate it, depending on the original capacity of the line.
5,554,990
5,555,392
Proactor and async write
Boost asio implements proactor design pattern baded on ACE proactor. I understand why we need async read. Hovewer, I'm a confused with async write. Why we need is async write? Is it useful for TCP/UDP connection too (can write to TCP/UDP socket take time)? Can I mix async read with sync write?
1) Why we need is async write? Is it useful for TCP/UDP connection too (can write to TCP/UDP socket take time)? Asynchronous write is needed for the very same reasons as asynchronous read. When using synchronous write operations, the calls block until all data has been transmitted. This is not desirable for a numbe...
5,555,085
5,555,158
C++ function pointer syntax
I know that generally, a function pointer is declared like this: void __stdcall my_func(int i) {} // for assigning void (__stdcall * my_ptr)(int) = &my_func; Now I had several functions which take a function pointer as their argument: void calling_func(void (__stdcall * callback)(int)) { *callback(1); } In the he...
That is not a declaration, it's a cast of callback, which is then assigned to. Are you sure you didn't have a pre-existing declaration in scope?
5,555,136
5,561,198
Right-aligned tab items in Win32 tab control
I am trying to create a tab-control that have the tab-buttons aligned from right-to-left, in Win32/c++. The WS_EX_LAYOUTRTL flag doesn't help me, as it mirrors the drawing completely both for the tab items and the tab page contents. The application itself handles the mirroring automatically (it's a cross platform UI so...
If you take a look with a spy application you will see that it is not actually a normal windows tab-control but custom thing and the drawing is done by the parent window AFAIK: Both Visual Studio and Office use a lot of custom controls, some of the features make their way into the common controls after a few years, so...
5,555,507
5,555,532
Catching all invalid memory usage?
In Visual C++, sometimes when a resource has been destructed it can still be "accessed" via anything pointing to that memory location (albeit very unreliably/stably). Is there a way to have VC++ return an exception/message/etc. which would warn against this kind of unstable use? For example: int *c = new int(5); delete...
Don't use raw pointers? Using shared_ptr/unique_ptr or standard containers or boost's ptr containters will really reduce your new/delete problems. Also revisit your design and try to minimize spiderwebs of pointers between objects as much as possible. Use weak_ptr when you can. But to answer your question more directly...
5,555,543
5,555,599
Error C2451 using boost::any
class A { public: void f() { cout << "A()" << endl; } }; class B { public: void f() { cout << "B()" << endl; } }; class C { public: void f() { cout << "C()" << endl; } }; void print(boost::any& a) { if(A* pA = boost::any_cast<A>(&a)) { pA->f...
else if(string s = boost::any_cast<string>(a)) This line is causing you problems. string s is not a pointer, it's a stack variable. You can't do a check for null. The reason you can do a check on the integer below is that integers implicitly map to bool. 0 -> FALSE 1 -> TRUE
5,555,616
5,555,697
converting integer to string C++
I am trying to convert an integer to char array and I came across this piece of code int i = 5; std::string s; std::stringstream out; out << i; s = out.str(); But when I try to print the value of s it still prints 5. I don't know if its supposed to do that or am I doing something wrong? Besides I would prefer if I cou...
Besides I would prefer if I could convert the same int to char array. char *charPtr = new char[ s.length() + 1 ] ; // s is the string in the snippet posted strcpy( charPtr, s.c_str() ) ; // ....... delete[] charPtr ; // Should do this, else memory leak.
5,555,696
5,555,714
NonTemplate Function Friend of Class Template
On Lippman p656 I read: A nontemplate function or class can be a friend to a class template: template<class Type> class Bar { friend class Foobar; friend void fcn(); }; I wonder what all this means. If fcn is made a friend it is becuase you want it to access the private members of Bar, but how can it access...
Being afriend of a class X means the friend (whether it's function, or class) has access to all private and protected members of the class X. In your example, the class Foobar and the function fcn has access to private and protected members of the class Bar. Now the question is: how can it access them it if has not go...
5,556,288
5,556,314
compression API for C++
i am making an application which first compresses a file and then transfer it. I am using C++ as language in UNIX environment. I am unable to find any suitable library for my need. I checked but couldn't find any API for gunzip. Similarly 7zip also has SDK for windows only. It would be great if the library could provid...
zlib or bzip2 - Easy to use and well tested. bzip2 tends to compress better, zlib tends to be faster. Or you could use QuickLZ if speed matters most of all.
5,556,466
5,557,108
Checking at compile time if specified value is in a range of a type
Is it possible to check this: template<class IntType,IntType value> struct X{}; What I mean by this is, is it possible to check that value supplied by user will "fit" into IntType (which can be any of std integer types) type? For example, I would like to detect something like this: X<char,300> a;//here 300 is out of r...
Now that you've changed X's signature from the way it was in the original unedited question, it's easily implemented using Boost.Integer: #include <boost/static_assert.hpp> #include <boost/cstdint.hpp> #include <boost/integer_traits.hpp> template< typename IntType, boost::uint64_t Value, bool IsSigned = bo...
5,556,543
5,556,582
how to convert char string into a std string
I have following code and I cant figure out how to convert char string into a std string. Can someone help me out here? char Path[STRING_MAX]; test->getValue(Config::CODE,Path); size_t found; cout << "Splitting: " << Path << endl; found=Path.find_last_of("/"); cout << " folder: " << Path.substr(0,found) << endl; cout...
Use this: std::string sPath(Path); or: std::string sPath = Path; or: std::string sPath; sPath.assign(Path);
5,556,773
5,558,829
Implementing callback with pointer to non-static member function
Let's say I'm developing a grocery list manager. I have a window with a GroceryListDisplay, which is a control that displays the items that are on the grocery list. The grocery data is stored by the Model component of the program, in the GroceryStorage class. To load a saved file into my program, the Model component of...
The best thing to do is to abstract away from using raw function pointers. There are two usual approaches: The first is to use std::bind + std::function (or their boost:: counterparts on older compilers lacking std:: or std::tr1:: implementations): #include <functional> #include <vector> #include <string> class Grocer...
5,556,844
5,556,867
C Program Portability
As we know java is a platform independent language due to JVM it's program can run at any OS. What about C/C++? could C/C++ exe run at any OS ? Could we have done something about this(Like write once run anywhere)? please clear my doubt about this. Thanks
No - an executable is built for a specific operating system and hardware (CPU) architecture. If you are carefull not to use any OS specific functions, or any assumptions about word size etc, then c++ source can be recompiled to run anywhere.
5,557,002
5,557,074
Can't unblock/"wake up" thread with pthread_kill & sigwait
I'm working on a C/C++ networking project and am having difficulties synchronizing/signaling my threads. Here is what I am trying to accomplish: Poll a bunch of sockets using the poll function If any sockets are ready from the POLLIN event then send a signal to a reader thread and a writer thread to "wake up" I have ...
POSIX threads have condition variables for a reason; use them. You're not supposed to need signal hackery to accomplish basic synchronization tasks when programming with threads. Here is a good pthread tutorial with information on using condition variables: https://computing.llnl.gov/tutorials/pthreads/ Or, if you're m...
5,557,220
5,557,272
Rationale for 'CommonProgramFiles'
Among the many special folder locations in Windows, the 'CommonProgramFiles' seems out of place. The description suggests that components (viz. DLLs) would be shared at that location. It seems to me that a raw DLL storage location was the well-spring of "DLL hell." I had thought MS had moved towards the side-by-sid...
It's been with us for ages and MS doesn't make a habit of removing things because it breaks old programs.
5,557,392
5,557,436
Meaning of operator()?
What is the meaning of operator() in C++? I see that is often used for "functors," or function objects such as comparators. But then how are such functions called? Is it useful in other situations? And how many parameters can I declare for such an operator? E.g., is the following acceptable? bool operator() (Foo f, Baz...
Let's say you have a function object class, Func, with operator() defined. If you have an instance of that class, you can simply place parentheses after the expression referring to that instance: Func myFunc; myFunc(); // Calls the operator() member function As an example from the standard library, we can look at std:...
5,557,492
5,557,628
Arrays in C++ and Java
I never had to approach this before, but can you pass arguments to C++ contructors when creating an array off or on the heap. I have the same question for java, can you pass arguments to contructors when creating an array of objects, or must you just use the default contructor for both C++ and Java. Thanks :-)
Java: String [] as = new String [] {new String ("foo"), new String ("bar")}; This is just initialization of the array with elements while declaring it. But your question shows a misconception: 'or must you just use the default constructor for creating an array of objects'. You often declare an array in Java without d...
5,557,528
5,558,568
How to create and use dll files in C#
I am currently trying to learn how to write and use .dll files for Windows in C# and C++. I think once I understand one of those langueages I will be able to figure out the other one quite easily. I have searched for over 5 hours today but have had no luck in finding a working .dll guide. They are either outdated and r...
DLL's in C# are dead easy. Create a new project that builds to a dll. Add a reference to the new dll project to your existing project. Use classes marked public in your dll as if they were part of your original project. Peachykeen has laid out the most basic way to export classes and functions from a C++ DLL. There i...
5,557,555
5,557,651
RAII and Stack unwinding
TIL that my notions of the 'inter-twining' (for the lack of a better word) of RAII & stack-unwinding are/were quite(if not completely) wrong. My understanding was that using RAII, guarded against any/all resource leaks - even ones potentially caused by unhandled exceptions. However writing this test program and subseq...
From the C++03 standard, §15.3/9: If no matching handler is found in a program, the function terminate() is called; whether or not the stack is unwound before this call to terminate() is implementation-defined (15.5.1). §15.5.1/1: In the following situations exception handling must be abandoned for less subtle error...
5,558,189
5,560,432
Open-Source compression algorithm with Checkpoints
I'm working in C++ with gcc 4.5.0, and msvc8/9. I'd like to be able to compress a file (10 Gb), then open this file using my application. However, the file contents are such that I don't necessarily need everything inside of them everytime I use them. So, for example, one time I open one of these compressed files, an...
bzip2 is free and open-source, and has readily available library implementations. It's block based, so you can decompress only the parts you need. If you need to seek to a particular location in the decompressed file, though, you might need to build a simple index over all the bzip2 blocks, to allow you to determine wh...
5,558,389
8,603,401
Passing CALLBACK from dll to EXE
I have a DLL that I use to hook the Notepad and catch keystrokes. All works well, but I'd like to have access to the KeyboardHook Callback from within my exe. So that everytime the Callback in the .dll is triggered, it passes it's values to the .exe Is this possible? ** HOOK.dll (hookDll.cpp) ** #include "windows.h...
Inside your DLL: LRESULT CALLBACK (*myCallbackRef)(int nCode, WPARAM wParam, LPARAM lParam); extern "C" __declspec(dllexport) void InstallMyHook(LRESULT CALLBACK (*MyCallback)(int nCode, WPARAM wParam, LPARAM lParam)) { myCallbackRef = MyCallback; } Use myCallbackRef with parameters inside KeyboardHook. In your pr...
5,558,504
5,558,557
Templates, polymorphism, abstract base class pointers and run-time casting
I am wanting to implement a Memento pattern in a game for the purpose of implementing checkpoints. I have a list of GameObject pointers in the game. GameObject is an abstract class, which is implemented by classes like StaticObject, AnimatedObject etc... I would like to make my Memento class as abstract as possible, s...
What you're looking for is the "virtual copy constructor", or clone, idiom. class GameObject { ... public: virtual GameObject* clone() = 0; }; class StaticObject : public GameObject { ... public: virtual StaticObject* clone() { return new StaticObject(*this); } }; //..
5,558,523
5,558,649
Is it always true that virtual function cannot be inlined in C++?
It is said that virtual functions cannot be inlined. Is it always true that if a function is declared virtual, it cannot be inlined anywhere in the code, or is it applicable only under certain situations? (eg., calling method from a base pointer vs. calling method on a reference, etc.)
No, virtual functions can indeed be inlined. Virtual dispatch is only used when calling a virtual method polymorphically (i.e., on a pointer or reference to an object). However, when a virtual method is called on an object value, virtual dispatch is not used and the compiler is free to inline as it sees fit.
5,558,728
5,559,401
What is the most short way to run your GLSL shader (not compiled yet) from C++?
So what is simple - crossplatform C++ library for compiling and running GLSL shaders from source and emulating videocard if needed. Generally I want to give it shader and data and be capable to run it and get resulting data. Is there any such library/ or described way to use some libs in combo?
Probably the easiest way would be to use a cross-platform OpenGL framework like GLFW with a bit to compile and use a shader (e.g., one I posted in a previous answer). For systems that didn't support OpenGL otherwise, you'd probably want to use Mesa3D.
5,558,734
5,558,955
c++ bad_weak_ptr error
I want to create some Timer class, which prints "text" every N seconds, where N will be initialized in constructor. #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/enable_shared_from_this.hpp> #include <iostream> class Timer : public boost::enable_shared_from_this<Timer> { public: Timer ( cons...
The problem is most probably that you cannot use shared_from_this until the object is actually managed by a shared pointer. In general it is not a good idea to launch a thread or asynchronous service in the constructor, as you might be unlucky and the new thread might start before the constructor has completed and thus...
5,558,793
5,560,996
Catching SEH exceptions in GUI code
I have a Visual Studio 2008 C++ Windows Mobile 6.5 project where I would like to catch SEH exceptions, write them to a file, and present the user with specific instructions on how to log a defect report for this issue. My code looks pretty much like this: static int WriteDump( struct _EXCEPTION_POINTERS* ep ) { // ...
The window procedure is typically invoked indirectly and the library probably protects itself by inserting an SEH exception block around callback functions, masking the error and preventing it from propagating up the call stack and back to WinMain(). Add an SEH exception block in your window procedure to catch any exce...
5,559,135
5,559,186
Use of dynamic memory allocation for a client socket class in C++
Coming from a Java background I am still grappling with C++ memory allocation and when to use smart pointer, automatic stack allocation or dynamic stack allocation. However I have a concrete use case: I created a class which consists only of a client socket and a function which sends a std::string to the target machine...
Given that a socket/file descriptor is really just an int handle on an object managed by the OS, I'd go for stack allocation + copy construction or pass-by-reference whenever possible. You're only copying an int and the relative overhead of indirection through a pointer would be great. (If you're also storing the hostn...
5,559,146
5,559,302
min and max in opencv
I have a huge amount of points data set. so i want to find min and max values from these points set. now i am using normal for loop for this purpose nice it is working but i want to know posibility to use opencv library since i wish to use this library. so plese any one help me. thanks
No need for OpenCV in this case: it's already in the standard library (std::min_element and std::max_element).
5,559,160
5,560,184
Resulting EXE speed for C++ under VS2005, VS2008; VS2010 compilers
When I upgraded from VS6 to VS2005, I saw a 10% boost in the speed of my chess engine program with the default compile settings. Wondering if the same is true in general, and what improvements, if any, have been made to the final output of the MS C++ compiler since then.
Regarding moving to VC++ 2010+ from versions of VC++ prior to 2010: If you make heavy use of the STL containers and algorithms, upgrading to VC++ 2010+ may provide substantially more than just a 10% improvement, as VC++ 2010+ implement C++11's move semantics. I recall a specific post on the Boost mailing list that clai...
5,559,226
5,559,391
Qt4 problem with formatting hours in QDateTime
I've a problem with following code: QDateTime test2; test2.setTime_t(25); qDebug() << test2.toString("hh:mm:ss"); this prints "01:00:25" to output instead of 00:00:25. Why is the first hour set to 01 instead of 00 ? I thought that maybe am/pm notation is used so i tried this QDateTime test2; test2.setTime_t(3600*22+25...
It's because you didn't set the QDateTime to UTC. So, 00:00:25 on Jan 1st 1970 in UTC time was probably 01:00:25 in your local timezone? And your code says "10:00:25" for me, at UTC+10 :) Try this: QDateTime test2; test2.setTimeSpec(Qt::UTC); test2.setTime_t(25); qDebug() << test2.toString("hh:mm:ss");
5,559,278
5,559,315
How does one get to this stage:
Hey guys reading some of the posts I came to realise something: Reflecting parameter name: abuse of C# lambda expressions or Syntax brilliance? Why is it that atm im learning how to implement operations but I have no bearing on the foundations its made of. I can write a program to do a specific task but I dont know whe...
I hope I understood your question. My answer is: Learn hardware basics (e.g. I/O - memory .. etc) Learn operating systems basics (e.g. threading - processes .. etc) Learn networking basics (e.g. HTTP - TCP/IP - Data packets .. etc)
5,559,357
5,559,612
_DebugHeapDelete Access Violation at termination
I'm getting a weird access violation at the end of my main whose cause I'm having some difficulties finding. When shutting down my application I get an access violation in the following: xdebug // TEMPLATE FUNCTION _DebugHeapDelete template<class _Ty> void __CLRCALL_OR_CDECL _DebugHeapDelete(_Ty *_Ptr) ...
Memory corruption bugs can (obviously) cause this (and many other kinds) of failure. Have you tried using valgrind (memcheck) or Rational Purify against this? It will probably report the problem (possibly buried in a whole lot of other information if this would be the first time you ran such a check on your code base. ...
5,559,432
5,559,728
What order do I include header files in?
I'm new to programming and the topic of header files is sort of bogging me down after I started using a lot of them. In addition to that I'm trying to use precompiled headers. I'm also using the SFML library so I have those headers that also have to be included. Right now I have stdafx.h, main.cpp, then classes A, B, C...
My philosophy is that in well-written code, header files should include all other header files that they depend on. My reasoning is that it should not be possible to include a header file and get a compiler error for doing so. Therefore, each header file should (after the #ifdef or #pragma once include guard) include a...
5,559,482
5,567,339
How would i set up collision using the Bullet Physics Library?
hey im having a bit of a "delay" in setting up some collision in my opengl/sfml game. its not much of an error, just asking for some help. Im using Bullet Physics(this is the API reference) and i have been looking at the different functions and classes. then i noticed that there are demos included in the lbrary, so whi...
Not sure if this is what you're after, but this is my setup code for basic rigid body physics: #include "btBulletDynamicsCommon.h" ... m_pBroadphase = new btDbvtBroadphase(); m_pCollisionConfig = new btDefaultCollisionConfiguration(); m_pCollisionDispatcher = new btCollisionDispatcher(m_pCollisionConfig); m_pSolver =...
5,559,525
5,559,932
would the pointer returned by new(size, value) Type[0] be legal and could it be used to build an array?
The standard says, in 5.3.4[expr.new]/7 When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements. and in 3.7.3.1[basic.stc.dynamic.allocation]/2 The effect of dereferencing a pointer returned as a request for zero size is undefined. ...
There's an irritating logic problem in your code: The new expression: T* a = new(100, T(7)) T[0]; Calls T's deleted default constructor [expr.new]/17. ;-( std::vector<T> is sure looking good about now... :-)
5,559,566
5,559,592
static variable position of singleton
I have a question with singlton. Where should I declare the static member of the singleton class? why not working like this class singleton{ private: static singleton & m_singleton; public: static singleton& get_instance{ return m_singleton; } } but I have to be like this class singleton{ ...
In the first case, the singleton is constructed (constructor called) when the program initializes, before main() is called. In this case you will also need to define the static variable somewhere in your cpp file. In the second case the singleton is constructed when the function is first called. Mind you that this impl...
5,559,795
5,560,036
Save file to location and name defined by user input in C++
I am having some issues saving a text file that is created in a console window to a custom location that is defined by a user's input. I want it to take string filepath which would be the save location and combine it with the string filename which would be the name of the text file which the user chose. Such as this C:...
In true c++ spirit #include <iostream> #include <fstream> #include <string> int main() { std::string filename, filepath, data; std::cout << "Please enter a name for your file: " << std::endl; std::cin >> filename; std::cout <<" Please enter a directory to save your file in: " << std::endl; std::c...
5,560,050
5,560,574
Do inline functions make it harder to reverse-engineer the compiled binary?
So basically, besides possible performance effects, does inlining functions have any considerable effect on how difficult it is to reverse-engineer the program from its compiled and linked binary? I mean, it should be, since 1) the cracker just sees more machine instructions, instead of nice understandable "call XXXXX"...
The choice to inline methods or not should not be based on how easy it is to reverse engineer. The difference between inlining and not will be negligible. The exception is if you have any anti-piracy code, inlining that, or even using macros to ensure it's "inlined" can help remove a single point of failure. If you're...
5,560,173
23,958,819
Xlib Fatal IO Error: 11 (resource temporarily unavailable) caused by not using XCloseDisplay()
I'm using X11 and when I run my program the window displays fine, but when I quit the following error is outputted in the console: XIO: fatal IO error 11 (Resource temporarily unavailable) on X server ":0.0" after 58 requests (58 known processed) with 0 events remaining. I have looked in the documentation but I ca...
The error is because I quit the application without closing the display using XCloseDisplay().
5,560,279
5,560,388
C++ 64 bits - could not read symbols: Archive has no index; run ranlib to add one
I am trying to generate a very simple binary on Linux RHAS 5.3 64bits using a static library. test1.cpp, whom resulting .o will be embedded in a static library. void ctest1(int *i) { *i=5; } and prog.cpp #include <stdio.h> void ctest1(int *); int main() { int x; ctest1(&x); printf("Valx=%d\n",x); retu...
Did you delete the library before recompiling with the 64-bit build? Your compilation sequence worked for me: $ g++ -m64 -Wall -c prog.cpp $ g++ -m64 -Wall -c test1.cpp $ ar -cvq libtest.a test1.o a - test1.o $ g++ -m64 -Wall -o prog1 prog.o libtest.a $ file test1.o prog.o test1.o: ELF 64-bit LSB relocatable, AMD x86-6...
5,560,363
5,560,395
c++ template constructor initialization
template<class T> class Node { public: Node(Node<T>* next=NULL, T data=T()) : _next(next), _data(data) { } Node<T>* _next; T _data; }; I'm new to c++ template. For default parameters, is T data = T() the standard way to do it? Maybe T data = 0 is ok too?
That's not "constructor initialization", that's a default parameter. It allows the caller to provide fewer arguments than the function has, the unspecified arguments will take on the default value. Another way to do it would be: template<class T> class Node { public: Node(Node<T>* next, T data) : m_next(next),...
5,560,464
5,560,497
Writing the implementation for an operator method
So I have a LongInt class that will have new definition for the + and * operators. The initialization in the header file looks like: friend LongInt operator+(const LongInt& x, const LongInt& y); friend LongInt operator*(const LongInt& x, const LongInt& y); however in my implementation file, where I'm defining the met...
The friend keyword is only used when declaring or defining the operator inside of a class; when declaring the operator as a friend inside of the class and defining it elsewhere, friend is only used on the declaration, not the definition. Also, functions declared as friend inside a class are in fact free functions in na...
5,560,541
5,560,559
typedef to template type
What's wrong with the following? typedef boost::shared_ptr SharedPtr; GCC gives the following error: ISO C++ forbids declaration of ‘shared_ptr’ with no type
C++ doesn't (yet) have "template typedefs" where you can "rename" a template like this. This is a feature being added in C++0x, where such a "typedef" is called an "alias template." The simplest workaround that works today is to use a class template with a nested typedef: template <typename T> struct SharedPtr { t...
5,560,573
5,560,592
std::map one key, two values
What is the best way to map two values to one key? ie An item with a value and bool. Tried using: std::map<std::string, std::pair<std::string, bool> > myMap2 But that doesn't seem like the correct solution. Is there a more elegant way to do this?
That is indeed the correct solution. More generally, consider using std::tuple instead of std::pair for a uniform interface regardless of the number of values (as std::pair is obviously restricted to two), or boost::tuple if your compiler is too old to ship with a std:: or std::tr1:: implementation.
5,560,787
5,560,810
Making a long function inline
Suppose I have a 10 line function. If I add inline keyword, let's say there is a chance of 50% that compiler will make it inline. If I have a 2 line function, there might be 90% chance it will be inlined. Can I split the code in 10 line function into 5 functions to make it inlined with better chances?
There may be a reason why the compiler isn't inlining it, possibly something to look at. In addition, the function call overhead becomes less of an issue with longer functions, so inlining them may not be as important (if that's your only reason). Splitting the function into 5 small functions will just make a mess of y...
5,560,949
5,560,971
Adding and removing large amounts of data with std::vector
Possible Duplicate: How to downsize std::vector? It seems that std::vector will not release memory even I call pop_back(), clear() or resize(). Is there any good way to deal with this? For example, in the following code: #include<vector>    using namespace std;    int main(){ int i, j; vector<int> v[10000]; fo...
std::vector grows but never shrinks. The reason is that growing is expensive, so if you shrink and then grow back it's a waste of performance. If you really want to shrink a large vector use the swap idiom: std::vector<T> vec; // push push push ... std::vector<T>(vec).swap(vec); This doesn't guarantee the new size of ...
5,561,036
5,562,161
Adding two lists of characters
In this problem, the user enters in two numbers. Each number represents an integer, whose characters are stored into a list. I need to modify the + operator, so that the program will take the two list characters, change them to ints, add them, and then change it back to a char list. Its confusing I know, but hopeful...
If you want to convert the list of chars to an int, you can do something like this: std::list<char> digits; int value = 0; for(std::list<char>::iterator it = digits.begin(); it != digits.end(); ++it) { value = value * 10 + *it - '0'; }
5,561,071
5,561,125
C/C++/Java question: will the expression used in for loop evaluate multiple times?
for example,we have code like this: for (i = 0; i < function(); ++i ) { // loop body; } will the function() be evaluated for each loop?
It depends. In most cases, the function will be called mutiple times. However: In C++, if it's a very simple function and make 'inline', then it's possible that there's no function call there indeed. And in Java, if it's simple as well, JIT of VM may optimize it to reduce the unnecessary calls.
5,561,138
5,561,157
Interview Question : Trim multiple consecutive spaces from a string
This is an interview question Looking for best optimal solution to trim multiple spaces from a string. This operation should be in-place operation. input = "I Like StackOverflow a lot" output = "I Like StackOverflow a lot" String functions are not allowed, as this is an interview question. Looking for an a...
Keep two indices: The next available spot to put a letter in (say, i), and the current index you're examining (say, j). Just loop over all the characters with j, and whenever you see a letter, copy it to index i, then increment i. If you see a space that was not preceded by a space, also copy the space. I think this wo...