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
4,591,670
4,591,750
Non-Static Data Duration in Static Functions
I would like to initialize a static array of abstract interfaces. I'm just wondering if a call to a static function to build the data is a valid means of initialization. What will the lifetime of the data that the pointer is pointing to in the code below look like? typedef class FOO { public: static const int** a...
Your variables are locals and they will cease to exist when the function exits. If you need them to survive then declare both vars and array as static inside the function with const int** array_int_init() { static const int A = 5; static const int B = 6; static const int C = 7; static const int* array_...
4,591,915
4,591,953
No console output on cout
Good morning, I have a problem with Eclipse IDE for C/C++ Developers. I'm writting a smal tool for converting Strings. While testing on some point eclipse stopped to give console output. e.g.: cout<<"test"; doesn't get displayed. But it's not every where... another example: // File path as argument int main(int argc, ...
You need to end output strings with newline, e.g.: `cout << "test\n"``. The reason is that the standard output is buffered and the buffer is flushed on newline. There probably exists a way to flush the cout buffer without outputting a newline, but I don't know it by heart. Probably includes access to the underlying str...
4,591,994
4,592,167
What front-end and back-end technologies do Google and Facebook use?
What technologies do Google and Facebook use for their back-end and front-end? What are their database technologies, and languages they use to process the back-end data.
http://web.archive.org/web/20110708015633/http://panela.blog-city.com/python_at_google_greg_stein__sdforum.htm Where is Python used? The Google build system is written in python. All of Google's corporate code is checked into a repository and the dependency and building of this code is managed by python. G...
4,592,166
4,592,201
What does the term "empty loop" refer to exactly in C and C++?
Is it this kind of thing: for(;;) { statements; } Or is it this: for(initialisation;condition;updation) { } I am looking for answers with references to a variety of sources.
Your first case (for with empty expressions) is an infinite loop and the second one (with empty body of the for statement) is an empty loop
4,592,203
4,647,261
Find window handle of a ribbon button
I'm trying to do some automation of windows applications. To do whatever I want to do, I need the window handles of some controls. Before, I would accomplish this with a combination EnumWindows, EnumChildWindows and GetWindowText. But now, some newer programs no longer have toolbar with buttons on it. Instead, they hav...
Okay, So it was indeed not possible to get a handle on these buttons. I solved this by using SendKeys to send the keyboard-shortcut that activates the button. In my case it was the save button, so I used INPUT inputs[4]; // press control inputs[0].type = INPUT_KEYBOARD; inputs[0].ki.wVk = 0x11; // "VK_Control" ...
4,592,352
4,592,466
Number of parameters for a constructor
I have a class that needs 12 parameters to be passed to its constructor. So I think that there is something wrong with the design of this class. I would like to ask if there is any design pattern or a general collection of rules regarding the design of a class, especially its constructor.
12 parameters definitely sound too many to me. Options to reduce their numbers are: Introduce Parameter Object by grouping logically related parameters into an object and passing that object instead of the individual parameters. Introduce a Builder (optionally with method chaining). This does not reduce the actual par...
4,592,908
4,592,942
C++ queue - simple example
I can't find simple example how to use queues in C++ for pointers to some myclass objects. I have code like this: class myclass{ string s; }; myclass *p = new myclass(); my_queue.push(p); //something.... p = my_queue.front(); my_queue.pop(); std::cout << p->s; What should be declaration of my_queue? Should I us...
Simply declare it as below if you want to us the STL queue container. std::queue<myclass*> my_queue;
4,593,177
4,593,193
How do I write in-code comments and documentation in a proper way? Is there any standard for this?
I want to add documentation in my code by means of comment lines. Is there any standard format for this? For example, consider the code below: class Arithmetic { // This method adds two numbers, and returns the result. // dbNum1 is the first number to add, and dbNum2 is second. // The returning value is d...
For c++ there isn't a standard, like javadoc, but certain documentation tools are popular and common to use. Off the top of my head, I can mention doxygen. Doxygen also supports the familiar javadoc style, ie: /** This method adds two numbers, and returns the result. @param dbNum1 is the first number to add @p...
4,593,234
4,593,532
undefined reference to vtable - virtual member, classes generated by gsoap
gsoap with its tools wsdl2h and soapcpp2 provided me with a soapStub.h file containing the following: class SOAP_CMAC ns2__SOAPKunden { public: std::string *adresszusatz; // ... public: virtual int soap_type() const { return 7; } // ... ns2__SOAPKunden() : adresszusatz(NULL), x(NULL) { } // l...
The error means that the virtual table has not been correctly compiled/linked in the final binary (executable or library). There are two common circumstances that lead to this error: you are not linking the object file that includes the virtual table definitions --i.e. you compiled soapStub.cpp into soapStub.o, but di...
4,593,784
4,593,920
How to keep custom text in Window (Win32)
We can set window text with: BOOL WINAPI SetWindowText( __in HWND hWnd, __in_opt LPCTSTR lpString ); and this windows text by another application int WINAPI GetWindowText( __in HWND hWnd, __out LPTSTR lpString, __in int nMaxCount ); I don't want to change my forms caption but I want to keep a cus...
A simple way to do this is: Define your own WM_APP message, which instance A of your app will use to tell instance B's window "send me your private text". When instance B receives this message, it can use WM_COPYDATA to send a reply to instance A's window. Instance A receives the data from WM_COPYDATA and does what i...
4,593,793
4,594,060
How to decrypt string data in C++ with Crypto++ where the original string encrypted in Python with pyCrypto
I've just encrypted a data string with pyCrypto easily, but don't know how to decrypt it in crypto++. Anybody can help with a sample decryption code in C++ with crypto++? Here is my python code: key = '0123456789abcdef' data = "aaaaaaaaaaaaaaaa" iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16)) encryptor...
This code is from an example from 2005, but it should give you a good starting point: std::string ciphertext = "..."; // what Python encryption produces std::string decryptedtext; byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ]; // populate key and iv with the correct values CryptoPP::AE...
4,593,881
4,594,284
how to check if boost::deadline_timer is active
any way to check if deadline_timer is active? e.g. if it's in async_wait state and wasn't cancelled?
The handler for the timeout will be called with an error condition if the timer was canceled (as well as a normal timeout). So could you not simply set a bool before calling async_wait and then reset that in the handler if the error condition is set?
4,594,292
4,596,051
VS 2010 error - cannot open file "iostream"
I've just migrated from VS2005 to VS2010 and it fails to compile a simple program. #include <iostream> using std::cout; using std::endl; int main() { cout << "Hello Visual Studio 2010 :)" << endl; } Errors - 1 error TRK0005: Failed to locate: "CL.exe". The system cannot find the file specified. 2 IntelliSense: ...
I've run into the same issue on a couple of different machines where there were other versions of VS (2005, 2008) already installed. I ended up also getting all sorts of strange errors. I found the following trick worked for me, maybe it will work in your case too: - Open a new instance of VS2010 - Create new console ...
4,594,640
4,594,803
C++: Getting the "error C2065: 'pst' : undeclared identifier" while using pstsdk?
Following the suggestion of working with the pstsdk in this question: Processing Microsoft Office Outlook 2003/2007 email messages… And following the instructions here: PST File Format SDK - PST Layer Overview - Getting Started And also according to this video: In PST SDK Presentation, Terry Mahaffey, discusses the PST...
It is declared in a namespace, as it should. Fix: pstsdk::pst myfile(fileNameTextBox->Text);
4,594,970
4,595,226
OpenGL: Should i always clip the glColor*f values myself?
This may sound stupid... but I've been wondering, does it matter if i send a value greater than 1.0f to the glColor*f functions? Does older gfx cards/drivers handle these differently? Does OpenGL directly use the color value i give to it, or does it clip it on its own? Should i stop doing if(r > 1.0f) r = 1.0f; ? Is th...
From the manpage: "Neither floating-point nor signed integer values are clamped to the range [0,1] before the current color is updated. However, color components are clamped to this range before they are interpolated or written into a color buffer."
4,595,217
4,595,546
What can't the NDK be used for?
From the official NDK site: The Android NDK... provides headers and libraries that allow you to build activities, handle user input, use hardware sensors, access application resources, and more, when programming in C or C++. If you write native code, your applications are still packaged into an .apk file...
It's important to note that the documentation you're referring to was around before the ndk was actually capable of dealing with things such as activities, and whatnot. As such, back then what you would need to do is create an android app with the sdk, and at a bare minimum, you needed to create a java wrapper class f...
4,595,404
4,595,831
C++: Getting the c3859 error code while compiling in a mix of C++/CLI and C++
After I have done as suggested by Hans Passant in C++: Getting the "error C2065: 'pst' : undeclared identifier" while using pstsdk? (which works), my code now looks like this: private: System::Void readPstFileButton_Click(System::Object^ sender, System::EventArgs^ e) { pstsdk::pst myfile(marshal_as<std:...
Right-click your C++ project in Solution Explorer; choose Properties. In the Properties dialog, expand Configuration Properties > C/C++ > Command Line In Additional Options, add /Zm120 Repeat this for Debug and Release and any other configurations you have. For more information on what this command-line option does (...
4,595,646
4,597,226
c++ decode CCITT encoded images in pdfs
I'm trying to extract all images out of PDF files in C++. I'm stuck in decoding CCITT encoded images. Does anyone know an opensourced code for this? I use the ImageMagick Magick++ Library, is it possible to do the decoding with this library, too? Thanks for your help!
CCITT is one of the encodings TIFF supports, though in a PDF file the CCITT images are probably raw data. You can convert a raw CCITT image into a Tiff image using Fax2Tiff. It should be easy enough to work with the image once it is encoded as a Tiff. Fax2Tiff is part of LibTiff. See LibTiff Source
4,595,675
4,596,289
Determining Whether Pointer is Valid
It has been my observation that if free( ptr ) is called where ptr is not a valid pointer to system-allocated memory, an access violation occurs. Let's say that I call free like this: LPVOID ptr = (LPVOID)0x12345678; free( ptr ); This will most definitely cause an access violation. Is there a way to test that the me...
To address your specific concern, I don't think you have to worry about checking the pointer. If the application passes your DLL an invalid address, it represents a memory management problem in the application. No matter how you code your driver, you can't fix the real bug. To help the application developers debug th...
4,595,750
4,597,733
Source code dependency manager for C++
There are already some questions about dependency managers here, but it seems to me that they are mostly about build systems, while I am looking for something targeted purely at making dependency tracking and resolution simpler (and I'm not necessarily interested in learning a new build system). So, typically we have a...
You can use Maven in relationship with C++ in two ways. First you can use it for dependency management of components between each other. Second you can use Maven-nar-plugin for creating shared libraries and unit tests in relationship with boost library (my experience). In the end you can create RPM's (maven-rpm-plugin)...
4,595,796
4,596,001
How can I get file icons on Windows asynchronously (and ideally in parallel) from C++?
The MSDN documentation for SHGetFileInfo says, quite rightly: You should call this function from a background thread. Failure to do so could cause the UI to stop responding. so I'm trying to figure out a good way to do this where I have a large list (80+) of them to do, and would like to parallelize the underlying I/...
Create a queue of file names to process (a linked list would suffice; consider STL's std::list). Create a lock for that queue (a critical section would do). Spawn a bunch of threads (2-4). Each thread would acquire the lock, get the head from the queue, release the lock and retrieve the icon - in the loop. If no more i...
4,596,110
4,596,781
How do I get the column names of a QSqlTableModel?
I would like to have something like QString QSqlTableModel::getColumnName(int col).
You can set column name aliases like so in a QSqlTableModel: model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("First name")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("Last name")); So likewise then you can retrieve column name aliases like so f...
4,596,212
4,596,632
ODBC refuses to statically link to libcmt.lib under VS2010
There is a short response from Microsoft regarding this issue: https://connect.microsoft.com/VisualStudio/feedback/details/470376/odbc-application-linking-with-odbccp32-lib-gets-link-errors-in-vs2010-beta-1?wa=wsignin1.0#tabs Basically, their response doesn't seem to address the problem. Our application needs to static...
Reading through your link, it seems that Microsoft has verified that there is a problem, and they intend to fix it in the next version of the SDK. Doesn't help much, does it? It's quite normal for the linker to daisy-chain through the objects, linking one object only to discover that it has dependencies on other object...
4,596,421
5,336,715
DBus Glib with C++: Can't create a DBusGProxy, release it and create that again
I'm working on a lib that uses Glib internally to connect to other modules. This lib has a initialize method that sets up the dbus connection and a terminate method that finalizes all the internal resources (including the dbus connection). At least it should do this. However, I can't make dbus calls again after the ter...
Don't use dbus-glib in new code, use GDBus instead. GDBus is the new dbus api in glib 2.26. Its advantages over dbus-glib include the use of the GIO async patterns (GAsync*, GCancellable), the use of GVariant for variant types and better threading support. See http://library.gnome.org/devel/gio/2.28/ch29.html for migr...
4,596,499
4,596,518
how to specify NULL as pointer-type argument to template function
This shows the gist of it: #include <utility> class A { public: A() { } }; class B { public: B() { } }; typedef std::pair<A*, B*> ABPair; int main(int argc, char* argv[]) { B* b = 0; // no C2440 ABPair p2(new A(), b); ABPair p1(new A(), 0); // C2440 return 0; } Is there a b...
Not really. nullptr will fix this in C++0x, but for now, write (B*)0.
4,596,658
4,596,722
hash tables and 2d vectors
I want to push a 2d vector into a hash table row by row and later search for a row (vector) in the hash table and want to be able to find it. I want to do something like #include <iostream> #include <set> #include <vector> using namespace std; int main(){ std::set < vector<int> > myset; vector< vector<int> > v; in...
For inserting use std::set::insert, ala myset.insert(v.begin(), v.end()); for find, use std::set::find ala std::set < vector<int> >::iterator it = myset.find(v[1]); Working example: #include <iostream> #include <set> #include <vector> using namespace std; int main() { typedef vector<int> int_v_t; typedef set<int...
4,596,772
4,596,782
useful namespaces in c++ other than 'std'
Whenever I read books about C++, I find an example of "using namespace std". I would like to know if any other namespaces are present in C++ which are useful?
boost. std::tr1. (Technical Report 1) But using namespace std; is not a good idea, and especially not in header files. It's 5 extra characters every time you use it, for significantly clearer code and less clashes.
4,597,006
4,597,266
How can I access a string like an array in AutoIt? (I'm porting code from C++ to AutoIt)
Ok, gah, syntax conversion issue here...How would I do this in AutoIt? String theStr = "Here is a string"; String theNewStr = ""; for ( int theCount = 0; theCount < theStr.Size(); theCount++ ) { theNewStr.Append(theStr[theCount]); } I am trying to access individual chars within a string in AutoIt and extract them. Th...
What about this: $theStr = StringSplit("Here is a string", "") ; Create an array $theNewStr = "" For $i = 1 to $theStr[0] Step 1 $theNewStr = $theNewStr & $theStr[$i] Next MsgBox(0, "Result", $theNewStr)
4,597,032
4,597,055
Overloading a super class's function
Is there something in the C++ standard that prevents me from overloading a super class's function? Starting with this pair of classes: class A { // super class int x; public: void foo (int y) {x = y;} // original definition }; class B : public A { // derived class int x2; public: void foo...
You need to use a using declaration inside the definition of class B: class B : public A { public: using A::foo; // allow A::foo to be found void foo(int, int); // etc. }; Without the using declaration, the compiler finds B::foo during name lookup and effectively does not search base classes for o...
4,597,048
4,775,690
Boost Property_Tree iterators, how to handle them?
I am sorry, I asked a question about the same topic before, but my problem concerns another aspect of the one described there (How to iterate a boost...). Take a look at the following code: #include <iostream> #include <string> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #incl...
I agree with Andry, and find the documentation of property_tree to be extremely minimal at the least. I needed ptree for loading identical objects with different settings, and had trouble figuring out what the iterator iterates over, what type it returns, and whether or not it will remain on the objects level, or go th...
4,597,175
4,597,578
Missing type specifer error
I've got problem while including header files, in every header file i use #pragma once File structure: Main.cpp - includes Main.h class definition Main.h - includes "class.h" "random_header.h" others ( windows , fstream ) class declaration Class.h - includes "Main.h" class cApplicatio...
What you have is a circular inclusion issue. Manually replace each of those #includes with the file they include's content, in the order they happen, ignoring any file that was previously include, and you'll see that, in cApplication.cpp, "extern cApplication App;" happens above the declaration of cApplication. As to h...
4,597,281
4,597,319
MYSQL headers conflict with STL <algorithm> in C++
// File test.cpp #include <my_global.h> #include <algorithm> int main() { return 0; } Compiled with: g++ -c -I /usr/local/mysql/include/mysql/ test.cpp, where /usr/local/mysql is the mysql install directory.Then the compiler report the following errors: In file included from /usr/include/c++/4.4/algorithm:61, ...
It seems that the mysql header defines a macro min. #if !defined(max) #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) #endif This has been reported to MySQL as bug 28184. The bug is marked as closed, so try updating to the newest version. According to the bug page it sh...
4,597,932
4,597,974
How can I (is there a way to) convert an HRESULT into a system specific error message?
According to this, there's no way to convert a HRESULT error code into a Win32 error code. Therefore (at least to my understanding), my use of FormatMessage in order to generate error messages (i.e. std::wstring Exception::GetWideMessage() const { using std::tr1::shared_ptr; shared_ptr<void> buff; LPWSTR bu...
This answer incorporates Raymond Chen's ideas, and correctly discerns the incoming HRESULT, and returns an error string using the correct facility to obtain the error message: ///////////////////////////// // ComException CString FormatMessage(HRESULT result) { CString strMessage; WORD facility = HRESULT_FACIL...
4,598,165
4,598,387
Unsatisfied symbols in Debug but not Release
I am building something on HPUX. Code works fine in Sun/Linux/AIX. But on HPUX it complains on [sshexec] /usr/ccs/bin/ld: Unsatisfied symbols: [sshexec] globalVar (first referenced in blah.o) Once again code works in Release but not in Debug. All it does it uses global variable defined in some other file extern ...
The first thing to do when the linker complains that something isn't defined is to go find for yourself where that thing is defined. If you can't find it, then don't expect the linker to find it, either. What you have shown is a declaration, not a definition. A definition will not have the extern keyword. There should ...
4,598,308
4,598,573
How do I compile and link C++ code with compiled C code?
I want to be able to use Cmockery to mock C functions called from C++ code I'm testing. As a step towards that, I've renamed the Cmockery example run_tests.c to run_tests.cpp, and am attempting to compile and link it with cmockery.c: g++ -m32 -DHAVE_CONFIG_H -DPIC -I ../cmockery-0.1.2 -I /usr/include/malloc -c run_tes...
I think that you can get thinkgs to link from C++ by adding the following around the contents of the cmockery.h file: At or near the beginning: #if defined(__cplusplus) extern "C" { #endif At or near the end: #if defined(__cplusplus) } #endif That way, use of the header in C sources will ignore the extern "C" part of...
4,598,343
4,598,372
How can facebook deals with their databases informations?
Good day guys, After browsing a bit in my spare time at work, I stumbled upon the Facebook statistics page. "More than 30 billions pieces of content ... shared each month." We can assume there are probably around let's say 20ish billions posts a month. For now, I believe MySQL will have no problem dealing with such...
What about unsigned long long which is 64-bit long, exactly as BIGINT? :) Also, I believe that Facebook do not use numeric ids for their DB, because it is very hard to do that at multiserver database configuration with parallel inserts.
4,598,872
4,616,394
Creating HBITMAP from memory buffer
I have an application which loads some blob data out of a database which can represent png formatted or raw binary data for various bitmaps and icons. This is being stored in a std::vector<unsigned char> I'm using CImageList objects to display various images in tree views, toolbar images, etc but the problem is creati...
Using GdiPlus I got something that works pretty well and doesn't involve pulling any teeth! Gdiplus::Bitmap* pBitmap = NULL; IStream* pStream = NULL; HRESULT hResult = ::CreateStreamOnHGlobal( NULL, TRUE, &pStream ); if(hResult == S_OK && pStream) { hResult = pStream->Write(&bits[0], ULONG(bits.size()), NULL); ...
4,598,941
4,598,994
how to set 2D window
How to set up 2d view in Directx? Is there any similar function, to this OpenGL one? gluOrtho2D( 0 , 800 , 0 , 600 );
The equivelent call in DirectX 9 would be D3DXMatrixOrthoRH - However, you very likely will want to use the Left handed version, if you are trying to follow other DirectX code, as DirectX 9 is often done in a left handed coordinate system (instead of RH like OpenGL). The left handed version is D3DXMatrixOrthoLH.
4,598,956
9,363,451
Async OpenSSL problem with BIO_ctrl_pending()
I have an asynchronous client and server application that wrap OpenSSL. Once created, they call SSL_set_connect_state()/SSL_set_accept_state() respectively to initialize their internal state. Up to this point everything is running as it should be. I'm assuming once those aforementioned states are set, hand shaking can ...
Old question but keeps popping up when googling openssl stuff, so for reference: Just initiate handshake instead of relying on peek/read doing it internally: If it's not a socket bio the handshake will fail with ssl_error_want_read and then you use ctrl_pending to get the size to read. Something like this: ret = S...
4,598,986
4,599,040
Weak pointer to this in constructor
I understand it is not possible to obtain a shared_ptr by calling shared_from_this() from the constructor of a class, as the object is not yet constructed. Is it possible however to obtain a weak_ptr to the object from the constructor? Some boost forum posts discussing a "weak_from_raw()" method suggests that it may be...
I think what you're referencing is this. Which seems not to have been merged to the boost release (may be wrong about that). From the boost docs: Frequently Asked Questions Q. Can an object create a weak_ptr to itself in its constructor? A. No. A weak_ptr can only be created from a shared_ptr, and at object constructio...
4,599,249
4,599,272
When to use pointer to a class and when to just instantiate it as a variable
Im sort of confused by it. The best I could find was reading through the cplusplus.com tutorial and all they have to say about pointers to classes. "It is perfectly valid to create pointers that point to classes. We simply have to consider that once declared, a class becomes a valid type, so we can use the class name a...
A good way to think about when to stack-allocate (non-pointer) versus heap-allocate (pointer) an object is to think about how long you want that object to live. If you put the object on the stack as a local variable, then it will be cleaned up and cease to exist as soon as the function returns. If you want the object...
4,599,324
4,605,970
building boost with unicode regex enabled on x64 windows
Am trying to build boost on x64 windows. So far all is going well, however, I can't persuade boost to find the ICU library. I have a binary release of x64 ICU available at c:\dev so, using the MSVC x64 tools prompt I am issuing the following: set PATH=%PATH%;c:\dev\bin; set INCLUDE=%INCLUDE%;c:\dev\include; set LIB=%LI...
Apply this patch from Boost SVN and make sure ICU_PATH is defined, for more information see Boost bug#4864 .
4,599,599
4,599,606
where are images stored inside programs?
i'm new to programs so bear with me For example, Firefox.. I go to the C/program files/mozilla/firefox folder ..but I don't see the images/buttons they used for the default theme of the program Also, photoshop and other programs: how are the buttons, images, and other media stored (not in a folder from what I see)? sam...
Images are usually stored as resources in DLL or EXE files. You can see the resources by opening a compiled binary in Visual Studio. Firefox stores images in JAR files for skins.
4,599,625
4,599,914
Distribution of many small classes
I have a base class called EventArgs. Derived from this are many, many specializations that represent event arguments for a particular kind of event. Consumers of these events may need some, many, or very few of these argument classes. My question is, would you provide a header file for each type (e.g, 50+ header fil...
I would have to put two classes into separate headers in one of the following cases: they are huge they are unrelated or unlikely to be used together each of them introduces its own header dependencies Otherwise, it does not make much sense to separate them. I know some people have this "one class per header" rule, b...
4,599,643
4,599,683
How to copy vector column-wise?
I've a 2d vector say vector < vector < int > > sample; sample = 1 2 3 4 5 6 7 8 9 0 1 1 1 1 1 2 2 2 2 2 Now I want to copy only the last two columns into another 2d vector like vector < vector < int > > test; test = 4 5 9 0 1 1 2 2 How can I do this efficiently ?
Maybe like this? #include <algorithm> vector<vector<int> > new_vector; new_vector.resize(sample.size()); for (size_t i = 0; i < new_vector.size(); ++i) { new_vector[i].resize(2); copy(sample[i].end() - 2, sample[i].end(), new_vector[i].begin()); }
4,599,792
4,602,607
Accessing std::map keys and values
How do you access an std::vector of the keys or values of an std::map? Thanks. Edit: I would like to access the actual elements, not just copies of their contents. essentially I want a reference, not a copy. This is essentially what I am wanting to do: std::map<std::string, GLuint> textures_map; // fill map glGenText...
As others have said in their answers, you can't access all the keys or values in the form of a std::vector without copying them - std::map isn't designed for this form of access. For your situation, I would set up 2 containers: std::vector<GLuint> texture_id; std::map<std::string, size_t> texture_map; where the vector...
4,599,837
4,599,949
Learning C++ and SDL- does the following generate a memory leak?
I'm learning a bit of C++ on my own, and I'm not entirely sure I have a good grasp on memory management. I only know Java and a bit of PHP and Python, so this is a bit new for me. I'm working with SDL as well- it seemed like a interesting way to accelerate the learning process. Anyways, I'm trying to write a cleanup fu...
Your own code does not have any memory leakage. Assuming load_image() is safe too, the entire code is clean of memory leakages. Remember that, if you don't use the new operator, no memory leakage occur.
4,599,962
4,599,988
How do I add code automatically to a derived function in C++
I have code that's meant to manage operations on both a networked client and a server, since there is significant overlap between the two. However, there are a few functions here and there that are meant to be exclusively called by the client or server, and accidentally calling a client function on the server (or vice ...
Another approach might be to override a different method than the one your callers actually call: class Base { public: void doit(const Something &); protected: virtual void real_doit(const Something &); }; class Derived: public Base { protected: virtual void real_doit(const Something &); }; The implementa...
4,600,149
4,600,732
PEM Conversion (PKCS7) to DER - AKA Base64 C++ Problems
I've just finished up writing some OpenSSL/PKCS7 digital signature code and now have a working PEM encoded PKCS7 file. So after little battle, I need to convert that PEM to DER format. This is proving tougher than I hoped. There are some convenience methods in OpenSSL such as "PEM_write_bio_PKCS7_stream" to write your ...
i2d_PKCS7_fp() and i2d_PKCS7_bio() from <openssl/pkcs7.h> will write out a PKCS7 structure in DER format to a file stream or BIO respectively.
4,600,190
4,600,196
Global function definition in header file - how to avoid duplicated symbol linkage error
I have the following code in a header only file. #pragma once class error_code { public: unsigned __int64 hi; unsigned __int64 lo; }; std::ostream& operator<< (std::ostream& o, const error_code& e) { return o << "[" << e.hi << "," << e.lo << "]"; } I get linkage error, when there are 2 cpp in the pro...
Use the inline keyword. inline std::ostream& operator<< (std::ostream& o, const error_code& e) { return o << "[" << e.hi << "," << e.lo << "]"; }
4,600,295
4,600,316
What is the meaning of "operator bool() const"
For example: operator bool() const { return col != 0; } col is an int. How does operator bool() const work?
Member functions of the form operator TypeName() are conversion operators. They allow objects of the class type to be used as if they were of type TypeName and when they are, they are converted to TypeName using the conversion function. In this particular case, operator bool() allows an object of the class type to...
4,600,412
4,600,691
What is OpenGL's method for assigning texture IDs?
I have a function that loads a texture, and returns the newly generated GLuint. I need to know what I should return if it fails to load the texture. So if glGenTextures starts assigning texture IDs at 1, I could return GL_FALSE, etc.
It's implementation-defined. You do not need to know, nor should you care, how the implementation allocates names (or IDs, as you call them) for any object. You are expected only to keep track of the integer that represents the object, so that you can bind it, and free it when you're done with it. If you are not alread...
4,600,426
4,603,639
Framework/tool for processing C++ unit tests with numerical output
I am working on a C++ application that uses computer vision techniques to identify various types of objects in a sequence of images. The (1000+) images have been hand-classified, so we have an XML file for each image containing a description of where the objects are actually located in the images. I would like to know ...
I think you should distinguish between Unit testing and algorithm performance (=accuracy and/or speed) evaluation. You should apply both, but separately. Unit testing should tell you whether your code does what it's supposed to be. Not sure if/how you can unit test the whole chain from a raw image to extracted objects,...
4,600,565
4,600,746
Short-circuiting while instantiating template?
Consider this code snippet, template<bool b> struct other { static const bool value = !b; }; template<bool b> struct test { static const bool value = b || other<b>::value; }; int main() { bool value = test<true>::value; } Do compilers instantiate other<true> in situations such as the above, when ins...
According to the C++ spec, section $14.7.1/4: "A class template specialization is implicitly instantiated if the class type is used in a context that requires a completely-defined object type or if the completeness of the class type affects the semantics of the program; in particular, if an expression wh...
4,600,567
4,600,592
How can I delete elements of a std::map with an iterator?
I would like to loop through an std::map and delete items based on their contents. How best would this be done?
If you have a C++11-compliant compiler, here's an easy way to do this: std::map<K, V>::iterator itr = myMap.begin(); while (itr != myMap.end()) { if (ShouldDelete(*itr)) { itr = myMap.erase(itr); } else { ++itr; } } The idea is to walk the iterator forward from the start of the container to t...
4,600,587
4,601,734
Loading mswsock.dll takes too much time
Everytime I run my application, loading time is too long. So I looked output window, this was the reason. This take too much time. 'AppName.exe': Loaded 'C:\Windows\SysWOW64\mswsock.dll', Cannot find or open the PDB file I'm using VisualStudio 2010 rightnow, but it was ok with VisualStudio 2005. 64bit, 32bit doesn't m...
Sounds like you are running your program under the Visual Studio debugger and you have the debugger set to automatically (try to) load debug symbols from Microsoft's symbol server. When symbols for a DLL cannot be found locally or on the symbol server there is a long delay while Visual Studio works it out. Who knows wh...
4,600,595
4,600,616
are programs coded separately for different operating systems?
If a program was written in c++ to run on Windows, does it have to be completely rewritten to run on Mac OS or a mobile OS?
C++ is a standard language, which means that the source code that you write can be compiled on any platform which has an implementation of the C++ standard. There are two ways you can write C++ programs that can't be compiled on different implementation. First, if you use language extensions that are found on a specifi...
4,600,643
4,600,678
Template Specialization in Header File
I realize I have to put the below code (For template specialization) in CPP file instead of Header file? Is there any way I can make it in Header file? template<> inline UINT AFXAPI HashKey<const error_code &> (const error_code & e) { // Hash code method required for MFC CMap. // This hash code generation metho...
I think you've to do this in your header file. //template non-specialized version which you forgot to write! //compiler must know it before the specialized ones! template<typename T> inline UINT AFXAPI HashKey(T e); //then do the specializations! template<> inline UINT AFXAPI HashKey<const error_code &> (const error_...
4,600,783
4,601,056
How to verify user's name and password in Windows?
Given a user's name and password, is there a way to check if the name is a valid user account on the system and if the supplied password matches the password for that user's account? Edit: The need for this arises from the way authentication is structured in this application. The app uses the local accounts on the sys...
You should be able to use the LogonUser() API for this purpose... If the call fails, then either the username or password are bogus.
4,601,273
4,601,647
gdb: internal error setting breakpoints
My program is compiled with the -g flag. I am having the following problem: 1) I have set a breakpoint in a function that is in a header file. The breakpoint works. Now, when I go two level up, it is supposed to take me to a C file (Sizer.C:505). It does, but I get loads of warnings: warning: (Internal error: pc 0xff63...
This seems to be a bug in gdb. Check this page: http://sourceware.org/ml/gdb-patches/2003-01/msg00074.html for more details. What's the version of gdb that you are using? try to upgrade to the latest version and try again. Upgrading should fix you problem. [Update] I also found this link: http://sourceware.org/ml/gdb/2...
4,601,578
4,601,608
Functions for comparing 2 bytearrays
I have two byte arrays of same length. Now i want to check if any value of the first array is different from any value of the second array. Is there any ready made functions that i can use rather than checking item by item of the arrays. I am using VC 6.0
http://www.cplusplus.com/reference/clibrary/cstring/memcmp/
4,601,700
4,601,798
Why we can't include std headers within a namespace in C++
The following code will cause compile errors in g++4.4: // File test.cpp namespace A { #include <iostream> } int main() { return 0; } I have this requirement because some third party library comes without namespace protected, and if I directly include these headers, my namespace is polluted. As a result, I tr...
I believe 17.4.2.1 [lib.using.headers] forbids including standard library headers in a namespace : A translation unit shall include a header only outside of any external declaration or definition, and shall include the header lexically before the first reference to any of the entities it declares or first defines in...
4,601,742
4,601,879
How can I search all the occurrence of a regex from a curl output in C++?
I would like to search for every IP address in a curl output. Is there a quick way to do so? I know about regex_search from boost, but from what I read, it is targeted for files. My actual non-working code: #include <iostream> #include <curl/curl.h> #include <boost/regex.hpp> using namespace std; boost::regex express...
regex_search from boost, but from what I read, it is targeted for files. Are you sure? From what I see here: http://www.boost.org/doc/libs/1_45_0/libs/regex/doc/html/boost_regex/ref/regex_search.html Determines whether there is some sub-sequence within [first,last) that matches the regular expression e, parameter ...
4,601,896
4,604,345
Simple MEF example in C++ / CLI
Anybody can give simple MEF example in C++/CLI? Best Wishes PS:I try to convert C# examples but have diffuculties...For example CompositionBatch^ batch = gcnew CompositionBatch(); batch->AddPart(this); In C++/CLI i can not reach CompositionBatch class overloaded method AddPart(object attributedPart) of CompositionBatc...
C++/CLI doesn't support extension methods this way. Extension methods are resolved by the compiler into absolute method calls. That particular method is an extension method of the AttributedModelServices class. Call it as such: AttributedModelServices::AddPart(batch, this);
4,601,930
4,601,940
Printing Associative Array in C++
I have declared an associative array and now want to print it: #include <map> #include <string> #include <cstdio> using namespace std; int main() { map<string, int> m; m["Peter"] = 4; m["John"] = 3; m["Katie"] = 3; map<string, int>::iterator curr,end; for(curr = m.begin(), end = m.end(); cu...
try: printf("%s : %i\n", curr->first.c_str(), curr->second); The c_str() method convert std::string to a c-style string (char*). the ... refers to printf's vararg prototype: int printf(const char *format, ...); which won't support passing c++ objects. BTW, you should use ++curr instead of curr++. This is some c...
4,602,066
4,602,162
Declaring a function as inline friend in different namespace
I have a class declared like this : namespace nsp1 { class A { public : inline friend void DoSomething(); private : A(); int a; }; } Like this, the function DoSomething() will be in the namespace nsp1. Is there a way to declare this function to have it both inline friend and outside of the namespac...
Here is a solution: namespace nsp1 { class A; } inline void DoSomething(const nsp1::A & a); namespace nsp1 { class A { public : inline friend void ::DoSomething(const nsp1::A & a); private : A(); int a; }; } inline void DoSomething(const nsp1::A & a) { std::cout<<a.a<<std::endl;//a.a ...
4,602,136
4,602,186
Linkage problem with Dev c++ and Boost::regex
I'm having a problem using the Boost library in Dev C++, specifically the regex one. I've tried using their example code: #include string #include iostream using namespace boost; regex expression("([0-9]+)(\\-| |$)(.*)"); // process_ftp: // on success returns the ftp response code, and fills // msg with the ftp...
As far as I know you should build the boost regex library and link to it. I assume you are not linking against the regex library. You can find instructions on building the library here: http://www.boost.org/doc/libs/1_45_0/libs/regex/doc/html/boost_regex/install.html
4,602,358
4,602,378
include c++ header (fstream) from c based code?
I'm modifying an open source code(pngcrush) and want to include some c++ header (fstream,iostream) Make complains there are no such files. How do I include them? Thank you -EDIT- adler32.c:60: error: ‘uLong adler32’ redeclared as different kind of symbol zlib.h:1469: error: previous declaration of ‘uLong adler32(uLon...
You cannot. C++ source code cannot be use from C. The only way is to switch to C++: transform your C code in C++ (this often requires no or little modification to the code, only to the build scripts in order to switch compiler) and then use C++ header and tools. EDIT: C++ uses a different way than C to identify symbol...
4,602,560
4,602,692
Rationale for Koenig lookup
What's the rationale of Koenig lookup? Cannot avoid thinking of it like something that makes your code a lot harder to read and more instable. Couldn't they define Koenig lookup so that it only work for specific cases (ie: non-member operators) or when explicitly required?
The original motivation, IIRC, was to be able to write std::cout << 42; without having to qualify std::operator<<(std::ostream&, int) explicitely. If you want to disable argument dependant lookup, you can explicitely qualify the function name, ie. use std::swap instead of swap to prevent swap to be looked up in whatev...
4,602,568
4,604,285
How to use lambda functions with boost::bind/std::bind in VC++ 2010?
I have some lambda functions which I want to bind using either boost::bind or std::bind. (Don't care which one, as long as it works.) Unfortunately both of them give me different compiler erros: auto f = [](){ cout<<"f()"<<endl; }; auto f2 = [](int x){ cout<<"f2() x="<<x<<endl; }; std::bind(f)(); //ok std::bind(f2, 13...
You need to manually specify the return type: boost::bind<void>(f)(); boost::bind<int>(f2, 13)(); You can also write yourself a template-function to deduce the return type automagically using Boost.FunctionTypes to inspect your lambda's operator(), if you don't like to explicitly tell bind.
4,602,574
4,602,611
Can glibc sprintf be used in a reentrant function?
Can I use sprintf in a reentrant function if it writes in a local buffer? Something like this: void reentrant_function () { int i = 4; char buffer[20]; snprintf(buffer, 20, "%d", i); }
Sure you can, unless your buffer is static.
4,602,597
4,603,112
Profiler for Solaris SPARC Platform (for C++ applications)
Is there a profiler for the Solaris 10 SPARC architecture for the use with c++ applications? If it matters: We're using gcc for compiling our c++ sources.
You can use free Solaris/Oracle Studio which comes with a profiler. http://www.oracle.com/technetwork/server-storage/solarisstudio/overview/index.html
4,602,672
4,604,967
create a folder and files in c:\program files\myApp\data in windows 7
I have an old c++ application that needs to be modified to work with windows 7. Problem is in creating a new folder and saving a file in that folder. This folder should be created in c:\program files\myApp\data\newFolder. This is function I use to create new folder and get errors: if(!CreateDirectory(pathSamples,NUL...
It looks like it was enough to set permissions for this folder in installer and now it works normally. Thanks everyone for your answers!
4,602,897
4,608,035
C++ Fake class with callbacks
What would be a good design pattern if I require to test a C++ class A which interfaces with class B where calls to B initiate callbacks to A later on?I require complete control over these callbacks - when they are executed and with what information. I'm using Google Test and Google Mock as my testing frameworks. In Go...
class A should not be concerned if the callback calls are made by B or by some completely different code, as long as all the information provided in the callback is correct. This means that, if your testcase can obtain all the information needed for the callback, then you can invoke the callback from within the test sc...
4,603,041
4,603,122
How to embed and protect some "text" files in my application
My c++ application use some "text files", theses files are very important and I need to protect their content to be viewed/decrypted/extracted/dissassembled... Also, if possible I would like to embed them in the DLL/EXE Can you tell me if there is a way to achieve this? The code must be portable if possible!
The problem with embedded content is that you can only obfuscate it. Imagine that you encrypt the text files with some key; now you must distribute the decryption key with the executable so that it can read the files. OK, but now whoever extracts the text files can also extract the key...
4,603,205
4,604,395
boost::posix_time::ptime to UTC8601?
Is there a way to convert an object of type boost::posix_time::ptime to format UTC8601?
Depends what you mean by convert.. If you just want to see the ISO string, use std::string to_iso_string(ptime) or std::string to_iso_extended_string(ptime) or to pull out the date and time components as date and time_durations use: date d(ptime.date()) and time_duration td(ptime.time_of_day())
4,603,219
4,603,868
Const_cast on a this pointer - would I get told off by other C++ coders for doing this?
I have a class Game e.g. class Game { public: InitObjects(); ... }; And I have another class Grid, that needs to be initialised with a non-const reference to that Game object. ( A Grid object needs to call functions that can update a Game object ). class Grid { public: Grid(Game & g): ...
I have seen more horrible things in my time without casting at all. class A { private: A * non_const_this; public: A() : non_const_this( this ) { } void changesme(); // non-const void method() const { non_const_this->changesme(); } }; The above code I have given is "I am in a non-cons...
4,603,220
4,603,254
C++ template partial specialization error
The following code is giving me a compilation error: class Q64 is not a valid type for a template constant parameter template<int GRIDD, class T> INLINE T grid_residue(T amount) { T rem = amount%(GRIDD); if (rem > GRIDD/2) rem -= GRIDD; return rem; } template<int GRIDD, Q64> INLINE Q64 grid_residue(Q64 amount) ...
Functions cannot be partially specialized! Either use function overloading: template <int GRIDD> inline Q64 grid_residue(Q64 amount) or wrap your function in a type (which can be partially specialized).
4,603,271
4,603,295
C++ extern storage class life-span
I am a C++ newbie and come from a Java background. I would like to confirm the following: I am reading C++ by dissection by Ira Pohl and the book states that the life-span for a file/extern variable/function is the duration of the program (which makes sense because the variable is not declared in a class). What I wan...
A member variable in a class has a life-span corresponding to the life-span of the class's instances, unless declared static. struct Foo { int x; static int y; }; This Foo, and therefore its x, has program life-span: static Foo foo; This one is auto: int main() { Foo foo; } This one is dynamically allocated ...
4,603,331
4,603,428
Concise lists/vectors in C++
I'm currently translating an algorithm in Python to C++. This line EXCH_SYMBOL_SETS = [["i", "1", "l"], ["s", "5"], ["b", "8"], ["m", "n"]] is now vector<vector<char>> exch_symbols; vector<char> vector_1il; vector_1il.push_back('1'); vector_1il.push_back('i'); vector_1il.push_back('l'); vector...
I would refactor, instead of vector<char>, use std::string as internal, i.e. vector<string> exch_symbols; exch_symbols.push_back("1il"); exch_symbols.push_back("s5"); exch_symbols.push_back("b8"); exch_symbols.push_back("mn"); then change your insert method: void insert_all_exch_pairs(const vector<string>& exch_symbol...
4,603,500
4,604,553
How do I cover up old text when double buffering? - Win32 C++
I'm trying to rapidly update text using double buffering. I draw the text on top of a bitmap and blit it to the screen. But the text is never covered up as more is drawn, so before it's just an unreadable jumble of overwritten letters. Here is my double buffering routine: void PaintControlWindow() { HDC hdc,hdcMe...
I think Moo-Juice's comments is relevant is several ways that you should think about. But the root of your problem is fairly easy to explain. You have the right idea in general that is you should: Have the preloaded background in a DC (such as hdcMemory2) so that you don't have to keep reloading it. Copy that bitmap i...
4,603,717
4,603,746
Stopping function implicit conversion
I came across a strange situation today where I needed a function to not implicitly convert values. After some looking on google I found this http://www.devx.com/cplus/10MinuteSolution/37078/1954 But I thought it was a bit stupid to use a function overload for every other type I want to block so instead I did this. vo...
Use templates to get the desired effect: template <class T> void foo(const T& t); template <> void foo<int>(const int& t) { } int main(){ foo(9); // will compile foo(9.0); // will not compile return 0; } Note that we only write a special version of the template for int so that a call that has any other type a...
4,603,886
4,604,017
C++ operator lookup rules / Koenig lookup
While writing a test suite, I needed to provide an implementation of operator<<(std::ostream&... for Boost unit test to use. This worked: namespace theseus { namespace core { std::ostream& operator<<(std::ostream& ss, const PixelRGB& p) { return (ss << "PixelRGB(" << (int)p.r << "," << (int)p.g << "," << (i...
In argument dependent lookup (the correct name for koenig lookup) the compiler adds to the overloaded function set the functions which are declared in the namespaces of each parameter. In your case, the first operator<< is declared in the namespace thesus::core, which is the type of the argument you call the operator w...
4,604,130
4,604,386
C/C++ Bit Array or Bit Vector
I am learning C/C++ programming & have encountered the usage of 'Bit arrays' or 'Bit Vectors'. Am not able to understand their purpose? here are my doubts - Are they used as boolean flags? Can one use int arrays instead? (more memory of course, but..) What's this concept of Bit-Masking? If bit-masking is simple bit o...
I think you've got yourself confused between arrays and numbers, specifically what it means to manipulate binary numbers. I'll go about this by example. Say you have a number of error messages and you want to return them in a return value from a function. Now, you might label your errors 1,2,3,4... which makes sense to...
4,604,136
4,604,177
How to search for an element in an stl list?
Is there a find() function for list as there was in vector? Is there a way to do that in list?
You use std::find from <algorithm>, which works equally well for std::list and std::vector. std::vector does not have its own search/find function. #include <list> #include <algorithm> int main() { std::list<int> ilist; ilist.push_back(1); ilist.push_back(2); ilist.push_back(3); std::list<int>::it...
4,604,283
4,604,340
Automatic #defines according to Debug/Release config in Visual Studio
I have debug output in my program like this: #define DEBUG ... #ifdef DEBUG std::cout << "[RE_words] " << m_re << std::endl; #endif and DEBUG is defined in my program manually. I always comment out the line when I make a release version. In Visual Studio, there are also Configurations for Debug vs Release versions...
The Visual Studio automatically defines _DEBUG symbol for Debug builds (and NDEBUG for non-debug builds). Another way to do this is to go to the project settings -> configuration properties -> C/C++ -> preprocessor, and edit the preprocessor definitions manually. See also: This answer explains the differences between ...
4,604,860
4,604,899
C++ subclass that derives from classes that derive from the same class
Why is the following inheritance structure not legitimate in C++? Son1 derives from Father1 Son2 derives from Father1 GrandSon1 derives from Son1 and Son2 If there could be a case where this is legitimate (perhaps if all classes are pure-virtual except for GrandSon1), what are they and how come?
You are wrong, this is perfectly legal in C++. You might look into virtual inheritance though.
4,605,030
4,605,473
Will the cache line aligned memory allocation pay off?
I just know basic ideas on aligned memory allocation. But I didn't cared much about align issue because I am not an assembly programmer, also didn't have experience with MMX/SIMD. And I think this is the one of the the premature optimizations. These days people saying more and more about cache hit, cache coherent, opti...
Most of the discussions on cache line alignment deal with high-performance computing working with many threads, and keeping scalability as close to linear as possible. In those discussions the reason for cache line alignment is to prevent a write to one data variable invalidating the cache line that also contains anoth...
4,605,058
4,605,099
Static Const Initialised Structure Array in C++ Class
I understand if I want a const array in a class namespace in C++ I cannot do: class c { private: struct p { int a; int b; }; static const p pp[2]; }; const c::p pp[2] = { {1,1},{2,2} }; int main(void) { class c; return 0; } I must do: class c { public: struct p { int a; int b; }; ...
Your first code snippet works fine. You just need to change it to: const c::p c::pp[2] = { {1,1},{2,2} };
4,605,370
4,605,447
Storing local variable in std::map
I have a class Message and a class Cache. In Message::processMessage() fn. I create a instance of another class CacheRef(not shown below.) then I call Cache::cacheData(cacheRef) Now, in Cache class, I have a map which has its key as CacheReference. I store the ref that I passed to cacheData fn. in this map. class Messa...
Because the 1st template parameter is a CacheRef (and not a reference or pointer to a CacheRef) then ref will be copied into the map when you do the insert. Hence, you won't be storing a reference to a local stack variable. As long as there is an appropriate copy constructor or assignment operator for CacheRef then thi...
4,605,440
4,605,530
template partial specialization of static fields initialisation
I'm attempting something like the following: struct MyType { }; template <typename T> struct Test { static const MyType * const sm_object; }; template <> struct Test<void> { static const MyType * const sm_object; }; template <typename T> const MyType * const Test<T>::sm_object = new MyType(); template <> con...
Judging from g++ I think you need to remove the template<> from that line and put the remainder in just one source file (not in the header). Since it's a specialization it's just like a normal non-template static which you don't define in a header. In some .C file: const MyType * const Test<void>::sm_object = new MyTyp...
4,605,496
4,605,565
C++ vector being overwritten
I have I have objects with x, y, z coordinates and another parameter - energy. The energy of objects with the same x, y, z coordinates are to be summed up. I have seen a program how this can be implemented and followed the exact same approach, however, my program fails and I do not understand why. Outlined is the appro...
If I use co_ord[300][300][300], the program gives a segmentation fault. This is normal. Let's say you have int a[2]; it's an array of two elements, starting from zero (a[0], a[1]). a[2] would be the third element and accessing it results into undefined behavior. co_ord[-9][0][1] will cout -1, but on the second loo...
4,605,556
4,606,206
When virtual inheritance IS a good design?
EDIT3: Please be sure to clearly understand what I am asking before answering (there are EDIT2 and lots of comments around). There are (or were) many answers which clearly show misunderstanding of the question (I know that's also my fault, sorry for that) Hi, I've looked over the questions on virtual inheritance (class...
If you have an interface hierarchy and a corresponding implementation hierarchy, making the interface base classes virtual bases is necessary. E.g. struct IBasicInterface { virtual ~IBasicInterface() {} virtual void f() = 0; }; struct IExtendedInterface : virtual IBasicInterface { virtual ~IExtendedInterfa...
4,605,633
4,608,875
C++: converting a container to a container of different yet compatible type
It often happens to me to have a a container C (or whatever kind of wrapper class, even smart pointers) for a type T1, and want to convert such C<T1> into C<T2>, where T2 is compatible to T1. C++ doesn't allow me to directly convert the whole container, and forcing a reinterpet_cast would result in undefined behavior, ...
Besides all the other issues dealt by others: conversion does not imply same memory footprint (think conversion operations...) potential specializations of the template class (container in your question, but from the point of view of the compiler a container is just another template) even if the types are themselves b...
4,605,645
4,605,680
How to pass a std-functor in c++ and use it without knowing which one it is specifically
I have something like a sort-algorithm here, and I want to pass it a functor, which provides the sorting criteria (std::binary_function). So it should call T.operator<() for example if std::less is given. Problem is, the member function operator() is not virtual. So I need to know which type of object was given, to per...
Problem is, the member function operator() is not virtual. So I need to know which type of object was given, to perform a dynamic cast which is not really nice. Why do you want to perform a dynamic cast? Normally you don’t need that. Just call the functor’s operator() just like you would call a normal function. The w...
4,605,650
4,605,790
Convert 32 bits .def file to 64 bits
In my company we use .def files to specify the symbols that need to be exported. (I wish I could use a more modern and automated technique, unfortunately, the guys who decide live back in the eighties). Writing a .def file by hand, using manual copy-paste is boring and error-prone but so far I can live with it. However...
I would probably __declspec(dllexport) the symbols I wanted, compile, and then run dumpbin /exports on the resulting DLL to get the mangled names, and then you can remove the __declspec and make a .def file.
4,605,842
4,605,893
How to identify platform/compiler from preprocessor macros?
I'm writing a cross-platform code, which should compile at linux, windows, Mac OS. On windows, I must support visual studio and mingw. There are some pieces of platform-specific code, which I should place in #ifdef .. #endif environment. For example, here I placed win32 specific code: #ifdef WIN32 #include <windows.h> ...
For Mac OS: #ifdef __APPLE__ For MingW on Windows: #ifdef __MINGW32__ For Linux: #ifdef __linux__ For other Windows compilers, check this thread and this for several other compilers and architectures.
4,606,295
5,244,760
MAX_PATH limitation in Boost.Filesystem
I want to use Boost.Filesystem library to manipulate paths, files and directories. My question is are paths longer than MAX_PATH supported? I know that in Win32API we have workaround "\\?\" but it's not supported by basic functions like PathAppend and PathCombine. So I'm looking for any useful info about MAX_PATH and B...
The truth is that Windows supports paths of any length, and any path can be converted to string on windows. Adding \\?\ is required in such case, but this is the part of "make a string out of a given path" operation. AFAIK, Boost::FileSystem does this wrong on windows. I do not know if a fix is planned. See this abou...
4,606,306
4,608,040
Performance testing utilities for C++
I was curious whether anyone has any suggestions for performance testing libraries and frontends that will produce nice graphical charts for C++ (like how gcov produces coverage data and there are frontends out there for viewing the code coverage data). Being able to produce charts like: http://download.eclipse.org/ec...
Some suggestions: The googletest C++ framework is capable of producing JUnit-compatible reports. Hudson can be used to run your tests. It only requires that your C++ application can be run as a console application. The Hudson Performance Plugin can generate graphical charts from JUnit reports. There are many other plu...
4,606,452
4,606,491
fastCGI application code structure
I am writing a fastCGI application using the fastCGI development kit on Linux (Ubuntu), using Apache 2.2 + mod_fcgid. According to the document, the correct code structure for an fastCGI app is: Initialization section, which is executed only once. Response loop section, which gets executed every time the FastCGI scrip...
This question looks related, and might help you.