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,357,109
4,357,117
OpenSSL establish connection between client and server
Im working on this assignment using Open SSL and C++. I need to establish a secure connection between a client and a server and then transfer a encrypted file. Could anyone give me any references (books, sites, ect) on where to set one up. Thanks a lot.
This should at least get you started: http://www.ibm.com/developerworks/linux/library/l-openssl.html Good luck!
4,357,163
5,706,887
#pragma pack won't compile?
I'm trying to compile some downloaded source which contains lots of: 142 #ifdef __cplusplus 143 #pragma pack(1) 144 #endif but I get the following error and it won't compile: src/globals.h:143:16: error: expected declaration before end of line mingw32-make: *** [obj/main.o] Error 1 I'm using a makefile downl...
While I have absolutely no idea why GCC picked on pragma pack to highlight it's issue the actual problem was that it was trying to compile a Version.h resource (Version resource information) as code. The compile was failing and just decided to spit out a completely irrelevant error.
4,357,267
4,357,287
mbstowcs_s is causing my program to crash
This is the relevant code: char c; size_t buffer_size = 0; wchar_t* wc = (wchar_t*) malloc(buffer_size); int result = recv(this->m_socket, &c, 1, 0); mbstowcs_s(&buffer_size, wc, buffer_size, &c, 1); // Something is wrong here How do I fix this?
You allocated 0 bytes for wc and passed that buffer to mbstowcs_s.
4,357,323
4,357,389
Stack object reinstantiation in C++
I would like to use the same variable but I want to reinstantiate it. How do I do it in c++? Here is a simple example. I try to reinstantiate t1 but it doesn't compile. (Notice t1 is stored in the stack. I'm not asking how to do dynamic memory allocation) class Table { private int feet; public Table(int x) { ...
The answer is a wonderful language feature called assignment. In short, you can change the value of a variable – even a variable of a type you have defined yourself – by using the = symbol. As a matter of fact your code is already using assignment, namely in the constructor. In the example below I've replaced that orig...
4,357,500
4,358,820
C++ Abstract Factory using templates
I'm trying to create an abstract factory template for multiple abstract factories in C++ and came up with this. #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #include <map> #include <stdio.h> class Base { public: virtual ~Base() {} virtual bool Get() = 0; }; class DerivedA : public Base { public: bool Ge...
The class DerivedCreator<DerivedA> is a Creator<DerivedA> not a Creator<Base>. You need to tell the derived template what the base type so it can implement the interface of Creator<Base> by creating an instance of the derived type: // DerivedCreator is Creator<BaseType> which creates a // DerivedType, not a Creator<De...
4,357,719
4,357,741
Is it okay to manually throw an std::bad_alloc?
I have this code.. CEngineLayer::CEngineLayer(void) { // Incoming creation of layers. Wrapping all of this in a try/catch block is // not helpful if logging of errors will happen. logger = new (std::nothrow) CLogger(this); if(logger == 0) { std::bad_alloc exception; throw exception; ...
You don't need to do that. You can use the parameterless form of the throw statement to catch the std::bad_alloc exception, log it, then rethrow it: logger = new CLogger(this); try { videoLayer = new CVideoLayer(this); } catch (std::bad_alloc&) { logger->log("Not enough memory to create the video layer."); ...
4,357,854
4,357,873
C++ template compilation error - recursive type or function dependency
I wrote a template class which is giving compilation error template<class T> class Entity { string EntityName; int EntitySize; Entity<T*> pPrev; Entity<T*> pNext; public: Entity<T>(const string & name, int size) { EntityName = name; EntitySize = size; } //member function...
Alright. I'm explaining you the problem you're facing. But first thing first. You said: I wrote a template class which is giving compilation error First of all, as far as C++ is concerned, there is no such thing as a "template class," there is only a "class template." The way to read that phrase is "a template for ...
4,357,955
4,358,202
Starting a thread on pushbutton
How would I make sure to create only a single thread on pushbutton without being accidently double-clicked?
The following code should do it (Under win32) ... EnterCriticalSection( &critSec ); if ( ghThread != INVALID_HANDLE_VALUE ) { ghThread = ::CreateThread( NULL, stackSize, (LPTHREAD_START_ROUTINE)ThreadEntry, NULL, 0, NULL ); } LeaveCriticalSection( &critSec ); This does of course assume you initialise the ghThre...
4,357,997
4,358,027
How can I access the wchar_t of a wchar_t*?
This is my code: wchar_t wbuffer[512]; wchar_t* wc = (wchar_t*) malloc(buffer_size); int buflen = 0; // ... stuff // inside the while loop wbuffer[buflen] = (wchar_t)wc; what is wrong with this?
Dereference wc within your loop. wbuffer[buflen] = *wc;
4,358,089
4,358,116
C++ STL Containers and pointer validity
Consider this piece of code: Uint counter = 0; int* p1; int* p2; deque<int> dequeInstance; vector<int> vectorInstance; dequeInstance.push_back(3); dequeInstance.push_back(7); p1 = &dequeInstance.back(); dequeInstance.push_back(17); p2 = &dequeInstance.back(); if(*p1 == !7) ++counter; if(*p2 == !17) ++c...
Hopefully for performance, std::vector is not 'wiped and recreated every time it's modified'. A vector has a capacity which may exceed its size, which means that it can allocate more memory than truly used. When you push_back, a reallocation will only occur if the new size is greater than the old capacity, and in this ...
4,358,196
4,358,372
Where does rend point to?
To support STL's notion of half-open ranges, we are allowed to point one-past-the-end of an array. Suppose we have a vector of three elements. If std::vector::iterator is implemented as a pointer, as is usually the case in release builds, then begin and end point to these locations: +---+---+---+.... | | | ...
There is a difference between what a reverse_iterator points to logically and what its contained iterator points to. Logically, rbegin yields an iterator that points to the last element of the sequence and rend yields an iterator that points to one element before the start. But this is usually implemented with a base i...
4,358,258
4,358,276
Picture entropy calculation
I've run into some nasty problem with my recorder. Some people are still using it with analog tuners, and analog tuners have a tendency to spit out 'snow' if there is no signal present. The Problem is that when noise is fed into the encoder, it goes completely crazy and first consumes all CPU then ultimately freezes. S...
PNG works this way (approximately): For each pixel, replace its value by the value that it had minus the value of the pixel left to it. Do this from right to left. Then you can calculate the entropy (bits per character) by making a table of how often which value appears now, making relative values out of these absolute...
4,358,284
4,358,782
libpcap: how to get active network interface (Mac OSX)
I am using libpcap to sniff traffic. I would like to do it on the currently active network device (e.g. one that has an assigned IP address, etc). What's the best way to do this? I'm assuming I would have to do the following: pcap_findalldevs(&alldevs, errbuf) to get all the network devices, then loop through and chec...
the API pcap has for looking up interfaces conforming to some user defined rules is trivial. You could indeed use pcap_findalldevs() to interate over all suitable-to-use network devices or use pcap_lookupdev() to get the next network device that you can use with pcap. Defining what is the interface you want to use with...
4,358,304
4,358,309
Unable to Find an Entry Point (cpp)
This is a similar question to this one. I want to export a simple function from C++, to be called by C# via PInvoke. This is my function definition: int fnValue() { return 42; } And this is the export definition in .h file: __declspec(dllexport) int fnValue(); This is how I PInvoke the function: [DllImport(...
Try to write extern "C"__declspec(dllexport) int fnValue();
4,358,387
4,890,248
PDcurses displaying question marks in place of intended character
Ive got a problem with PDcurses displaying some symbols as ? instead of the proper character. I made a little test program to display code page 437 to determine which symbols were working and which werent. Strangely, when I turned off PDcurses the problem symbols displayed correctly. The problem symbols are Çéâäàåçêëèï...
I came back and solved this one after a while. Turns out I was using the wrong version of PDcurses. From the ones available http://sourceforge.net/projects/pdcurses/files/pdcurses/3.4/ I was using pdc34dllw. I switched to pdc34dll and now it works perfectly.
4,358,422
4,358,464
How to enable a shared object accessing a data file in runtime (UNIX)
I have a class method (implemented in a shared object in UNIX environment) which needs to access a text data file in runtime (using ifstream). Currently the method assumes that the data file is available for opening without any relative path, i.e something like ifstream dataFile("data.txt"); The shared object is loade...
The proper way to go about this is to make the location of the text file a configurable value that will be set when your project is installed. Using a configuration file in /etc/ is a common way to store that value. That way you can put the text file in e.g. /usr/share/ with all the machine-independent files (that data...
4,358,494
4,358,858
Export std::Vector Member in a Class
I want to export a C++ class, which has a member std::vector<int>. How to export this class so that my C# application can consume it? And how to write the corresponding .Net code? This is what I tried so far, following the examples given here. #include <vector> # define BOOSTGRAPH_API __declspec(dllexport) # define E...
What are you trying to do? I see BOOST_GRAPH_API, what are you up to? You will not be able to use native C++ code from .Net directly, neither you should! That would force you to compile all imported dependencies on C++ standard library and boost(!) with clr support... You need to define interfaces to your classes along...
4,358,575
4,358,933
How to send text to an application?
I am trying to make an application, which reads the data from a serial port (on the serial port there is a barcode scanner plugged in), and then forwards it to an application. I can read data from serial port now, but i don't know, how to forward the read text, to an application, for example notepad. I tried to use Sen...
Sounds like you're looking for keybd_event or the newer SendInput. It allows you to simulate keyboard input.
4,358,870
4,359,056
Convert wstring to string encoded in UTF-8
I need to convert between wstring and string. I figured out, that using codecvt facet should do the trick, but it doesn't seem to work for utf-8 locale. My idea is, that when I read utf-8 encoded file to chars, one utf-8 character is read into two normal characters (which is how utf-8 works). I'd like to create this ut...
C++ has no idea of Unicode. Use an external library such as ICU (UnicodeString class) or Qt (QString class), both support Unicode, including UTF-8.
4,358,975
4,359,054
C++ / Arduino: dynamic int array
I'm writing a class for the Arduino. It's been going well so far, but I'm sort of stuck now... I have declared an int array in my class class myClass { public: MyClass(int size); private: int _intArray[]; }; When I initialize the class MyClass myClass1(5) I need the array to look like this {0,0,0,0,0}. My que...
Your code as I'm writing this: class myClass { public: MyClass(int size); private: int _intArray[]; }; The declaration of _intArray is not valid C++: a raw array needs to have a size specified at compile time. You can instead instead use a std::vector: class myClass { public: MyClass( int size ) : ...
4,359,186
4,359,212
Factoring large numbers
Possible Duplicate: Factor a large number efficiently with gmp I know I already posted it, but people misunderstood what I meant, and until I fixed it the post died. What I need is a way to efficiently factor(find prime factors of a number) large numbers(may get to 2048 bits) using C++ and GMP(Gnu Multiple Precessio...
Have you tried the quadratic sieve or the general number field sieve? (QS simpler and easier to implement, GNFS faster for very large numbers, but your numbers may not be large enough for GNFS to be much faster than QS) edit: According to a paper by Eric Landquist, the crossover point between QS and GNFS is about 110 d...
4,359,202
4,359,223
Converting some c++ array code to c#
I'm having some trouble converting the following code from c++ to c# because of pointers. Basically I have a STATE** State; States = new STATE* [max_states]; for (int i=0; i < max_states; i++) { States[i] = new STATE(max_symbols); } If this was some double array I would say STATE[][] States; States = new STATE[...
it is not a 2d-array, but a 1d-array containing pointers to single elements... new STATE(max_symbols) constructs a single STATE object, calling the constructor which takes a single argument (in this case max_symbols). i dont have that much clue of C#, but the following should be the correct representation of the C++ c...
4,359,314
4,359,461
Why QTreeView does not show the data?
I have a trouble with QTreeView. When I run this code ui->treeView does not show the data: QStandardItemModel paramList; QStandardItem itemroot("cats"); QStandardItem item1("cats"); QStandardItem item2("dogs"); QStandardItem item3("rats"); itemroot.setChild(0,&item1); itemroot.setChild(1,&item2); itemroot.setChild(2,&i...
in the header (private): QStandardItemModel paramList; in the .cpp ui->treeView->setModel(&paramList); QStandardItem *itemroot = new QStandardItem("cats"); QStandardItem *item1 = new QStandardItem("cats"); QStandardItem *item2 = new QStandardItem("dogs"); QStandardItem *item3 = new QStandardItem("rats"); itemroot->set...
4,359,319
4,359,537
Optimize function to write bits to file
Here is a function that writes n bits to a binary file. Parameters: Data : Bit sequence to be written to file (lsb on the right) Length: Number of bits to write OutFile: Destination file. First version of the funcion: void WriteBitsToFile(unsigned long long Data, unsigned Length, std::ofstream & OutFile) { stati...
I would start with removing static variables from your function body. They are a bit slower as should test their state (already initialized or not) on every function call. Just move them out of function scope. Why do you use such short buffer? Are you sure you need to write every unsigned long long into the file? I wo...
4,359,436
4,359,589
How to connect a Windows Service to the Console session
I've been developing a remote desktop application which runs as a Windows service, and I was wondering how I could connect the application to a specific session, and allow it to retrieve the user's desktop as a bitmap, set the cursor position, send mouse clicks, and keyboard input to the console session.
You need to use SetThreadDesktop() to change the thread's context in your service to the user's desktop. SetThreadDesktop() takes a handle to the desktop as it's first parameter; to get that handle, use EnumDesktops(). EnumDesktops() takes a handle to the window station as it's first parameter; to get that hand...
4,359,452
4,359,485
QT - pointer to QColor works direct access don't
I got following issue: That's work: #include <QtCore/QCoreApplication> #include <QColor> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QColor *c = new QColor(); c->setRgb(12,123,13); return a.exec(); } but this don't: #include <QtCore/QCoreApplication> #include <QColor> int main(in...
This QColor c(); is a function declaration. Change it to QColor c; That's a possible duplicate of hundreds of similar questions....
4,359,473
4,359,530
how to fix error in std::vector<int> WidthNumbers = 320, 640, 1280;?
So I try to do something like std::vector<int> WidthNumbers = 320, 640, 1280; but compiler gives me error C2440: 'int' to 'std::vector<_Ty>'
You cannot initialize a vector using that syntax. C++0x allows initializer lists which allow you to use the following: std::vector<int> WidthNumbers = {320, 640, 1280}; But this has not been implemented in VS2010. The alternatives are: int myArr[] = {320, 640, 1280}; std::vector<int> WidthNumbers( myArr, myArr + sizeo...
4,359,587
4,359,628
Problem sorting a list of pointers
i am trying to sort a list of pointers (in my case each pointer is of type Job) my intention is to sort the jobs by their serial number void Container::jobSort(list<Job*> &jobs) { sort(jobs.begin(), jobs.end(), jobSerialCompare); } bool Container::jobSerialCompare(const Job *jobA,const Job *jobB) { return (jo...
The error message says it all. You are trying to sort a list with a sort() that expects a random access iterators. List supports only bidirectional iterators, so the stand-alone sort() doesn't work. That's why you must use a specific algorithms for lists: list.sort(); Also others spotted the non-static comparator issue...
4,359,657
4,359,754
deploying imagemagick application using qt
I have create an application that makes use of the ImagemMagick library. I have succesfully installed the library on my mac and I was able to use it inside my application. My .pro file Include path and library looks like that: INCLUDEPATH += . /opt/local/include/ImageMagick LIBS += -L/opt/local/lib -lMagick++ I would ...
I'd recommend reading the qt docs about deployment on different platforms: http://doc.qt.io/archives/qt-4.7/deployment-windows.html http://doc.qt.io/archives/qt-4.7/deployment-mac.html http://doc.qt.io/archives/qt-4.7/deployment-x11.html They basically describe in detail how to deploy dynamically linked libraries with ...
4,359,666
4,508,046
Stop Intellisense display timeout
I'm using VS 2010 Ultimate for C++ coding, with no changes to any settings. If I type MyClass-> Intellisense shows popup list of MyClass members. Initially the first item in the popup is highlighted, but I can single-click to move the highlight. A "child" popup to the right of the highlighted item shows the function d...
The answer is in Microsoft Connect: http://connect.microsoft.com/VisualStudio/feedback/details/328852/tooltips-in-intellisense-disappear-unwantedly Posted by Microsoft on 4/26/2010 at 3:38 PM Hi TimwiTerby, As Sean wrote in his previous comment, this was postponed so that we could consider it for a future version of V...
4,359,706
4,359,808
What's the purpose of: "using namespace"?
There are convincing arguments against using namespace std, so why was it introduced into the language at all? Doesn't using namespace defeat the purpose of namespaces? Why would I ever want to write using namespace? Is there any problem I am not aware of that is solved elegantly by using namespace, maybe in the lines...
For one thing, this is the way to use operator overloads in a namespace (e.g using namespace std::rel_ops; or using namespace boost::assign;) Brevity is also a strong argument. Would you really enjoy typing and reading std::placeholders::_1 instead of _1? Also, when you write code in functional style, you'll be using a...
4,359,720
4,365,306
How to use NDK in android project?
I need to use some native c/c++ in my project, so I need to use the NDK. Is there an easy way to set it up in eclipse? Thanks.
Ok, after I spent some time experimenting, I can say that the best way for a beginner to start using NDK in eclipse is first to go over this tutorial: http://marakana.com/forums/android/examples/49.html and simply create the necessary files for the jni folder (but don't do anything else). Then you should read this http...
4,359,859
4,742,119
can linker omit object file when linking static lib?
I have a static library (lib.a) and a program that links to it. The library doesn't have any entry point that would always be called before using it, but I need to execute a piece of code very early in the program (preferably before main() starts). Therefore I thought I would use static variable of my own class. I adde...
It turns out that what the linker does is pretty standard (I don't mean C++ standard, just generally observer behaviour) and you can work around it. In GNU ld it is --whole-archive option, in my case of Sun tools it is -z allextract. Which didn't actually work as expected for my project, so I used some magic with weak ...
4,360,041
4,361,107
Game Collision-Handling
The code given is for example purposes, not copypasta from my codebase I'm writing a primitive, cross-platform Snake game in C++ with Boost & SDL, and I'm wondering what the best way to implement collision-handling is (not collision-detection). So far, I've been using a single-dispatch idea, with ugly spaghetti code, l...
Collision handling is an area where C++/Java-style object orientation (with single dispatch) is not flexible enough. The result of a collision depends on the types of both colliding objects, so you need multiple dispatch to handle it. (It's no coincidence that the motivating example on Wikipedia's multiple dispatch art...
4,360,254
4,360,275
bool and C/C++ interoperability
When I write a function in C, which may also prove useful in a C++ context, shall I use the bool macro or not? Could that lead to compatibility issues, at C and C++ both define a bool type (well, C befines _Bool, but you know what I mean :-))?
Why not use int? It is always properly supported. The only reason to use bool would be if you knew for sure that your code would be used only in modern C and C++ environments. But if there was any chance it would have to run on some old legacy compiler, perhaps for an obscure embedded processor, someone would have to...
4,360,348
4,360,365
How to find nearest even number for given int? (given 11 return 12)
So how to create a function to return nearest up so nearest to 9 9+ 1 to given int leaving no remainder when divided by 2 int?
"Nearest" is ambiguous when given an integer. Take, say, 9: both 8 and 10 are even, and are equally near to it. If you want to always go up, then something like... int nearestEvenInt(int to) { return (to % 2 == 0) ? to : (to + 1); }
4,360,606
4,361,117
SetWindowsHookEx process-wide instead of system-wide
I'd like to use SetWindowHookEx to catch WM_CREATE (or HCBT_CREATEWND) messages in a process before a creation of a window. Using the hMod and dwThreadId it is possible to define whether the hook will be system-wide (by setting hMod to be the gInstance of the DLL and dwThreadId to 0), it is also possible to use it to m...
It is very unusual for a process to create more than one thread that owns a UI window. Sometimes it is a interop window which is intentionally hidden, unlikely that you'd want to know about it. Verify your assumptions with Spy++, the owner thread ID is shown in the window properties, Process tab. If it does have more...
4,360,617
4,360,782
How can I get nm to show the return types of a function?
I'm trying to write a script to produce a 'fake' version of a huge and messy code library, I thought using 'nm' on the binary and filtering just the text symbols might be the way to go, but I can't seem to get nm to display the return type of the function as well as the signature. Many thanks in advance.
The return type of the function is not part of the name mangling. Return types are enforced by the compiler directly based on type rules. It is possible to call a function defined as, for example, returning int, and having a declaration for it returning, say char. Most tools will not notice the mismatch. Considering...
4,361,095
4,362,347
PKG_CHECK_MODULES for somelib++
I am trying to make my autotools project in C++ link against library, that originates as C library (libsomelib.so), but also has bindings to c++ (libsomelib++.so). I ma trying to use PKG_CHECK_MODULES to check if this package is installed, and use autotools to link against it. However both libs come in one package (c++...
Yes, the missing ++.pc usually hints towards an omission on behalf of the packager. BTW: If simple (DCE) UUIDs are sufficient, you could consider e2fsprogs/util-linux's libuuid (in case you run this OS).
4,361,101
4,361,128
how can i change eclipse from "c/c++" to "java" enviorment?
I did the opposite by mistake and now i can't go back to the java enviorment. anyoune knows how? thanks.
There should be a button in the top right corner for changing perspectives. You can also get to it through the Window > Open Perspective menu.
4,361,202
4,361,241
try / catch block fails and application crashes
I have the following code try { clientService.sin_family = AF_INET; clientService.sin_addr = *((LPIN_ADDR)*hostEntry->h_addr_list); //fails clientService.sin_port = htons(port); } catch (...) { return; } If I disable my network adapter, my application crashes. Isn't such errors supposed to be caught?...
It's just a guess but you probably haven't checked hostEntry after gethostbyname returned and you got a NULL-pointer. Check it if it's null before using it.
4,361,335
4,361,518
QTextStream and Visual Studio 2008 release mode
I have a simple code using QTextStream and it works very fine in visual studio in debug mode, but if I put it in release mode it doesnt read anything from the file. I included QtCore4.lib for the release mode and for the debug mode QtCored4.lib. Im using Qt4.6.3 vs2008,what could be the problem if it works in debug mod...
That's because you put code with side-effects into an assert: assert(qfile.open( QIODevice::ReadOnly | QIODevice::Text)); This code is never executed in release mode. Not only are assertions disabled, also the code inside them is not executed! Rule: Never put anything with side-effects inside an assert(). This is the ...
4,361,371
4,361,400
Copy constructor not called when using boost::bind, boost::shared_ptr, and boost::thread together
I am creating a new boost::thread using boost::bind, and storing it in a boost::shared_ptr. I am passing a function and argument to the boost::thread, but when the thread is started, it does not correctly call the copy constructor for the function argument. The thread creation method I'm using is a very common Boost ...
It seems your copy constructor is flawed. You're copying from your empty vector to your vector. Which results in nothing being copied. I think you mean: for (it = (workflow->_tasks).begin(); it < (workflow->_tasks).end(); it++) (this->_tasks).push_back(*it);
4,361,541
4,361,566
C++ - Error E2285 : Could not find a match for 'tolower(char *)' in function parseInput(fstream &)
Given the following code: void parseInput(fstream &inputFile) { const int LENGTH = 81; char line[LENGTH]; while(!inputFile.fail()) { inputFile.getline(line,LENGTH); line = tolower(line); cout << line << endl; } } upon compiling I'm getting this ...
You can simply perform the following loop to convert a string, character-by-character, to lower case: const int lineLen = strlen( line ); for ( int i = 0; i < lineLen; i++ ) { line[i] = static_cast< char >( ::tolower( static_cast< unsigned char >( line[i] ) ) ); } Edit: furthermore the following code is even ...
4,361,584
4,361,721
Error while trying to run a release build of a Qt application on Windows
I'm trying to build the Windows version of my app. The program compiles and runs fine on Qt Creator but when I try to run it standalone it throws the following error: The procedure entry point _Z17qt_message_output9QtMsgTypePKc could not be located in the dynamic link library QtCore4.dll I have all the necessary dlls ...
Ok I found the problem. I was copying the wrosng dll (not sure why Qt ships with 2 different versions). The right ones are in:C:\Qt\2010.05\qt\bin and NOT in C:\Qt\2010.05\bin I hope this helps anyone who might stumble upon this issue.
4,361,769
4,361,834
C++ builder how to configure compiler to output just exe?
the question is how to configure in c++ builder 2010 compiler and debug option to output just one exe file, and all the other inside of that, so that i can easily use program on other maschine without installing them, with just runing exe file.
With all versions of C++Builder you don't need to make an installer for this, (although inno setup is simply brilliant if you do require one). Just select the following project options:- Project/Packages:, Build with Runtime Packages = DISABLED C++/Linker: Dynamic RTL = FALSE That's it. You will get a single exe with...
4,361,780
4,361,798
Link Error C++ Inheritance
I have two classes Person and Student. I'm currently trying to derive the Student class from the Person Class. However, I keep getting a link error. The error: [Linker error] undefined reference to `Person::Person()' My code: #include <iostream> #include <iomanip> using namespace std; class Person { string Nam...
You've declared a default constructor for Person: public: Person(void); But never defined it. In this case, you don't need to have your own default constructor - remove the declaration and let the compiler generate a default for you. Alternatively, you can define a do-nothing: Person::Person() { }
4,361,804
4,361,818
C++ string literals vs. const strings
I know that string literals in C/C++ have static storage duration, meaning that they live "forever", i.e. as long as the program runs. Thus, if I have a function that is being called very frequently and uses a string literal like so: void foo(int val) { std::stringstream s; s << val; lbl->set_label("Value: ...
Your program operates on the same literal every time. There is no more efficient form of storage. A std::string would be constructed, duplicated on the heap, then freed every time the function runs, which would be a total waste.
4,361,926
4,362,072
Why is the "gptr" type of basic_streambuf char_type* rather than const char_type*?
The basic_streambuf member to set the three "gptrs" of the streambuf, setg, is declared as: protected: void setg(char_type *gback, char_type *gptr, char_type *egptr); I am wondering: why was the type of each gptr made char_type* instead of const char_type*? Is it safe to use const_cast here to use const char pointer...
It's not const because the streambuf interface doesn't know how you're populating the buffer. For example the underflow and uflow methods may pull n bytes from a file or similar and populate the extant buffer of the streambuf. You may also be using the same storage for the buffers for a read/write stream stream. The st...
4,362,019
4,641,998
C++ unit test framework again
I have been looking for specific properties from a unit test framework in c++ but I have struggled find all of the following properties in a framework: Creation of Stubs (only in c++test). Has Code-Coverage tool (only in c++test). VS integration (Common enough) Fixtures (very common in most c++ frame works) Integratio...
GoogleMock from Google or Isolator++ from Typemock. Isolator++ is a mocking framework which works with several UT frameworks. You don't need that as part of a UT framework (you can instrument binaries and get coverage in VS). Isolator++ has VS integration AFAIK. Like you are saying this is very common, so it will be h...
4,362,186
4,366,510
C++ Meshes getting animated when they are not suppose too
I have two meshes. One of them is animated and the other one is not animated. When i render them the inanimate mesh gets animated the same way the animated mesh is animating. So, let just the animated mesh goes to left than comes back, my inanimate mesh does the same thing! This is my code class for the inanimate mes...
The anination comes from a transformation matrix. You either pass that directly to the device (if using fixed function) or to a shader/effect. All meshes you draw after the matrix has been set will undergo the same transform. So, if you want to have one mesh stay inanimate you have to change the transform before drawin...
4,362,198
4,362,329
Why does the compiler not see this function header?
My function header is this: void FileIO::write(LinkedList<Librarian>& librarians, int numlibrarians, LinkedList<Patron>& patrons, int numpatrons, LinkedList<LinkedList<Item> >[] items, int numitems, int currid) The header in my .h is this: void write(LinkedList<...
This is C++ so LinkedList<LinkedList<Item> >[] items doesn't make sense since this is a Java construct. Actually the parser is bombing out early somehow thinking the [] is some token which is indeed odd. Replace with LinkedList<LinkedList<Item> > items[] and you should be good.
4,362,202
4,362,227
C++ Homework - Binary Search Tree Help
For starters this is homework, I just really need help with a binary search tree. The program is to display polymorphism, using person as an abstract base class, and other types of people which inherit Person. Each person has a last name, and I am trying to use a binary search tree to alphabetize the people by last nam...
You omitted the return type on some of your function definitions. For example: template <class T> BST<T>::traverse() { traverseAux(root); } should be: template <class T> void BST<T>::traverse() { traverseAux(root); }
4,362,229
4,362,246
How can I use SimpleIni to return wchar_t and then convert to std::wstring?
SimpleIni Documentation says wchar_t is supported but I don't understand how to use it. This is what I tried: CSimpleIniCaseW ini; ini.LoadFile("myapp.ini"); std::wstring test(ini.GetValue("testsection", "testkey", "")); error C2664: 'CSimpleIniTempl::GetValue' : cannot convert parameter 1 from 'const char [12]...
You need to specify your strings as L"testsection" << Note the L.
4,362,354
4,362,422
C++ - Alphabetizing Strings - '<' Operator Overload
For starters this is homework, I have a good understanding of what i'm supposed to do but I am obviously missing something. I currently have an abstract base class called "Person". And I have 3 classes that inherit person they are Staff, Faculty, and Student. I am trying to organize all the "Person's" names by last nam...
The error you get probably occurs when you try to call the operator on a const object. The compiler doesn't know that operator< doesn't change the object it is called on and therefore gives an error. To ensure that the function doesn't change the object, declare the function as const: bool operator < ( const Faculty &r...
4,362,393
4,373,115
comparing bits (one position at a time)
Initially I have user input decimal numbers (0 - 15), and I will turn that into binary numbers. Say these numbers are written into a text file, as shown in the picture. These numbers are arranged by the numbers of 1's. The dash - is used to separate different groups of 1. I have to read this file, and compare strings...
I don't understand your code snippet -- it looks like all it does is read in the input file into a vector of strings, which will then contain each whitespace-delimited word in a separate string, then write it back out in 2 different ways (once with words separated by \n, once with them separated by spaces). It seems th...
4,362,402
13,342,454
what is wrong with c++ streams when using boost.python?
Update 2: I'm not sure why this is still being upvoted (March 2014). This appears to be fixed since I asked this question many years ago. Make sure you're using a recent version of boost. UPDATE: Perhaps C++ streams need to be initialized in order to format numbers, and the initialization is not happening when the s...
I also run into this problem a while ago, using self_ns as outlined in the answers here Build problems when adding `__str__` method to Boost Python C++ class The reason for using self_ns is explained by Dave himself here http://mail.python.org/pipermail/cplusplus-sig/2004-February/006496.html Just for the sake of debu...
4,362,482
4,363,756
How can I print multiple values of the same key from SimpleIni
The ini file: user = abc user = def user = ghi user = xyz The code: CSimpleIniCaseW ini; ini.SetUnicode(); ini.LoadFile("myapp.ini"); CSimpleIniCaseW::TNamesDepend values; ini.GetAllValues(L"", L"user", values); values.sort(CSimpleIniCaseW::Entry::LoadOrder()); CSimpleIniCaseW::TNamesDepend::const_iterator i; for (...
You have to enable multi-key first. http://code.jellycan.com/simpleini-doc/html/class_c_simple_ini_templ.html#c3cfaf072a64f960bdcb7ddf2edc52b6 CSimpleIniCaseW ini; ini.SetUnicode(); ini.SetMultiKey() ...
4,362,501
4,366,797
Any good reason why assignment operator isn't a sequence point?
Is there any good reason for operator = not being a sequence point? Both in C and C++. I have trouble thinking about an counter-example.
By request: In general, things need a reason to be a sequence point. They don't need a reason not to be a sequence point; that's the default. For example, && must be a sequence point because of short-circuiting behaviour: if the left-hand side is false, the right-hand side must not be evaluated. (This is not just about...
4,362,525
4,362,543
About recv and the read buffer - C Berkeley Sockets
I am using berkeley sockets and TCP (SOCK_STREAM sockets). The process is: I connect to a remote address. I send a message to it. I receive a message from it. Imagine I am using the following buffer: char recv_buffer[3000]; recv(socket, recv_buffer, 3000, 0); Questions are: How can I know if after calling recv firs...
How can I know if after calling recv first time the read buffer is empty or not? If it's not empty I would have to call recv again, but if I do that when it's empty I would have it blocking for much time. You can use the select or poll system calls along with your socket descriptor to tell if there is data ...
4,362,604
4,363,322
_Expand versus new versus GNU
Recently, I made a new friend. His name is _expand, and we've had some nice conversations, and I've even hung out with him a few times. But when I started asking around, no one had ever heard of my _expand. I became suspicious. I called a few thoroughly non-metaphorical friends at microsoft, and a few friends elsew...
That C++ has been getting by with new and delete sans any equivalent of realloc shows how little attention these things get. Unsurprising _expand is largely ignored when it's not even consistently available at the OS level. If you want to roll your own, there's plenty of precedent for user-defined versions of malloc,...
4,362,680
4,362,699
C++ unresolved external symbol
I have a class setup and from that class I am using inheritance. In file a.h class a { public: virtual void print(); }; In file b.h: #include "a.h" #include <iostream> class b: public a { public: void print(); }; And in b.cpp #include "a.h" #include "b.h" void b::print(){}; In the main file I am including bo...
You have an implementation for b::print but not for a::print. What would happen if instantiated an object of class a and called print() on it? i.e. a o; o.print(); b::print overrides a::print but you still need to have an implementation of a::print (unless you make it pure virtual). to make print pure virtual in a, de...
4,362,831
4,363,456
Scoped using-directive within a struct/class declaration?
I find that my C++ header files are quite hard to read (and really tedious to type) with all the fully-qualified types (which goes as deep as 4 nested namespaces). This is the question (all the answers give messy alternatives to implementing it, but that's not the question): Is there a strong reason against introducing...
Given that using declarations at class scope are not inherited, this could work. The name would only be valid inside that class declaration, or inside the declarations of nested classes. But I think it's sort of overloading the concept of a class with an idea that should be larger. In Java and Python individual files...
4,363,009
4,364,581
C++ - Noob Binary File IO question
I am currently trying to read in names from an input file. The file is a .dat file. I can read in the data using: student_struct s; string fileName; fstream inFile; inFile.open(fileName, ios::in | ios::binary); inFile.read(reinterpret_cast<char*>(&s),sizeof(Student)); This all works fine... But ...
Reading your file this way will work only for struct having no pointers at all - just plain variable types. That means you can not store even a table there (eg. char *). If your Student structure is more complex, you should have some kind of protocol saying how is your file organized. For example, you can use one or tw...
4,363,102
4,364,160
MinGW not recognised through path variable
Eclipse CDT in Windows 7 is showing warnings like this: Error launching external scanner info generator (g++ -E -P -v -dD C:/Users/User/workspace/.metadata/.plugins/org.eclipse.cdt.make.core/specs.cpp) So I already set the path environment variable to C:\MinGW\bin, but if i type gcc --version in cmd the command is not...
You can type "path" in the cmd window in order to see the path that's in effect (make sure you appended a value to the path variable and didn't replace it entirely, no spaces, etc.) If opening a new cmd or reboot doesn't help, you can use process monitor with a filter of "process name is cmd.exe" to see where exactly c...
4,363,167
4,363,208
Marshaling C++ int* to C#
I am trying to get a dll to work. The DLL is written in C++, and it needs to pass int* to C#. I spent passed few days to get this to work, and it fails. I am starting to pull my hair out because I can not figure out what is wrong. I have tried everything. I am not as familiar with C++ as I am with C#, so problem might...
The C++ code contains an error: you are returning a pointer to a variable stored on the stack (t[128] is only a temporary variable), which will not work. As soon as your encryptFunc returns, the call stack will be unwound and the variable t[128] will be trashed. If your code needs not be re-entrant or thread safe, you ...
4,363,180
4,363,273
quick sort and merge sort
Hey can someone tell me the basic algorithm for each and the tracing sequence for each. i'm confused there are many ways to it online and i don't really know which is the easiest/smartest. thanks.
Fundamentally, quicksort is a top-down approach while mergesort is a bottom-up approach. In quicksort, we select a "pivot" or "partition" value, and partition the list into two "halves" (not always exactly half, but the closer to half the better) - those less-than the pivot and those greater. We then recurse on those t...
4,363,282
4,363,504
Box2D (C++) Gravity Wells
Currently I am using the Box2D physics engine in a game of mine - and I was wondering if I could create a gravity well of sorts, in which all the bodies are attracted to a single arbitrary point. Is there a certain way to do this, or will i have to apply a custom force of sorts to each body? (I tried making a static su...
This functionality isn't built into Box2D unfortunately. The easiest thing to do is get the angle and the distance between the gravity well and the rigid body and set the bodies velocity accordingly. To get the angle: double dx = rigidBodyX - gravityWellX; double dy = rigidBodyY - gravityWellY; double angle = atan2(dy,...
4,363,308
4,363,452
Memory release issue in C++
We have code similar to the one below. We are trying to achieve RAII using a class called MemRelease class. Now, FXOMemRelease is being used the way shown in sample.cc. Is this OK to use the obeject of FXOMemRelase like that ? Most of the time I see that the destructor for MemRelease only gets called after Make...
Most of the time I see that the destructor for MemRelease only gets called after MakeString() is completed. That is fine. Will it be the case always ? Yes, always. The temporary object stays valid until the assignment to newstr completes. As afriza points out, we can't verify which destruction code is running becau...
4,363,318
4,363,351
Making a member function a friend
What happens when you make a member function of a class a friend of itself!? The code below compiles and runs. Without the friend declaration a 'too many arguments to operator' is generated (and rightly so). I realise that doing this doesn't make any sense but can anyone tell me what is happening here? Does friend forc...
The difference is that a friend is not a member even if the entire definition appears inside the class; rather, the function is placed in the surrounding namespace. So, there is no this pointer. While a member operator< operates implicitly on this and the explicit right-hand-side argument, a friend needs both left- a...
4,363,465
4,365,505
How to invalidate an iterator?
Since I know an iterator in the program could be invalidated by some previous operation, I want to invalidate it explicitly. Such as assign NULL to a pointer to invalidate it, I just want to do the same on iterator. container.end() could not be the precise idea here. I tried to assign NULL to my iterator, but it failed...
Shouldn't this always work? (iterators are always assignable and default-constructible) template <typename Iter> void foo(Iter it){ it = Iter(); // invalidate }
4,363,471
4,363,523
complex C++ template syntax
After joining SO, I am frequently seeing this kind of syntax whenever I open topics discussing templates. I tried searching on google, but in vain. template<typename T> char (&f(T[1]))[1]; //what is it? what is the use of '[]' brackets and the integer in it? template<typename T> char (&f(...))[2]; //not this either ...
The following two are equivalent // 1 template<typename T> char (&f(...))[2]; // 2 typedef char rettype[2]; template<typename T> rettype &f(...); You may have have seen that pattern before with function pointers char (*XXX)(); Now just replace the () with [N] to create an array instead of a function part, and repla...
4,363,771
4,363,789
How to prevent user from destroying an object
I want to return an implementation of a class from a function. The function is in a library. I want to prevent the user from destroying the objects I return. How can I achieve this? EDIT: Example. Interface to the world: class Base { public: virtual void foo() = 0; }; Base* GetFoo(); Implementation - Interna...
You could use a private destructor and create some method (release()) to allow the object to be freed in a controlled manner. Private destructors What is the use of having destructor as private?
4,364,331
4,364,350
Compile C++ for all linux distributions
How can i compile my C++ files to work on ALL linux distributions. The machine that i'll compile them on is Ubuntu 10.10 If i compile them on Ubuntu 10.10, will they work on other Distros like ubuntu, fedora, debian, non debian distros.. etc?
% gcc -o foo foo.c -static the resulting binary should work on most distros, given that it runs on the same architecture (64bit, 32bit, arm, mips etc). the main point is: since you do not know what can be found on the target systems in advance, you have to bundle everything you can into either the binary you are shipp...
4,364,374
4,364,518
How to get maya like rotations?
I am trying to achieve the same rotational effect like Maya in my project. I have some knowledge on quaternions and the trackball example. Unfortunately I am still unable to wrap my head around the concept of using the quaternions to get the desired effect. Basically I am still getting the same issue I had before with ...
I don't know Maya so I can only guess that its rotation is like this: if you rotate left-right, it feels natural. Then if you rotate the object up-down 180 degrees, then rotate left-right again, it still feels natural. If you are familiar with the concept of using a matrix to do transformations (like rotate, scale and ...
4,364,513
4,371,302
Filter QFileInfoList files with Qt
I have a QFileInfoList (list) that contains info about a directory and its file QFileInfoList list = directory.entryInfoList(); How can I apply filters to remove everything except image file(jpg, gif, png etc.) ? Here is a simple foreach loop that only removes everything that is not a file foreach (QFileInfo f, list){...
QDir::entryInfoList() takes name filters, if you're comfortable determining images by extension: QStringList nameFilter; nameFilter << "*.png" << "*.jpg" << "*.gif"; QFileInfoList list = directory.entryInfoList( nameFilter, QDir::Files );
4,364,536
4,364,586
Is null reference possible?
Is this piece of code valid (and defined behavior)? int &nullReference = *(int*)0; Both g++ and clang++ compile it without any warning, even when using -Wall, -Wextra, -std=c++98, -pedantic, -Weffc++... Of course the reference is not actually null, since it cannot be accessed (it would mean dereferencing a null pointe...
References are not pointers. 8.3.2/1: A reference shall be initialized to refer to a valid object or function. [Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a nul...
4,364,539
4,364,578
Passing int via winsocks send
How could it be possible to send int (not using third party libraries) via windows sockets Send: it requires (const char *) as parameter. My attempt was to send int like this: unsigned char * serialize_int(unsigned char *buffer, int value) { /* Write big-endian int value into buffer; assumes 32-bit int and 8-bit ch...
Ah, this is easily fixed. The compiler wants a char* (ignore const for now), but you're passing an unsigned char*, and the only real difference is how the compiler interprets each byte when manipulated. Therefore you can easily cast the pointer from unsigned char* to char*. This way: (char*)serialize_int(...)
4,364,599
4,364,610
C++ overloaded method pointer
How do I get a method pointer to a particular overload of a method: struct A { void f(); void f(int); void g(); }; I know that &A::g is a pointer to g. But how do I get a pointer to f or f(int)?
(void (A::*)()) &A::f (void (A::*)(int)) &A::f function pointers and member function pointers have this feature - the overload can be resolved by to what the result was assigned or cast. If the functions are static, then you should treat them as ordinary functions: (void (*)()) &A::f; (void (*)(int)) &A::f; or even (...
4,364,647
4,364,821
How to redefine malloc() in Linux for use in C++ new
I have a mem_malloc() and mem_free() defined for me and I want to use them to replace the malloc() and free() and consequently C++'s new and delete. I define them as follows: extern "C" { extern void *mem_malloc(size_t); extern void mem_free(void *); void * malloc(size_t size) { return mem_malloc(size); } void fre...
I assume you define malloc and free in the main.cpp file that you try to compile and that mem_alloc and mem_free are located in libmemnmf-0.a What is probably happening, is that some references in main.cpp require objects from glibc. Specifically, something is dynamically loading a library (dlopen). This code is includ...
4,364,714
4,365,987
How to get undecoded filename
Could somebody please give me some tips about how to get undecoded byte[] of filename? I want to do the decoding myself. I have traced java src code, but I am blocked by native function. Thanks a lot! I mean I want the original byte[] of filename, not convert it to a string and then convert it back. This may cause some...
When I made the comment that in c/c++ it is trivial I meant that in my experience c and c++ rarely converts data without being told to, and you should get what you want by doing nothing. To get the file name I'd expect you to have to iterater the contents of the folder. Two methods of doing this are to call FindFirstFi...
4,364,961
4,369,034
OpenGL rotation in 2D
I have a simple OpenGL application, which displays a line. I store x1, y1, x2 and y2 in global variables. The rotation function uses the feedback functionality, discussed here and the translation to origin method, suggested here. It's intended to rotate a line around it's center. Here's the code: void rotate( float ...
Looks to me like you're translating in the wrong direction and the origin is being placed outside your viewport in the lower-left. You want to move the origin to the point you want to translate around--so if the origin is in the lower-left, you need to translate +center_x, +center_y. Rotate, translate back (-center_x, ...
4,365,078
4,411,119
How to compile Qt library 4.7.1 with text codecs supported?
I've successfully built static Qt library and I could see plugins/codecs/libqcncodecs.a, but I still can not use GB18030 like this: QTextCodec::codecForName("GB18030") and all I still couldn't find Chinese related codecs by foreach (int mib, QTextCodec::availableMibs()) { QTextCodec *codec = QTextCodec::codecForM...
The documentation says: "To link statically against those plugins, you need to use the Q_IMPORT_PLUGIN() macro in your application and you need to add the required plugins to your build using QTPLUGIN." I think you are missing a Q_IMPORT_PLUGIN(qcncodecs) in your application.
4,365,157
4,365,257
virtual destructor's practical necessity in a particular case
C++03 5.3.5.3 In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined. This is the theory. The ques...
One example is if you provide a custom operator new in struct Derived. Obviously calling wrong operator delete will likely produce devastating results.
4,365,329
4,365,489
Determine the area of the intersection of two rectangles
I have two rectangles, each identified by a set of four coordinates. I've read up on how to see whether they intersect, but how can I calculate the area of the intersection? The rectangles are not axis-aligned. Is there an OpenCV function for this? I was told there was, but I fail to find it.
Treat your rectangles as general polygons, and decompose the problem into two steps: compute the intersection of the two polygons, which itself is a polygon (or is empty); compute the area of the resulting polygon. There's plenty of literature on the Web for both problems. I don't know anything about OpenCV so can't ...
4,365,468
4,365,480
Renaming a File in a different path
I tried renaming a fie with Follwoing Syntax: int iRenameXML,iRenameXMLErr; iRenameXML = rename("D:\Debug\CurrentServers.xml", "D:\Debug\CurrentServersssss.xml"); iRenameXMLErr = GetLastError(); But this Get me GLE 2 ,ERROR_FILE_NOT_FOUND. Is there any other way I can change tha name of a ...
You need do double backslash the \ int iRenameXML,iRenameXMLErr; iRenameXML = rename("D:\\Debug\\CurrentServers.xml", "D:\\Debug\\CurrentServersssss.xml"); iRenameXMLErr = GetLastError();
4,365,747
4,365,837
generically convert from boost::variant<T> to type
I have a typedef boost::variant<int, float, double, long, bool, std::string, boost::posix_time::ptime> variant which I use to store different types of values in a struct. Only one of the specific type is ever going to be stored in that struct, however I have a vector of these structs which I need to go through and get ...
Actually looking at your code some more, here is a different option - again based on using visitor.. struct add_node_visitor : boost::static_visitor<> { add_node_visitor(<type of modvalue> & node, <type of key> & key) : _node(node), _key(key) {} template <typename _Item> void operator()(_Item const& item) { ...
4,365,980
4,366,805
How to use profile guided optimizations in g++?
Also, can anyone point me to a good tutorial on the subject? I can't find any.
-fprofile-generate will instrument the application with profiling code. The application will, while actually running, log certain events that could improve performance if this usage pattern was known at compile time. Branches, possibility for inlining, etc, can all be logged, but I'm not sure in detail how GCC implemen...
4,365,982
4,366,023
How do I call a static method of another class
I have a class, lets say CAppPath which has a static method: public: static CString GetAppPath(); and in CAppPath.cpp it's defined as: CString CAppPath::GetAppPath() { return "C:\..\MypAth"; } Now I have another class CXMLHandler, and I have included CAppPath.h in it. But how do I call the GetAppPath() metho...
You only need to use the scope resolution operator :: to qualify the method with the name of the class that exposes it: CString appPath = CAppPath::GetAppPath();
4,366,061
4,370,056
How to find out from where (x) integral of a function (from that point to infinety) starts to be lesser than some eps?
So we have some function like (pow(e,(-a*x)))/(sqrt(x)) where a, e are const floats. we have some float eps=pow (10,(-4)). We need to find out starting from which x integral of that function from that x to infinety is less than eps? We can not use functions for special default integration function just standart math l...
Hmm, no one seems to understand the question. The question is: given some function f, find the smallest x such that Integral _ x ^ +inf f(x) < eps. That's the question. So basically we try x = 0, then x = 0.1 then x = 0.2 ... until the integral, for all intents and purposes, vanishes. For example, given the bell curve ...
4,366,257
4,367,147
Is there any online, html/flash/js based, free C++ editor that can compile code for ubuntu?
It can be opensource. I need it because I don't want to install virtual machine. So is there any online, html/flash/js based, free C++ (or at least C) compiler that can compile code simulating ubuntu c/c++ compiler and return built executable file to me? I heard that Mozilla had some cool online editors but I don't kno...
Codepad allows you to compile and run code snippets, which is good to quickly test ideas and/or share code quickly among friends; in no way it substitutes a good editor and programming environment. Plus, in any non-trivial project you need external libraries, I don't know how you would be able to deal with that. Just ...
4,366,282
4,366,355
Is there a generic "clean-up" class in boost?
I simply want a class that does this: class cleanup : boost::noncopyable { public: typedef boost::function0<void> function; explicit cleanup( function f ) : func( f ) { } ~cleanup() { func(); } private: function func; }; The purpose being that I have this "cleanup" to invoke func when it is ...
I believe that there is a Scope Exit library within Boost. However, why not just use the code you wrote in the OP? And, typically, if you have a class within a container, make the container's owner dish out the references and handle what happens when there are none left.
4,366,309
4,366,465
a simple question about casting integers in c++
i have the following very simple code - int x=15000 int z=0.7*x cout<<"z = "<<z<<endl; i get the output z=10499 but if i change it to int z=0.7*15000 cout<<"z = "<<z<<endl; outputs z=10500 i understand it has something to do with z casting the result to int but why is it different in both cases ? thanks, EDIT - i'...
int z=0.7*x; The double-precision value 0.7 is not exactly representable as a floating-point number; its hex representation is 3fe6666666666666 on most machines, which is less than the true value 3fe6666666666666... So the double-precision result of 0.7*x is less than its true value, and is rounded down. This is corr...
4,366,352
4,366,367
C++ overloading + operator in order to always concatenate strings of every kind
It's very pointless and troublesome that everytime that you need to concatenate two strings it is necessary to do at least: std::string mystr = std::string("Hello") + " World"; I would like to overload operator+ and use it in order to always do a concat between tho char* in this way: std::string mystr = "Ciao " + "Mon...
You cannot make + work like this. To define an operator overload, at least one of the operands must be a user-defined type. However, the functionality is built in: if you just put two string literals together "like" "this", they will automatically be joined together at compile time.
4,366,442
4,377,213
How should I create classes in ATL project?
I'm writing an ATL project and I wonder how should I create classes here. Right now I have one class created by Add/Class/ATL Simple Object. I want to divide it to smaller classes but method from this classes should use CComPtr and have CComPtr as an argument. I can't create 'simple' c++ class because I don't have CCom...
I don't understand your comment that you can't use CComPtr from a simple C++ class. Can you please clarify? I see two strategies: build a clean C++ object model that solves the problem, and then wrap it in a thin facade layer of one or more COM objects Use ATL classes throughout, and use CComObject<> and derivatives t...
4,366,487
4,367,480
Performance compare (normal function call vs for_each+mem_fun vs lambda expression) in C++
Which is the best one (in performance) among these snippets? 1) for(list<Enemy*>::iterator iter = enemies.begin(); iter != enemies.end(); iter ++) (*iter)->prepare(time_elapsed); 2) for_each(enemies.begin(), enemies.end(), [time_elapsed] (Enemy *e) {e->prepare(time_elapsed);}); 3) for_each(enemies.begin(), enemies...
Lambdas are the fastest solution. There are special optimizations involved with taking references to stack-based variables. In addition, in C++0x, they're FAR more flexible than any of that bind stuff, and the first loop also has the clarity disadvantage. Lambdas are the winrar in every way. However, I'm seriously thin...
4,366,532
4,367,344
C++ Convert Binary File to Image
I'm trying to make a C++ console app that can convert binary(mp3) files to images. How can I read every binary character in the file, convert to hex, and then save it as an image. Here is what I want but in C++
You might find this tutorial helpful: http://www.cplusplus.com/doc/tutorial/files/ (Scroll down to the section binary files) Also, let me share my standard recommended links for people asking for aid on basic c++: Full scale tutorial on c++ C++ Language Reference (including STL) ANSI C Language reference for all those ...
4,366,585
4,366,679
Why should the default template-argument of a mem func be explicitly defined as illegal?
In N3126 (Warning: very large PDF) 14.1/9, there are two statements that make me confused: #1: "A default template-argument may be specified in a template declaration." #2: "A default template-argument shall not be specified in the template-parameter-lists of the definition of a member of a class template that appears...
I might be mistaken, but my understanding of #2 is that it makes the following illegal : template<class T> struct A { void foo(); }; template<class T = int> void A<T>::foo() { /* ... */ }
4,366,756
4,366,874
Should the Interop Structure Memory be Freed After Calling?
I have the following function and structures in C++ code that are designed for interop: extern "C" __declspec(dllexport) typedef struct { int num_vertices; int *vertices; } Vertex_List; extern "C" __declspec(dllexport) typedef struct { int num_cycles; Vertex_List *cycles; } Cycle_List; extern "C" __d...
Responsibility of the releasing is by whoever has allocated the memory. As simple as it seem, this is the golden rule. According to this rule, when an unmanaged DLL returns me a pointer to an unmanaged structure it means that it has allocated the memory. So releasing the memory would require calling the unmanaged DLL t...
4,366,863
4,366,918
C++ assignment operator resolving
Consider the following code: struct A { void foo( const char * ) { cout << __PRETTY_FUNCTION__ << endl; } A & operator = ( const A & ) { cout << __PRETTY_FUNCTION__ << endl; return * this; } }; struct B : public A { void foo( const char * ) { cout << __PRETTY_FUNCTION__ << endl; } A & operator = ( co...
What you see is not a hiding problem at all. You did not create an assignment operator to assign B into B, therefore the compiler created one for you. The one created by the compiler is calling assignment operator of A. Therefore, if your question "Question: why B::foo hides A::foo, but B::operator= doesn't?" should be...