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,975,224
5,975,336
MFC Save file dialog
I am writing an MFC C++ application that has a Save As button for saving a .txt file to the disc. With it I am trying to add an extra verification for file overwriting (if a file with the same filename exists, then it should query the user if he wants to overwrite the old file or not). I have tried this with the below ...
CFileDialog can detect itself if a file exists and prompt the user for overwriting. explicit CFileDialog( BOOL bOpenFileDialog, LPCTSTR lpszDefExt = NULL, LPCTSTR lpszFileName = NULL, DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, LPCTSTR lpszFilter = NULL, CWnd* pParentWnd = NULL, DWORD d...
5,975,421
5,975,568
Does "friend"ing a class extend to classes declared within that class?
I have the following code where class A declares class B as friend. Should class C, declared within class B, be able to view private declarations/members of class A? It compiles without error with CL version 16 (Visual Studio 2010), but gcc g++ version 4.1.1 gives the error "typedef int A::T is private within this cont...
From standard docs., $11.4.2 Declaring a class to be a friend implies that the names of private and protected members from the class granting friendship can be accessed in the base-specifier s and member declarations of the befriended class. An example from the standard docs., themselves, class A { class B { }; fri...
5,975,566
5,976,769
Why does not g++ or clang elicit a warning when truncating a non-const variable by assigning it to a variable of smaller type?
Both clang 2.9 and g++ 4.1.2 will generate a warning when the variable x is declared constant in the code snippet below. However when const is removed, as it has been in the snippet, neither of the compilers generates a warning even when executed with the following parameters which are the strictest I know: "-Wall -Wex...
For GCC, add the flag -Wconversion and you will get the desired warning. It's not a part of -Wall since so much code just ignores these types of things. I always have it turned on since it finds otherwise hard to debug defects.
5,975,677
5,975,799
What is the best log file format?
We are developing a database tool and we'd like to write a log file in a format which is extendable and easy to be imported into a database table. We all feel that filtering this info by using SQL is a good idea, since the log will be a long file and "search" may not be good enough. Could you give me some suggestions? ...
The first thing I would say is that your file format ought to be human readable. My reasons are given here: Why should I use a human readable file format. Beyond that, it is impossible to answer with such a vague question. However, here are some of the issues you should consider: How big does this log file grow? How d...
5,975,736
5,976,062
C++ ADL in nested namespaces with template function
I have a question regarding the standard ADL resolution in C++. Here is a sample code explaining my enquiry: #include <string> // The mechanism: namespace A { template< class C > ::std::string scope(const C*) { return "A"; } namespace B { template< class C > ::std::string scope(const C *foo) { return A::s...
According to the standard, ADL works (modulo a couple of special rules) "as if" the function name were preceded by the namespace; in your last line, lookup should precede as if you'd written A::B::scope. Which does not look in the surrounding namespaces. Note that even within namespace A::B, there would be no ambiguit...
5,976,075
5,976,418
overloading operators == and != : compiler moans ambiguity
I have the following code: bool operator==(const Inc::CReminderItem& Item1, const Inc::CReminderItem& Item2) { bool bDate = false, bDesc = false, bInfo = false, bWeekday = false; if(Item1.m_Date == Item2.m_Date) bDate = true; if(Item1.m_strDescription == Item2.m_strDescription) bDesc = true...
First, if it is "ambiguous", I would expect other operator== to be present somewhere. But it's hard to say what any particular compiler is really trying to tell you with it's error messages. Second, you really don't show enough code for anyone to say what is wrong. There are a number of possible errors: the class whe...
5,976,277
6,013,428
Changing syslog log path
How do I change the log path of syslog daemon during runtime? My goal is to rotate log file every filesize or date, but I don't have logrotate in QNX/POSIX. Do I just do an edit and hope that the syslogd checks the .conf file everytime, or is there any other workaround? Thanks. Clarification: It has to be done in C or...
Answer based on some solution found on web, and also based on @bills answer, modified to suit QNX environment. Perform a system call for slay syslogd and perform edit to syslog.conf and system call to syslogd again. QNX does not supply logrotate, otherwise other than the above answer, install third party logging is a...
5,976,350
5,976,693
Creating iterative string
is there a better / faster way to create string (std or (const) char *) created from string (const char *) and number (int), like animation0, animation1, animation2 ... animation99 than this? NOTE : doesnt have to use std, because hasValueForKey accepts const char * std::stringstream strIter("animation0"); int i = 0...
well you could use the C99 API with snprintf(char *str, size_t size, const char *format, ...);: int i = 0; char str[50]; while (hasValueForKey(str)) { // do some stuff ++i; snprintf(str, 50, "animation%d", i); }
5,976,525
5,976,589
How to deal with the idea of "many small functions" for classes, without passing lots of parameters?
Over time I have come to appreciate the mindset of many small functions ,and I really do like it a lot, but I'm having a hard time losing my shyness to apply it to classes, especially ones with more than a handful of nonpublic member variables. Every additional helper function clutters up the interface, since often the...
Every additional helper function clutters up the interface A private helper function doesn't. I usually create a helper class which becomes the friend of the class that needs to be operated on Don't do this unless it's absolutely unavoidable. You might want to break up your class's data into smaller nested classes ...
5,976,879
5,976,946
Getting the size of member variable
If there is a POD structure, with some member variables, for example like this: struct foo { short a; int b; char c[50]; // ... }; Is there a way to get the size of a member variable in bytes, without creating an object of this type? I know that this will work: foo fooObj; std::cout << sizeof( fooObj.a ) <...
5.3.3/1: The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is not evaluated, or a parenthesized type-id. The above means the following construct is well defined: sizeof( ((foo *) 0)->a);
5,977,169
5,977,353
Using arrays to loop through starting multiple threads, pass different parameters, and return handles for WaitForMultipleObjects
I want to test out using WaitForMultipleObjects, and to do so I want to start multiple threads, using a loop, each passing different ThreadArgs. (Essentially just an array of five ThreadArgs, and five HANDLEs?) When I try to create an array of either the struct, or the HANDLE, neither will work and I get the error 'ca...
You need to use WaitForMultipleObjects and pass it an array of handles to wait for multiple threads to complete. See an example here. #include <windows.h> #include <iostream> #include <vector> using std::vector; using std::cout; using std::endl; CRITICAL_SECTION cs; struct ThreadArgs { int id; }; VOID MyThread(...
5,977,378
5,993,115
boost::factory creating boost::enable_shared_from_this class
I have multiple class derivated from A class A : public boost::enable_shared_from_this<A> { public: typedef boost::shared_ptr<A> pointer; static pointer create(tcp::socket& socket) { return pointer(new A(socket)); } private: A(&tcp::socket socket) : m_socket(socke...
If anyone goes into the same mistake, Here the answer. It does not need boost::factory to work, using boost::function directly is enough. so class MyFactory { public: static MyFactory* getInstance(); typedef boost::function< A(tcp::socket) > a_fact; private: MyFactory() { m...
5,977,432
5,978,155
Inline assembly troubles
I tried to compile with GCC inline assembly code which compiled fine with MSVC, but got the following errors for basic operations: // var is a template variable in a C++ function __asm__ { mov edx, var //error: Register name not specified for %edx push ebx //error: Register name not specified for %ebx sub e...
g++ inline assembler is much more flexible than MSVC, and much more complicated. It treats an asm directive as a pseudo-instruction, which has to be described in the language of the code generator. Here is a working sample from my own code (for MinGW, not Mac): // int BNASM_Add (DWORD* result, DWORD* a, int len) // // ...
5,977,515
5,977,538
C++ OOP quiz question
I'm doing a C++ quiz and I need to say whats wrong in the following code: class Base { friend class SubClass; int n; virtual int getN() { return n; } }; class SubClass: public Base { public: SubClass() {} SubClass(const SubClass& s) {} }; int main() { SubClass sc; if(sc.get...
As by default every member of a class1 is private, getN in the base class is declared private. Make getN public as: class Base { friend class SubClass; int n; public: //<--------------------- you forgot this virtual int getN() { return n; } }; 1. I mean, a class defined with the keyword cl...
5,977,542
7,663,879
Eclipse CDT: Unresolved inclusion of stl header
I'm trying to use Eclipse to edit sources, compiled under C++ Builder, but stuck with Unresolved inclusion problem. For example, code like: #include <vector> Gives Unresolved inclusion: <vector> error in Eclipse IDE. C++ Builder indeed has no vector file, instead it has vector.h which is used by compiler. Eclipse IDE ...
This allowed me to avoid Eclipse "Unresolved inclusion" error. In my case I had to find the location of the C++ vector header on my computer (which is a Mac): find /usr/local -name vector -print I found the correct include location in folder "/usr/include/c++/4.2.1". Then I set my project eclipse settings like so: Pr...
5,977,591
5,977,666
Opening a file with a certain program changes that programs working directory?
I have a file saved to my desktop, when I open it with my program the working directory changes to the desktop, this means my program can not load in some files it needs as it searches for these in the working directory. Is there a way I can stop the working directory from changing like this?
You can just save your working directory at startup and use absolute paths. In fact, it's better to always open files with absolute paths, unless you really want to rely on the current working directory.
5,977,948
5,977,983
C/C++: How does this inline if get parsed?
Consider this code: int main() { cout << true ? "Yes" : "No"; return 0; } Its output will be 1 , not Yes or No. Why is it that true is sent to the output stream instead of the Yes or No strings? How does the rest of the inline if get parsed?
It has to do with order of operations. It's the same as: (cout << true) ? "Yes" : "No"; cout << true returns an ostream&, which must have a conversion to bool or an equivalent. The result of ?: is thrown away. If this seems odd (why this precedence?), just remember that ostream's operator<< is an overload introduc...
5,978,217
5,978,406
Packet Delay Variation (PDV)
I am currently implementing video streaming application where the goal is to utilize as much as possible gigabit ethernet bandwidth Application protocol is built over tcp/ip Network library is using asynchronous iocp mechanism Only streaming over LAN is needed No need for packets to go through routers This simplifies...
For video streaming, I would recommend using UDP instead of TCP, as it has less overhead and packet confirmation is usually not needed, as the retransmited data would already be obsolete.
5,978,287
5,978,534
c++ OpenGL display problem for gluLookAt
I have been trying to solve this program: Program to draw a color cube and allow the user to move the camera suitably to experiment with perspective viewing. Also the cube should rotate. I have completed the coding and here it is. It seems to work fine except for 1 simple problem: //Program to draw a color cube and a...
There are two mistakes in your program: You're treating OpenGL like a scene graph with persistency – however OpenGL just draws pictures. You apply viewpoint transformation to the projection matrix. Both is fundamentally wrong. Here's a corrected version of your code: //Program to draw a color cube and allow the user...
5,978,617
5,984,323
Why is it disallowed for partial specialization in a non-type argument to use nested template parameters
I have this code template<int N, bool C = true> struct A; template<int N> struct A<N, !(N % 5)> { /* ... */ }; // should work A<25> a; That is, for numbers N that are divisible by 5, the compiler should use the partial specialization. But the compiler won't accept that partial specialization, because the Standard ...
I think a lot of it is historical. Non-type template parameters weren't originally allowed at all. When they were added, there were lots of limitations. As people tried different possibilities, and confirmed that they didn't cause problems, some of the limitations were removed. Some of those original limitations remain...
5,978,811
5,978,857
Understanding the Boost MultiArray parameters
This is from the Boost docs and compiles without problems. #include "boost/multi_array.hpp" int main () { // Create a 3D array that is 3 x 4 x 2 typedef boost::multi_array<double,3> array_type; typedef array_type::index index; array_type A(boost::extents[3][4][2]); return 0; } My question is: What...
It's how many dimensions you need. boost::extents[3][4][2] // we use 3 dimensions So if you change this number, you'll have to change this line to.
5,978,815
5,978,876
Casting: What is the difference btw. T(value) and (T)value for built-in types?
Possible Duplicates: C++ cast syntax styles What is the difference between (type)value and type(value) ? In C++, when explicitly converting one built-in type to another, you can write: int x = (int)c; int x = int(c); int d = (double)f; int d = double(f); I known that (T)v is a C-style cast, and I think the other sy...
T(value) is actually an initialization of the type T, and because it's an initialization, an implicit type conversion can take place if the type of value and T are convertible. If T is a class-object, then one of it's constructors is called, either a default constructor that takes a single value and T and value are imp...
5,978,981
5,979,109
C++ Namespace versioning
In C++ its possible to do the following for namespace versioning First version: namespace A__v1 { class X ... class Y ... class Z ... } namespace A = A__v1 Second version (where the X class is changed): namespace A__v1 { class X ... class Y ... class Z ... } namespace A__v2 { class X ... using A__v1::Y...
I actually like the non-macro way of handling this, it allows one build of the library to serve many versions. This will inevitably increase library size (due to more versions of some classes all being present) but there is one caveat though: the compiler will most likely report the full namespace qualification of the ...
5,979,121
5,979,198
Using std::tm as Key in std::map
I'd like to use std::tm () as the key for an std::map-container. But when I try to compile it, I get a lot(10) of errors. For example: 1. error C2784: 'bool std::operator <(const std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem *)' : could not deduce template argument for 'const std::basic_string<_Elem,...
std::map uses a comparer to check if the key already exists or not. So when you use std::tm , you've to provide a comparer as third argument as well. template < class Key, class T, class Compare = less<Key>, class Allocator = allocator<pair<const Key,T> > > class map So a solution would be functor (as you a...
5,979,279
5,979,316
c++ how to obtain the type of the object?
how can i obtain the typeid of the following: T& object; where T is: template<class T>. I am working in c++ code. I did test: const std::type_info& ObjT= typeid(object); std::cout<<"******the objT is: "<<&ObjT<<std::endl; But it crashes. Why?
did you include: #include <typeinfo> and perhaps you should send std::cout << typeid(object).name() << std::endl; And perhaps there is a problem in the fact that you are doing && on the object. look at the example here
5,979,482
5,980,147
convert VARIANT to unsigned char array
I'm using Comm32 (an activeX control) to get data coming through serial port using the method GetInput(). This method returns a _variant_t, so I need to convert it to an array of unsigned char's. When serial port is configured to TextMode (this is data input is interpreted as String), converting the Variant to a BSTR a...
The InputMode property determines the type of data that is retrieved with the Input property. If InputMode is set to comInputModeText then the Input property returns text data in a Variant. If InputMode is comInputModeBinary then the Input property returns binary data in an array of bytes in a Variant. (from msdn) To u...
5,979,606
5,979,645
C++ -- what is operator .*?
In C++, you cannot overload operator .* Can someone give me an example for the usage of operator .*?
This is a pointer to member operator.
5,979,719
5,980,451
Cannot access Qt object methods through javascript using QtWebkit
Using QtWebkit's javascript bridge, I have created a class to interface the data in my web frame with the rest of my Qt code. it recognises the object, but none of its methods. //executed with main window constructor void MainWindow::initJavascriptInterface(){ webInterfacer JSInterface; QWebFrame *frame = ui->...
webInterFacer JSInterface; Your webInterfacer object is a local variable.It is destroyed as soon as it is out of scope ie, once you exit the function initJavaScriptInterface(); Fix void MainWindow::initJavascriptInterface(){ webInterfacer* JSInterface = new webInterfacer(); QWebFrame *frame = ui->webView->page()->main...
5,979,723
5,980,461
Do templates actually have to be compile-time constructs?
Does the C++ Standard actually mandate that templates must be instantiated at compile-time, not run-time? If not, is it a convention that we use purely because it obviously makes sense to do it that way? Or is there some practical reason that would, theoretically, prevent an implementation from existing that can instan...
All the standard requires is that the observable behavior be as if the templates were instantiated before the program started to run. Any errors, for example, would have to trigger a message in some phase of the compilation, or at least before runtime. In theory, a compiler could probably defer full instantiation unt...
5,979,809
6,041,402
unixODBC C++ documentation...?
I cannot find any. All I found is this: http://libodbcxx.sourceforge.net/ but this is not the right documentation for me. I got a UnixODBC library for C++, and cannot find any docs I have this in the headers: /*! * \file * * \author Peter Harvey * \author \sa AUTHORS file * \version 2 * \date 2007 * \licen...
There is NO such documentation. I contacted Peter Harvey, he advised (what I thought at the beginning) just to watch what his wrapper does in each function and watch the documentation for unixODBC - the C version. The other option is to rewrite the software, using the sourceforge wrapper, as it seems to be well-docume...
5,979,866
5,980,124
Unhandled exception / Access violation writing location in a Mutex example
I'm working through an example of protecting a global double using mutexes, however I get the error - Unhandled exception at 0x77b6308e in Lab7.exe: 0xC0000005: Access violation writing location 0x00000068. I assume this is related to accessing score? (The global double) #include <windows.h> #include <iostream> ...
The remaining bug in your code is in the call to WaitForMultipleObjects(). You set the 3rd parameter to 0 (FALSE) such that the main thread unblocks as soon as any of the 10 threads finishes. This causes the call to DeleteCriticalSection() to execute before all threads are finished, creating an access violation when o...
5,979,911
5,979,936
How to check whether a function in dll/lib is extern "C" in windows?
For example ObReferenceObjectByName is defined in c, so in c++ should use extern "C" But how can I check this directly in the dll/lib instead of reading docs?
You can look at the export in Dependency Walker. Open the DLL, find the function in the middle right pane, and look at the icon. It will be C, C++, or O# (exported by ordinal only) For more information, see Export Function List View in the help file.
5,980,249
5,980,283
A easy question of assignment function of class
I write a class struct opera{ int a,b; int op; opera(int a1=0,int b1=0,int op1=-1):a(a1),b(b1),op(op1){} opera& operator=(opera& tmp){ a=tmp.a; b=tmp.b; op=tmp.op; } And I want to assign it to an array element like this: ans[a][b]= opera(t.a,t.b,i); Why it can't compile successfully. However th...
When you want to assign from a temporary, you need   opera& operator=(opera const& tmp){ The other line opera tmp=opera(t.a,t.b,i); is an initialization of a new object, and not an assignment.
5,980,397
5,980,523
Multiplatform C++ cross-compiler
How can I build a cross-compiler for a C++ library to target many platforms on a single build server? The cross-compiler should be able to build the library for (at least) {Windows 7, Mac OS X, Ubuntu 11.04} × {32 bit, 64 bit} × {Debug, Release}. I don't care if the whole build from scratch takes forever or if the gcc ...
Building cross-compiler is quite well covered in OSDev Wiki. For Windows, you can use mingw packages in your distro's repository
5,980,483
5,981,800
how to send string data into a javascript?
I am using v8 and i faced next problem - i have an application which running a javascript file ( i simply read it into a string and than execute with Local<String> source = String::New(javascript); //javascript is string with js file Local<Script> script = Script::Compile(source); Local<Value> result = script->Run(); ...
Put a placeholder in the script source, like STRING_HERE. Then, before creating the source object, find that placeholder in the string and replace it with the string value you want.
5,980,500
5,980,782
Recording sound sent to speakers
I'm trying to make a program which allows me to capture every sound which I can hear through my speakers. I don't have any idea how I can do this... I want to send it to another PC using sockets (how can I do this?). I want to write it in Java or C++ (I definitely prefer Java) on Windows. Edit Inshort, I want to send...
For Windows 7 you can do this using WASAPI (see my answer to a similar question here). In order to use WASAPI I would recommend to use either C++ or some .net based language (C#, vb.net, etc) For other versions of Windows, you will need an intermediate virtual sound card, and you will only be able to capure the audio s...
5,980,520
5,980,549
Define static method in source-file with declaration in header-file in C++
I am having a little trouble working with static methods in C++ Example .h: class IC_Utility { public: IC_Utility(); ~IC_Utility(); std::string CP_PStringToString( const unsigned char *outString ); void CP_StringToPString( std::string& inString, unsigned char *outString, short inMaxLength ); static...
Remove static keyword in method definition. Keep it just in your class definition. static keyword placed in .cpp file means that a certain function has a static linkage, ie. it is accessible only from other functions in the same file.
5,980,674
5,980,731
Does something happen different in the compiler between these two ways of including the same headers?
Does: #include <vector> #include <string> #include <winsock2.h> #include <iphlpapi.h> #include "FileX.h" <--------------which #include <windows.h> Compile the same as in one header file: #include <vector> #include <string> #include <winsock2.h> #include <iphlpapi.h> #include <windows.h> In the first case, the w...
In my world, "FileX.h" is defined as follows #error "This is different from windows.h, as it contains an #error!" #include <windows.h> So yes, there "Does something happen different in the compiler" in this case. Even if it is simply defined as follows, things may be different #include <windows.h> If you include too...
5,980,676
5,980,821
Algorithmically generating a drop shadow?
For my game, I need to be able to generate drop shadows. The kind that only span the bottom right. Like this (neglect the blue square): Given a 2D array of RGBA pixels, how could I generate a drop shadow bitmap? Thanks
This is done by a Gausian blur of a black square. It also can be done with every other shape.
5,980,702
5,981,291
Design approach for interface with many input widgets
I have an interface that has ~16 input field boxes. They are all declared as public pointers within a class, initialized, etc. However, as my code has grown more and more with private functions doing database committals, error checking, temporary storage routines, etc it has become very painful if a field has to get ...
You could possible add a container of InputBox as a member to Foo and iterate it to make life simpler. #include <vector> class Foo { private: static void clearFieldsFunc1(void * v); // callback bound to a button static void loadFieldFunc2(void * v); // callback bound to a button void ...
5,980,809
5,995,782
MapViewOfFile freezes the Windows Mobile 6 device
I have a Visual Studio 2008 C++ project for Windows Mobile 6 ARMV4I where I'm using memory mapped files. Unfortunately, it causes the device to lock up. I can demonstrate the issue with this code: #include <list> #include <algorithm> int _tmain(int argc, _TCHAR* argv[]) { DWORD alloc_size = 256; DWORD alloc_m...
I spoke with somebody that has access to the sources. As it turns out, MapViewOfFile uses an internal reference counter that is a USHORT. So, on the 65535th iteration, it overflowed and caused hate and discontent all over the place eventually halting the system. So, there is an undocumented limit of 65535 open views in...
5,980,919
5,980,945
Renaming a class in C++
I have a class that I would like to reference in my header file, which is in a long chain of nested namespaces: MySpaceA::MySpaceB::MySpaceC::MySpaceD::MyVeryLongNamedClass. I would like to use it under a different name, but not MyVeryLongNamedClass -- something shorter and more useful, like MyClass. I could put using ...
typedef MySpaceA::MySpaceB::MySpaceC::MySpaceD::MyVeryLongNamedClass MyClass; For templates, you could use a template typedef: template <typename T> struct MyClass { typedef MySpaceA::MySpaceB::MySpaceC::MySpaceD::MyVeryLongNamedClass<T> type; }; Now you can refer to MyClass<T>::type instead of MySpaceA::MySpaceB::...
5,981,172
5,981,275
Some floating point precision and numeric limits question
I know that there are tons of questions like this one, but I couldn't find my answers. Please read before voting to close (: According to PC ASM: The numeric coprocessor has eight floating point registers. Each register holds 80 bits of data. Floating point numbers are always stored as 80-bit extended precision nu...
1) sizeof is the size in memory, not in a register. sizeof is in bytes, so 8 bytes = 64 bits. When doubles are calculated in memory (on this architecture), they get an extra 16 bits for more precise intermediate calculations. When the value is copied back to memory, the extra 16 bits are lost. 2) Why do you think lo...
5,981,306
5,981,446
Where can I find the source code for GNU stdc++ operator new?
I tried here: http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/index.html and I found new.h but not the code to implement it. Thanks
The relevant source code for libstdc++ can be browsed online here. You probably want to read this.
5,981,694
5,981,716
assigning values to pointers
If a have an array of pointers to an object, which way of filling the array is cleaner, (1) or (2), in the code segment below? Are string ** list = new string*[5]; string* s = new string("foo"); *list[0] = *s; //(1) list[0] = s; //(2)
The first method will result in undefined behaviour. list[0] doesn't point at a valid string object, so dereferencing it and assigning to it will be bad. The second method looks ok to me (in the sense that it won't have undefined behaviour), but I guess it depends on how you go on to use it.
5,981,947
5,982,151
C++: Boost: how do I check the existence of a folder inside another folder in my working directory?
code: boost::filesystem::path config_folder(Config::CONFIG_FOLDER_NAME); if( !(boost::filesystem::exists(config_folder))) { std::cout << "Network Config Directory not found...\n"; std::cout << "Creating folder called " << Config::CONFIG_FOLDER_NAME << "\n"; boost::filesystem::create_directory(config_folder...
The / operator is overloaded to concatenate path objects. No need for explicit string formatting, and no need to worry about the platform-specific path-separator character, either. if(!(boost::filesystem::exists(config_folder / Config::fmap[Config::current_hash_function])); Either operand can be a std::string as long ...
5,982,087
5,986,185
Reference problem (I guess) when using boost::asio
I am building an HTTP client based on the example on HTTP server given at boost website. Now, the difference between that code and mine is that the example uses the server constructor to start the asynchronous operations. This makes sense since a server is supposed to listen all the time. In my client, on the other han...
If you don't expect to have some work at all times, to keep the io_service busy, you should construct an io_service::work object in some scope which can be exited without io_service::run() having to return first. If you're running the io_service in a separate thread, I would imagine you wouldn't have a problem with tha...
5,982,094
5,982,248
fork and exec many different processes, and obtain results from each one
I have managed to fork and exec a different program from within my app. I'm currently working on how to wait until the process called from exec returns a result through a pipe or stdout. However, can I have a group of processes using a single fork, or do I have to fork many times and call the same program again? Can I ...
One Fork syscall make only one new process (one PID). You should organize some data structures (e.g. array of pids, array of parent's ends of pipes, etc), do 8 fork from main program (every child will do exec) and then wait for childs. After each fork() it will return you a PID of child. You can store this pid and asso...
5,982,421
5,982,462
Class Instantiation Inside Member Function
Is is safe to instantiate a class inside a member function of that class? For example, let's say I have class CMyClass with member function CMyClass::MemberFunc, and I want to create another instance of CMyClass inside of CMyClass::MemberFunc. void CMyClass::MemberFunc( void ) { CMyClass * pMyClass = new CMyClass(...
This isn't more or less safe than instantiating any other object. Note that in your example at the bottom, the recursion is strictly based on the fact that the method calls itself; it would recurse indefinitely regardless. In sum: you should be fine.
5,982,452
5,982,963
Passing an array by pointer
How do i get the size of array in void Func(int (*a)[5]) for loop condition and print elements? void Func(int (*a)[5]) { for (int i = 0; i < 5; i++) cout << a[i]; // doesn't work } int main() { int a[] = {1, 2, 3, 4, 5}; Func(&a); }
Firstly, the way you access the array is wrong. Inside your function you have a pointer to an array. The pointer has to be dereferenced first, before you use the [] operator on it void Func(int (*a)[5]) { for (int i = 0; i < 5; i++) cout << (*a)[i]; } Secondly, i don't understand why you need to "get" the siz...
5,982,578
5,985,194
Time Complexity of std::multimap::equal_range
Good afternoon, I am wondering what the time complexity of std::multimap::equal_range is? Is it Big-O(n) or BIG-0(log n). I remember reading that the time complexity of std::multimap::erase "is logarithmic plus linear time for the length of the sequence being removed." <http://frank.mtsu.edu/~csjudy/STL/Multimap.html>
C++03 standard, Table 69 ("Associative container requirements") in 23.1.2 says that equal_range has logarithmic complexity.
5,982,727
5,996,959
regex: boost::xpressive vs boost::regex
I wanted to do some regular expressions in C++ so I looked on the interwebz (yes, I am an beginner/intermediate with C++) and found this SO answer. I really don't know what to choose between boost::regex and boost::xpressive. What are the pros/cons? I also read that boost::xpressive opposed to boost::regex is a header-...
Well if you need to create a regular expression at runtime (i.e. Letting the user type in a regular expression to search for) you can't use xpressive as it is compile time only. On the other hand, since it is a compile-time construct, it should benefit more from your optimizer than regex does. I do enough stuff with Bo...
5,982,747
5,982,854
Change NetBeans Debugger Command
I have a .gdbinit file to set the solib-absolute-prefix and solib-search-path when attaching a debugger from NetBeans. I've turned on the debugger console (by adding -J-Dgdb.console.window=true to netbeans_default_options in /usr/share/netbeans/6.9/etc/netbeans.conf) and it tells me: Debugger Command: [/path/to/gdb, -n...
Never mind, you can add -J-Dgdb.init.enable=trueto netbeans_default_options in /usr/share/netbeans/6.9/etc/netbeans.conf and it will load the .gdbinit file.
5,982,835
5,982,913
Class member attributes error
I have two classes and want to have a reference from class Kunde to class Konto and backward, but my compiler shows many errors. I don't know what the problem is. Please help me. Class Konto: #pragma once #include "Kunde.h" class Konto { private: Kunde* kunde; protected: int kontonummer; double stand; publ...
You have a circular inclusion problem. You see the #pragma once statement in the first line of the header file? This prevents an inclusion of the header if it has already been included. Since your header files include each other, at the declaration of either Kunde or Konto the other one has not yet been defined. You ca...
5,983,136
5,983,164
What is being printed? C++ pointer to an integer
So I have the following (very simple) code: int* pInt = new int(32); std::cout<< pInt << std::endl; //statement A std::cout<< *pInt << std::endl; //statement B std::cout << &pInt << std::endl; //statement C So here's what I think I am doing (I have learned that in C++ I am rarely ever doing what I think I am doing):...
Your second statement is wrong. You allocate a new int off the heap. The compile-time constant "32" does not have an address, and therefore you cannot take it. You create an int whose value is 32. This is not the same thing. int* pInt1 = new int(32); int* pInt2 = new int(32); pInt1 and pInt2 are not equal. Oh, one las...
5,983,218
8,155,970
Explicitly instantiating a class template with a list of parameters
I am trying to instantiate a class template with a whole bunch of different combinations of template parameters which will be decided by some runtime information: https://github.com/ITKTools/ITKTools/blob/newpixeltypeselector/src/binarythinning/binarythinning.cxx . This system works fine (lines 169 - 190), but it is qu...
I guess the consensus is "use Boost."
5,983,587
5,983,682
Having problem passing member function pointers to templatized member function on gcc
I'm having problem passing member function pointers to templatized member function on gcc. Does anyone know how to modify the code below to get gcc to accept what I am trying to do? class Foo { public: template <class C, class R> void Execute(R(typename C::*memFn)()) { } }; I get the following errors ...
You don't need typename. Remove that and it should work. (I tested it on gcc 4.3.2).
5,983,949
5,986,355
Time efficiency on std::tr1::unordered_map::operator[]
I am optimizing a piece of code in Visual Studio 2008 SP1. Knowing that unorder_map is awesome with constant time insert/delete/find, so I optimized the code by using unordered_map as my primary data structure. Please take a look at the following code. .... typedef std::tr1::unordered_map <__int64, int> umap_id; ...
In VS 2008 without SP1 (but with the Feature Pack that gives you the TR1 library) the default hash function for tr1::unordered_map<> only considers the lower 32 bits of the key value. At least that's by my reading of the template<class _Kty> class hash::operator() implementation in the <functional> header. The footstep...
5,984,009
5,984,047
a question in c++. just want a easy way to do this/
I have class class A { int x; int y} and set<A> myset; how can I iterate this set? I want to touch x, y variable in the class. Thank you
I want to touch x, y variable in the class. In your class x and y are private. Members of classes are private by default. You can't just set x and y directly or else you'll get a compiler error. You need to provide a way to set x and y in the A's public interface, for example: class A { int x; int y; // these are by ...
5,984,144
6,010,756
Assertion error in CRT calling _osfile() in VS 2008?
I have a C++ code base that has been working for a long time. The code base was a legacy VS 2003 set of projects that I recently migrated to VS 2008. The migration seemed to be successful in that the resulting program built, and run. I reinstalled my OS and all applications on a fresh drive, and now when I attempt to...
The issue is resolved - and unrelated to chsize. The linking model to the c-runtime libraries chosen for code generation was set to multi-threaded debug (/MTd) for the main project, but multi-threaded debug DLL (/MDd) for all of the projects in the solution that it linked to. Changing to /MDd resolved the issue. I am...
5,984,219
5,984,436
Help understanding marching squares algorithm
In my game, I want to layout squares along the edges of a monochrome image: So I found this algorithm which should solve the issue. http://en.wikipedia.org/wiki/Marching_squares It does not seem that hard to implement, I just think I do not understand exactly what Wiki is saying. I think I have to break the image up i...
After you create the 2x2 cells, for each one you compute a number like this: set the number to 0 if the top left point is above the threshold, add 8 if the top right point is above, add 4 if the lower right point is above, add 2 if the lower left point is above the threshold, add 1. Edited formatting.
5,984,320
5,984,385
C++ array contents changing in between function calls
Example code: #include <stdio.h> class compArray { public: unsigned int* myArr; //The array compArray() { unsigned int temp[4]; for (unsigned int i=0;i<4;i++) { temp[i] = 0; } myArr = temp; print_arr(myArr); } void set() { print_arr(myArr); ...
In your constructor, you have these two lines: unsigned int temp[4]; ... myArr = temp; You set your member variable pointer myArr equal to the address of your local variable temp. But, temp goes out of scope and is destroyed as soon as you return from the constructor. After that, myArr refers to storage that is no lon...
5,984,763
5,984,780
I need help choosing the right c++ container
key is :(x,y) , that means 2 integers. value is: 0 or 1. And I have frequently operation of iteration of this hash map. Which data structure is fit? I am using C++ stl or tr1. Don't consider boost.
Well, the data format stored obviously is a bool. And for the key format, if you would know the bitsize of those integers and performance is a must, I would use a associative array (called a map in C++) with twice the bitwidth integers as key: bool val = true; uint32 x, y; // key uint64 combo = x << 32 + y; std::map<u...
5,984,789
5,984,819
fstream end of file question
I am reading in multiple files. There are roughly 300 of these files. For some reason, if I set the loop to run over 3 iterations, the while loop which is supposed to iterate through each line becomes infinite. My question is: Is there somthing I am forgetting to include in my while loop? For now I am simply trying to ...
It makes no sense to check for end-of-file before you read. Try this loop contruct instead: char buffer[256]; while (inFile.getline(buffer, 100)) { cout << "HEY"; } or, better yet, std::string buffer; while (std::getline(inFile, buffer)) { cout << "HEY"; } EDIT: Fix stoopid bug in ...
5,984,807
5,993,739
Template Class Type Sizing
I have written a template class for a circular buffer: template <class T> class CRingBuffer { /* ... */ }; Some of the operations this class performs rely on an accurate evaluation of the size of T. This seems to work okay when T is BYTE (i.e. sizeof(T) == 1, check). However, when I try to use the same class where T...
Oh, this is really simple after all :) Without realising it, in pFlags->pHead += sizeof(T); you use pointer arithmetic. pHead is a pointer to T, and when you increase it by sizeof(T), it means you move it forward by that many elements of type T, and not by that many bytes as you thought. So the size of T gets squared. ...
5,984,862
5,984,917
Access the last line in console
I want to access the last line of the console independent of the others. Only the possibility to write to/read from this last line is needed. If there is a working way using the seekg and tellg function of cin/cout or any solution using the some cstdio function i wasn't able to find it. Greets
There's no way to do it with the standard library. You need an add-on package such as ncurses.
5,985,055
5,985,142
C++ Variables Scope Question
I can't understand why this works: #include <iostream> using namespace std; int main(){ signed long int count = 1; //... count++; return 0; } And yet if I move the identifier declaration (limit) to the start of the script (just after the using namespace), it fails to compile with the error "cou...
You probably have a collision between your count variable and std::count. You should not use using namespace std as this places everything from the standard library into the global namespace and names will soon collide. Use specific using lines such as using std::cin; instead.
5,985,427
5,985,457
C++ create Object accesible by . operator on heap?
this might be stupid question, but: When I moved from ASM to C (no, I am not actually that old, I just started to love programing on MCU), I LOVED the way heap memory is used. Malloc was my friend, and I quickly became familiar with pointers. BUT... Than I moved to OOP and Java. And actully, despite I don´t like Java a...
Class &c = *c_ptr; // dereference pointer https://isocpp.org/wiki/faq/references
5,985,473
5,985,775
Include static external library in QT4 application
Newish C++ programmer here. I am creating a QT4 application and it's gotten large enough to where I want to start using log4cplus. I think I'm close but qmake is still not cooperating. I am running on a Windows machine, and I compiled log4cplus as a static library under cygwin ($ ./configure --enable-static). First Que...
Assuming everything else is correct, you should change your LIBS to this: LIBS += -llog4cplus The -L flag tells g++ to set a path to look for libraries. The -l flag tells it to link a specified library (with the lib- prefix and the filetype removed). If by you mean large as in size instead of complexity when you are s...
5,985,567
5,985,603
Pointer Arithmetic? What is the difference between these three expressions?
So I am trying to understand two things: What are the differences between these three expressions? What is the equivalent to the first expression (A)? Here is the code (fixed): #include "stdafx.h" void someFunc(double** pArray, int length) { for(int i = 0; i < length; i++) { //this works perfectly ...
I think the problem is, that [] is applied before *, so in expr C you are doing *(ppDoubleArray[i]) actually the equivalent of expr B, but the expr A does (*ppDoubleArray)[i] (assuming the 1 in the expression should be an i, otherwise thats different anyway).
5,985,768
5,985,828
C++ preprocessor directive
I have a macro which defines the model number of an equipment. I am having problems determining how to compare it to a string. In a customer's specific header I have defined my macro as follows: #define FTP_MODEL_NUM CT1030 Here I want to conditionally compile a section of code depending on the model number but no...
Assuming C++'s preprocessor works the same way as C99's, what you're trying to do can't work. After FTP_MODEL_NUM == CT1031 is expanded to, e.g., CT1030 == CT1031, any identifiers remaining in the expression are replaced with 0, yielding 0 == 0, which is always true. I believe the standard way to do what you're tryin...
5,985,798
5,985,819
C++ function return reference
Why is it that I cannot/shouldn't return the reference to a local variable to a function? Is it because the temporary variable is automatically destroyed after the function finishes executing? const string & wrap(string & s1, const string & s2){ string temp; temp = s2 + s1 + s2; return temp; } What about t...
Variables declared locally inside functions are allocated on the stack. When a function returns to the caller, the space on the stack where the variable used to reside is reclaimed and no longer usable and the variables that were there no longer exist (well they do but you can't use them, and they can be overwritten at...
5,985,983
5,985,994
C++ function prototypes?
Here goes newbie question number 5, but I don't have a teacher.. so.. anyhow here we go: I'm wondering if is necessary to have function prototypes at the top of the file, instead of putting the main function to the end of the file and create all the function at the top of the file. As far as I can tell, VC++ and G++ bo...
This declares but does not define the function say_hi: void say_hi(); This both declares and defines the function say_hi: void say_hi(){ std::cout << "hi" << std::endl; } You can declare a function many times; you can only define it once. A function must be declared in the file before you can call it. A function...
5,986,070
5,986,115
Error compiling Cuda - expected primary-expression
this program seems be fine but I still getting an erro, some suggestion? Program: #include "dot.h" #include <cuda.h> #include <cuda_runtime.h> #include <stdio.h> int main(int argc, char** argv) { int *a, *b, *c; int *dev_a, *dev_b, *dev_c; int size = N * sizeof(int); cudaMalloc((void**)&dev_a, size); ...
The <<< >>> syntax for calling a kernel is not standard C or C++. Those calls must be in a file compiled by the NVCC compiler. Those files are normally named with a .cu extension. Other API calls to CUDA such as cudaMalloc can be in regular .c or .cpp files.
5,986,266
5,986,283
Exceptions vs. errno
As a C programmer, I don't have much experience with exceptions. I'm rather used to errno as a means of communicating errors across several function calls. That having said, I don't see the distinguishing feature of exceptions, so... What is the fundamental difference between exceptions and using errno?
There are so many differences here it's hard to say where to start. First of all, errno as used in C is a global variable; this means every routine that calls an errno-setting subroutine must check errno before performing any other work, if it cares about correctness. Luckily enough, errno is threadsafe. C++ exceptions...
5,986,273
5,986,303
Are C++ floats guaranteed to have infinity?
In standards compliant C++, is the following guaranteed to be true? #include <limits> std::numeric_limits<float>::has_infinity
I'm no expert, but doesn't that depend on the value of is_iec559, (Tests if a type conforms to IEC-559 / IEEE-754 standard)?
5,986,428
5,986,458
Making a JIT compiler
I've written a Brainfuck implementation (C++) that works like this: Read input brainfuck file Do trivial optimizations Convert brainfuck to machine code for the VM Execute this machine code in the VM This is pretty fast, but the bottleneck is now at the VM. It's written in C++ and reads a token, executes an action (w...
Generated machine code is just jmp-ed to or call-ed as usual function. Sometimes it also needed to disable no-execution flag (NX bit) on memory, containing generated code. In linux, this is done with mprotect(addr, size, PROT_READ | PROT_WRITE | PROT_EXEC.) In windows the NX is called DEP. There are some... E.g. http:...
5,986,442
5,986,482
Question about seekg() function of ifstream in C++?
I am testing the following code: int _tmain(int argc, _TCHAR* argv[]) { int sum = 0; int x; ifstream inFile; inFile.open("test.txt"); if (!inFile) { cout << "Unable to open file"; exit(1); // terminate with error } while (inFile >> x) { cout << x << endl; } ...
Before you seek to the beginning, you need to clear all error flags, else no operations are done on the stream: inFile.clear(); inFile.seekg(0,std::ios::beg); That's because the eof bit will be set, because you reached the end of the file before.
5,986,668
5,986,688
Does this code produce Undefined Behavior or it is merely Unspecified Behavior?
Lets say that we have two compilation units as follows: // a.cpp extern int value2; int value1 = value2 + 10; // b.cpp extern int value1; int value2 = value1 + 10; When I tried it on VC2010, it initializes value1 and value2 to zero first. aren't both value1 and value2 dynamically initialized and default initializatio...
3.6.2/1 says that "Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place". So you're right, they aren't default-initialized. But they are zero-initialized, which in fact for int is the same thing. For a class type it's not necessarily the same thing. Th...
5,986,757
5,986,787
Is it possible to send/receive data to/from a SOAP web service from unmanaged C++/MFC code?
I have an C++/MFC project that I need to connect to a SOAP web service from to send data and receive a response. Is there any way to do it?
There are tools that can help you do it, such as gSOAP, which works basically as you would expect it too (similar to Java and .NET WSDL to code generators).
5,986,875
5,987,225
C++ ceil and negative zero
On VC++ 2008, ceil(-0.5) is returning -0.0. Is this usual/expected behavior? What is the best practice to avoid printing a -0.0 to i/o streams.
ceil in C++ comes from the C standard library. The C standard says that if a platform implements IEEE-754 arithmetic, ceil( ) behaves as though its argument were rounded to integral according to the IEEE-754 roundTowardPositive rounding attribute. The IEEE-754 standard says (clause 6.3): the sign of the result of con...
5,986,934
5,987,192
IPC between a C# application and other applications in C++ and VB.Net
I have a C# server application and it needs to talk to and control another 3 client applications: one in C#, one in C++ and one in VB.Net. All of them are Windows Form applications. They basically need to exchange some strings and numbers, not heavily loaded. What is the best way to do IPC between C# and those differen...
Actually WCF configured to expose services via HTTP might be the best option for the list of languages you want to support. If you don't like WCF consider exposing HTTP REST interfaces i.e. by writing server in ASP.Net MVC. Named pipes support - C#/VB.Net, C++ - good, VB6 - I don't know, VBScript - definitely not out o...
5,986,935
5,986,975
Difference between explicit specialization and regular functions when overloading a template function
I'm on a roll today. Here goes n00b question number 7: What's the difference between explicit specialization and just regular functions when you try to overload a template function? What's the appropriate situation to use the explicit specialization? I don't quite understand it: #include <iostream> template <typename ...
There really isn't a difference between an explicitly specialized template function and a non-template regular function other than the fact that when the compiler looks for a matching signature type for the function call, it will first pick a non-template function that matches the required signature before trying to in...
5,987,001
5,987,320
Proper message queue usage in POSIX
I'm quite bewildered by the use of message queues in realtime OS. The code that was given seems to have message queues used down to the bone: even passing variables to another class object is done through MQ. I always have a concept of MQ used in IPC. Question is: what is a proper use of a message queue?
In realtime OS environments you often face the problem that you have to guarantee execution of code at a fixed schedule. E.g. you may have a function that gets called exactly each 10 milliseconds. Not earlier, not later. To guarantee such hard timing constraints you have to write code that must not block the time criti...
5,987,184
5,987,237
Class internal lambdas and boost function
I'm using C++0x's lambdas to define boost functions. I have some classes where I define some of their behaviour using lambdas/boost functions. What I was wondering is, is it possible to expose data about the classes into the lambda's context without altering the function definition? For example, I have a set of class l...
Do you need to access variables that are available in the scope of StatBoostingItem::StatBoostingItem from your lambda? In that case you could simply use captures: RegularUse = [&](std::set<Character::BaseCharacter*> users, std::set<Character::BaseCharacter*> targets) The [&] tells the lambda to captures everything fro...
5,987,213
5,988,726
What is the potential scope of a template parameter?
A point from ISO draft n3290 section 3.3.9 paragraph 5: Because the name of a template parameter cannot be redeclared within its potential scope (14.6.1), a template parameter’s scope is often its potential scope. However, it is still possible for a template parameter name to be hidden; What does "potenti...
3.3.1 : The scope of a declaration is the same as its potential scope unless the potential scope contains another declaration of the same name. In that case, the potential scope of the declaration in the inner (contained) declarative region is excluded from the scope of the declaration in the outer (co...
5,987,224
5,987,270
c++ programming problem
hi I'm trying to compile a c++ , program for julia set my source code is following #include<stdio.h> #include<stdlib.h> #include<iostream> #include<cpu_bitmap.h> #include<book.h> #define DIM 20 using namespace std; struct cuComplex{ float r; float i; cuComplex( float a, float b ) : r(a), i(b){} float magnitud...
The error is telling you that the kernel() needs to know the declaration of the function julia() before using it. In your code It is defined after kernel() Declare it before usage. Add int julia(int x, int y); before kernel() definition. You could also move the entire julia() function definition before kernel() to...
5,987,285
5,988,472
What is an "acceptable" return value from cv::calibrateCamera?
Background: I'm currently working on a stereo vision project using OpenCV. I'm trying to create a disparity map from a set of two rectified images, but I'm not getting the result I expect. When looking at the rectified images, there is a noticeable vertical shift between the images, which should not be there after rect...
There is a problem with your camera calibration: cv::calibrateCamera() returns the root mean square (RMS) reprojection error [1] and should be between 0.1 and 1.0 pixels in a good calibration. For a point of reference, I get approximately 0.25 px RMS error using my custom stereo camera made of two hardware-synchronized...
5,987,482
5,987,491
why ++++i regular but i++++ not regular in C++?
When I use i++++ give compile error : for (int i=1;i<=10;i++++) {} //a.cpp:63: error: lvalue required as increment operand or int i = 0; i++++; // a.cpp:65: error: lvalue required as increment operand but when I use ++++i is working. Anybody explain me why ++++i regular but i++++ not regular? Thanks.
Since type of x is built-in primitive type, both expressions invoke undefined behaviour, as both attempt to modify the same object twice between two sequence points. Don't do either of them. Read this FAQ : Undefined behavior and sequence points However if the type of x is a user-defined type and you've overloaded op...
5,987,535
5,987,610
Multithreading using threadpool
I'm currently using the boost threadpool with the number of threads equal to the number of cores. I have scheduled, say 10 tasks using the pool's schedule function. For example, suppose I have the function void my_fun(std::vector<double>* my_vec){ // Do something here } The argument 'my_vec' here is just used to d...
Probably boost::thread_specific_ptr is what you need. Below is how you may use it in your function: #include <boost/thread/tss.hpp> boost::thread_specific_ptr<std::vector<double> > tls_vec; void my_fun() { std::vector<double>* my_vec = tls_vec.get(); if( !my_vec ) { my_vec = new std::vector<double>(); ...
5,987,780
5,988,532
can Winelib be used with commercial applications?
This is the only place I can ask this question since the WineHQ forum is locked for some reason... So please tell me if I can statically link Winelib with a commercial application and what are the terms of its use - should it be acknowledged in documentation, application's about box, etc.?
A couple of points: You can't really link with Winelib statically. I mean - you probably can, but it you still need almost all of Wine's infrastructure, anyway. Winelib is 95% of Wine, basically everything minus the PE-Loader (the code that can read Windows executables). Wine is licensed LGPL. IANAL, but that means y...
5,987,789
5,987,938
multidimentional char array - how to fill it with random chars?
So I have tried to create a generator like: #include <iostream> #include <iomanip> #include <cmath> #include <stdio.h> #include <stdlib.h> using namespace std; char* data; void genRandomFilledChar(char *s, int i, int j, int k) { const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ...
char* data; // .... data = new char[10000][10000][10000]; Are wrong. First, a three dimensional array of chars is char***. Next, you need to initialize that memory in 3 steps. data = new char**[10000]; for(int i=0; i < 10000; ++i){ data[i] = new char*[10000]; for(int j=0; j < 10000; ++j){ data[i][j] = new cha...
5,987,817
5,987,883
How can understand a constant variable in memory. C++
If I have a constant variable, is it stored in a seperate memory space from non-constant variables? I have encounter some odd in this program. //--------assign a const value to non-const value------- const int cst_a = 5; int* ptra = const_cast<int*>(&cst_a); cout<<&cst_a<<" "<<ptra<<endl; // same address *ptra = ...
It may be stored in a memory area that can't be modified. Because of this, your const_cast results in undefined behavior.
5,987,986
5,989,108
Very Mysterious/Random C++ WDK STL 7 Error: iosfwd(202): error C2144: syntax error
I have the following trivial file named Temp.cpp: #include <string> int main() { return 0; } and I'm trying to compile it with the following command-line in the Windows XP Free Build Environment, using WDK 7.1: cl.exe /Iinc\api\crt\stl70 /Iinc\crt C:\Temp.cpp and I'm getting really random errors like: Microsoft (R) 3...
Found the answer myself, through modifying the headers and guess'n'checking: I need to have _STL70_ defined.
5,988,084
5,988,150
__cdecl forcing prefix with underscore
My company provides a third party with a DLL which provides them with API functions they can use to connect to our application. The DLL was written in VC9, and the API functions used VC's default calling convention (__cdecl). The third party has built their application around this interface. I have now been tasked with...
You should use .DEF file: EXPORTS HTMLayoutClassNameA = HTMLayoutClassNameA HTMLayoutClassNameW = HTMLayoutClassNameW HTMLayoutClipboardCopy = HTMLayoutClipboardCopy ... Here we have externalname = internalname
5,988,219
5,988,242
C++ destructor behaviour
I tried the following program on Visual Studio 2010. #include <iostream> using namespace std; class A { public: int p; /*A(){ cout << "Constructor A" << endl; }*/ ~A(){ cout << "Destructor in A" << endl; } }; class D: public A { public: /*D(...
The line D d = D(); first creates a temporary, unnamed object, which then is copied to d. What you see is the temporary object being destroyed when the statement is ended. The named object d is destroyed when it goes out of scope, after main() is completed. If you add a copy constructor to D you'll see that it is in...
5,988,457
5,988,538
Is wchar_t Supported in C++ WDK STL? I get Unresolved External Symbol's :(
I'm compiling a trivial C++ file Temp.cpp: #include <string> int main() { std::wstring s; } With the command line: cl.exe /MD /Iinc\api\crt\stl60 /Iinc\crt /Iinc\api C:\Temp.cpp /LibPath:lib\wxp\i386 /LibPath:lib\crt\i386 /link /LibPath:lib\wxp\i386 /LibPath:lib\crt\i386 in the WDK 7.1 Windows XP Free B...
The likely fix would be to set /Zc:wchar_t- to turn off wchar_t as an intrinsic type. STL6 doesn't have great support for /Zc:wchar_t which is the default since at least VC7.1, perhaps earlier. Meta: Please don't use the STL60 version of STL. This version from 1998 lacks a large number of bug fixes, performance improve...
5,988,621
5,988,746
template parameter hiding
A point from ISO draft n3290 section 3.3.9 paragraph 4: The declarative region of the name of a template parameter is nested within the immediately-enclosing declarative region.[Note: As a result, a template-parameter hides any entity with the same name in an enclosing scope (3.3.10). Example: typedef int ...
I think it is quite obvious: any time that an entity in the scope of the template declaration has the same name as one of the template parameters, the name will be hidden within the template. If you are having problems coming up with examples chances are that you did not understand the meaning of the quote. What is it ...
5,988,676
5,988,697
C++ operator overloading
In C#, the method(function) of overloading any operator must be static and public. I see that making it static is a good thing, every object doesn't need its own version of it. But in C++, it doesn't have to be static. Why does C# enforce this and C++ doesn't? What are the advantages and disadvantages of both designs?
why C++ Doesn't enforce operator overloading to be "Static" ? If you make overloaded operator function static it wont have access to this. One would need access to this inside the overloaded function, as usually the function would change the state of this. You can make a overloaded operator function static if you don...
5,988,991
5,989,434
Pointer typecasting with and without reference
Given that A* pA; and B* pB;, is there ANY difference between below type castings (query for all C++ style casts): pB = reinterpret_cast<B*>(pA); // pointer pB = reinterpret_cast<B*&>(pA); // pointer-reference
The two are radically different, at least in theory (and possibly on a few rare machines, in practice). The first takes a pointer to A, and converts it to a pointer to B; in theory, at least, this may involve changes in size and representation. (I've actually worked on machines where char* was larger than int*. I r...