question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,022,870
2,022,899
Assignment operator with Inheritance and virtual base class
I have an abstract virtual base class Foo from which I derive many other classes that differ in small ways. I have a factory that creates the derived classes and returns Foo*. One of my bigger problems is in my operator overloads, I need to make sure that the DFoo does not get operated on by DFoo1 (not shown). I have c...
You are probably looking for boost::noncopyable.
2,023,007
2,023,227
gcc version 4.1.2 in mac os x
I am taking a programming class and we are required to use the gcc 4.1.2 compiler to compile our c++ projects. I will be creating my projects in xcode and can't find how to set that compiler. I went to the get info window on the project and hit the drop down under Compiler Version, however I do not have 4.1.2 on the li...
You can probably get away with using whatever version of GCC is on your Mac, and doing a final compile on the university machines as a check. In general, the user visible changes using a later version is stricter syntax checking, so you might do something on the Mac that won't pass a newer compiler, but that generally...
2,023,032
2,023,045
catch exception by pointer in C++
I found that there are three ways to catch an exception, what are the differences? 1) catch by value; 2) catch by reference; 3) catch by pointer; I only know that catch by value will invoke two copies of the object, catch by reference will invoke one. So how about catch by pointer? When to use catch by pointer? In addi...
The recommended way is to throw by value and catch by reference. Your example code throws a pointer, which is a bad idea since you would have to manage memory at the catch site. If you really feel you should throw a pointer, use a smart pointer such as shared_ptr. Anyway, Herb Sutter and Alexei Alexandrescu explain tha...
2,023,046
2,024,120
Is there any OpenSSL function to convert PKCS7 file to PEM
Is there any openssl api function to convert PKCS7 file to PEM. I am able to convert a PKCS12 file to PEM using PKCS12_parse() function which returns key and certificate given the password. There is no similar function for pkcs7. My pkcs7 input has just the certificate in binary format. I am able to do the conversion u...
After some googling I am able to do that. if(p7->d.sign->cert != NULL){ PEM_write_X509(fp, sk_X509_value(p7->d.sign->cert, 0)); } where p7 is a pointer to pkcs7 struct and fp is the file pointer to PEM file
2,023,519
2,023,600
convert a string to int
I have a large file where each line contains space-separated integers. The task is to sparse this file line-by-line. For the string to int conversion I have three solutions: static int stringToIntV1(const string& str) { return (atoi(str.c_str())); } However, if I pass a malformed string, it doesn't produce any err...
I'd use strtol. It takes a parameter that it sets to point at the first character it couldn't convert, so you can use that to determine whether the entire string was converted. Edit: as far as speed goes, I'd expect it to be slightly slower than atoi, but faster than the others you tried.
2,023,808
2,023,835
how to take a very large hex string and format the output
i have a very long hex string in a byte array and I would like to format the output of that byte array such that it shows 0x??,0x??. The reason for this because I have a key that I am making and I don't want to type out a 512bit key like that. Any native code that could help me do that would be appreciated. basically, ...
For each byte in the array: cout << "0x" << hex << unsigned(theByte) << ","; where theByte is the value (hopefully an unsigned char) that you want to print.
2,023,952
2,023,956
C++ extern class definition
I'm reading some code that goes: extern class MyClass : BaseClass { ... } MyInstance; Does the extern refer to the class declaration or the instance?
Instance. Classes cannot be extern. Although the code smells - this snippet suggests that true declaration of that instance uses a separate class definition. Bad, bad idea - defining the class twice.
2,023,962
2,024,093
Organising .libs in a codebase of several C++ projects
Let's say you have several bespoke C++ projects in separate repositories or top-level directories in the same repository. Maybe 10 are library projects for stuff like graphics, database, maths, etc and 2 are actual applications using those libraries. What's the best way to organise those 2 application projects to have ...
I'd suggest this approach: Organise your code in a root folder. Let's call it code. Now put your projects and libraries as subfolders (e.g. Projects and Libraries). Build your libraries as normal and add a post-build step that copies the resulting headers and .lib files into a set of shared folders. For example, Librar...
2,023,976
2,024,481
Costs and benefits of Linux-like Windows development environment
I'm taking an Introduction to C++ this semester, so I need to set up development environments in both my Windows and Ubuntu partitions (I switch between them). I was planning to use GCC in both environments for consistency and because I plan to do my serious C++ developing in Linux with GCC. It appears that installing...
I think you're going about this the wrong way - I would actually suggest you use Visual Studio on the Windows environment, rather than going out of your way to setup GCC. It's a benefit, not a drawback, to run your code on multiple compilers from multiple vendors. Both GCC and Visual Studio are highly conformant (at l...
2,023,977
2,024,173
Difference of keywords 'typename' and 'class' in templates?
For templates I have seen both declarations: template < typename T > template < class T > What's the difference? And what exactly do those keywords mean in the following example (taken from the German Wikipedia article about templates)? template < template < typename, typename > class Container, typename Type > class...
typename and class are interchangeable in the basic case of specifying a template: template<class T> class Foo { }; and template<typename T> class Foo { }; are equivalent. Having said that, there are specific cases where there is a difference between typename and class. The first one is in the case of dependent types...
2,024,185
2,024,333
(C++ QT) QList only allows appending constant class objects?
I'm pretty new to QT. I've been messing with it for a week now. I came across a error while I was trying to add a custom datatype to a Qlist like so QObject parent; QList<MyInt*> myintarray; myintarray.append(new const MyInt(1,"intvar1",&parent)); myintarray.append(new const MyInt(2,"intvar2",&parent)); myintarray.ap...
So you created a list of: QList<MyInt*> myintarray; Then you later try to append myintarray.append(new const MyInt(1,"intvar1",&parent)); The problem is new const MyInt is creating a const MyInt *, which you can't assign to a MyInt * because it loses the constness. You either need to change your QList to hold const M...
2,024,595
2,024,622
c++ getting dynamic generic type of pointer?
the title probably is misleading, but i didn't really know how to name it. let's say I have the following structs template <typename T> struct SillyBase{ void doFunnyStuff(vector<T> vec){ dummyField = T(); for(int i=0; i<10; i++) vec.push_back(dummyField++); } T dummyField; }; s...
In your example you can't have SillyBase* because SillyBase is defined as template <typename T> struct SillyBase {...} So you need to provide type ... Another problem is that you pass a copy of vector<T> into doFunnyStuff() which you then populate ... that does not seems right because when the method returns you lose...
2,024,650
2,024,678
Parsing a bit field parameter, how to "discard" bits in an unsigned long?
First of all, I want to know if this is possible: let's say I have an unsigned long which contains some abritrary unsigned shorts, which may or may not be in the number. For example: unsigned short int id1 = 3456, id2 = 30998; unsigned long long bitfld = id1|id2; Can the other 2 fields be assumed a...
short int is 2 bytes long, but long long is 8 bytes, so you have some kind of length mismatch; You may have meant this: unsigned long long bitfld = id1|(id2<<16); you can check is there is a field occupied by ANDing it like: void dostuff (unsigned long long bf) { //pseudo code if(bf & 0xFFFF) return...
2,024,933
2,105,840
Warning "might be clobbered" on C++ object with setjmp
#include <setjmp.h> #include <vector> int main(int argc, char**) { std::vector<int> foo(argc); jmp_buf env; if (setjmp(env)) return 1; } Compiling the above code with GCC 4.4.1, g++ test.cc -Wextra -O1, gives this confusing warning: /usr/include/c++/4.4/bits/stl_vector.h: In function ‘int main(int, char**)’: /us...
The rule is that any non-volatile, non-static local variable in the stack frame calling setjmp might be clobbered by a call to longjmp. The easiest way to deal with it is to ensure that the frame you call setjmp doesn't contain any such variables you care about. This can usually be done by putting the setjmp into a f...
2,025,019
2,025,043
What object is rethrown in C++?
I am quite confused about the type of the object which is rethrown in C++. For example, in the code above, why is the output 241? My understanding is that in Line 1, an object of class Bar is thrown. It is caught in Line 2. The object of type Bar is sliced to type of Foo. However, when the exception is rethrown, what'...
throw; on its own throws the same object. The object is really a Bar, even though your reference to it is a Foo&. So when you say, "It is caught in Line 2. The object of type Bar is sliced to type of Foo", that's not right. It's not sliced either by the catch or by the rethrow. If you change the line throw; to throw e;...
2,025,104
2,025,132
Fast conversion from YUY2 to RGB24
I'm writing a program, that will do some transformations with image from a webcam in real-time. As almost all other webcams, my noname gives data in YUY2 format (as written in bmiHeader.biCompression). I tried straight conversion on CPU side according to http://www.fourcc.org/yuv.php#YUY2, but it is VERY slow and wrong...
I don't have the code available at the moment. but take a look at using the GDI to do the conversion its very fast. Basically capture the source frame, create a memory dib in the correct format (rgb24) and blit to the bitmap. the conversion occurs during the blitting and in my experience is very fast. I use this to gra...
2,025,119
2,025,122
How do i peek at at the next value of string iterator
In a loop running over the entire string how do i peek at the next value of iterator? for (string::iterator it = inp.begin(); it!= inp.end(); ++it) { // Just peek at the next value of it, without actually incrementing the iterator } This is quite simple in C, for (i = 0; i < strlen(str); ++i) { if (str[i] == st...
if ( not imp.empty() ) { for (string::iterator it = inp.begin(); it!= inp.end(); ++it) if (it + 1 != inp.end() and *it == *(it + 1)) { // Processing } } } or if ( not imp.empty() ) { for (string::iterator it = inp.begin(); it!= inp.end() - 1; ++it) if ( *it == *(it+1)...
2,025,145
2,032,797
Debugging C++ virtual multiple inheritance in Visual Studio 2008 watch window
I'm having trouble debugging a project in Visual Studio C++ 2008 with pointers to objects that have virtual multiple inheritance. I'm unable to examine the fields in the derived class, if the pointer is a type of a base. A simple test case I made: class A { public: A() { a = 3; }; virtual ~A() {} ...
This link also indicates that the debug symbol engine has problems with multiple inheritance with virtual base classes. But if you just want help debugging, why not add a helper function on the class A to get a D pointer if available. You can watch pB->GetMyD(). class D; class A { ... D* GetMyD(); ... } ...
2,025,153
2,026,225
C++ Language template question
Below is a small test case that demonstrates a problem that I am trying to solve using templates in C++: template<typename T> void unused(T const &) { /* Do nothing. */ } int main() { volatile bool x = false; unused(!x); // type of "!x" is bool } As written below, the g++ v3.4.6 compiler complains: test.cc: In ...
As Johannes said in the comments, you hit a compiler bug. You can work around it by explicitly converting to bool: unused( bool( !readWriteActivated) ); // add bool() to any (!volatile_bool_var) Old answer (but still not a bad idea) If I recall the const-volatile qualification rules, all you need is to qualify the du...
2,025,159
2,025,170
What's the use of const here
in int salary() const { return mySalary; } as far as I understand const is for this pointer, but I'm not sure. Can any one tell me what is the use of const over here?
Sounds like you've got the right idea, in C++ const on a method of an object means that the method cannot modify the object. For example, this would not be allowed: class Animal { int _state = 0; void changeState() const { _state = 1; } }
2,025,217
2,025,374
Need help with C++ templates
I'm fairly sure this is a template question, since I can't seem to solve it any other way - but non-template solutions are also welcome. A Finite State Machine has a number of program States and each state can react to a number of Events. So, I want to define classes for Event, State and FSM. FSM has a collection (prob...
I'm not shure if I'm understanding things correctly but I'll take a stab at it: I'm assuming you want to define a state machine by defining the transitions; e.g. "when in state 'myEvents' and you see 'a' do 'event_a'" class State {}; template<T> RealState : State { static void Add(T event, char*) { /* save stuff */...
2,025,228
2,025,532
Creating function pointers to functions created at runtime
I would like to do something like: for(int i=0;i<10;i++) addresses[i] = & function(){ callSomeFunction(i) }; Basically, having an array of addresses of functions with behaviours related to a list of numbers. If it's possible with external classes like Boost.Lambda is ok. Edit: after some discussion I've come to co...
If I understand you correctly, you're trying to fill a buffer with machine code generated at runtime and get a function pointer to that code so that you can call it. It is possible, but challenging. You can use reinterpret_cast<> to turn a data pointer into a function pointer, but you'll need to make sure that the mem...
2,025,287
2,025,377
sending back a vector from a function
How to translate properly the following Java code to C++? Vector v; v = getLargeVector(); ... Vector getLargeVector() { Vector v2 = new Vector(); // fill v2 return v2; } So here v is a reference. The function creates a new Vector object and returns a reference to it. Nice and clean. However, let's see the ...
Most C++ compilers implement return value optimization which means you can efficiently return a class from a function without the overhead of copying all the objects. I would also recommend that you write: vector<int> v(getLargeVector()); So that you copy construct the object instead of default construct and then oper...
2,025,380
2,025,423
unpredictable behavior of Inline functions with different definitions
I have the following source files: //test1.cpp #include <iostream> using namespace std; inline void foo() { cout << "test1's foo" << endl; } void bar(); int main(int argc, char *argv[]) { foo(); bar(); } and //test2.cpp #include <iostream> using namespace std; inline void foo() { cout << "test2's foo" <...
You are running into the one-definition-rule. You are not seeing any error because: [Some] violations, particularly those that span translation units, are not required to be diagnosed What going on under the covers is that the compiler is not inlining those functions (many compilers will not inline a function unless...
2,025,795
2,026,407
Private inheritance from std::basic_string
I've been trying to learn more about private inheritance and decided to create a string_t class that inherits from std::basic_string. I know a lot of you will tell me inheriting from STL classes is a bad idea and that it's better to just create global functions that accept references to instances of these classes if I ...
Your default constructor should not be explicit. I think explicitness may be the reason it can't convert std::string to string_t as well, but you erased that construtor from your snippet :vP . This program compiles and runs fine with GCC 4.2: #include <iostream> #include <string> #include <vector> using namespace std; ...
2,025,938
2,025,952
Searching c++ std vector of structs for struct with matching string
I'm sure I'm making this harder than it needs to be. I have a vector... vector<Joints> mJointsVector; ...comprised of structs patterned after the following: struct Joints { string name; float origUpperLimit; float origLowerLimit; }; I'm trying to search mJointsVector with "std::find" to locate an indi...
A straight-forward-approach: struct FindByName { const std::string name; FindByName(const std::string& name) : name(name) {} bool operator()(const Joints& j) const { return j.name == name; } }; std::vector<Joints>::iterator it = std::find_if(m_jointsVector.begin(), ...
2,026,217
2,026,296
Difference in linkage between C and C++?
I have read the existing questions on external/internal linkage over here on SO. My question is different - what happens if I have multiple definitions of the same variable with external linkage in different translation units under C and C++? For example: /*file1.c*/ typedef struct foo { int a; int b; int ...
Both C and C++ have a "one definition rule" which is that each object may only be defined once in any program. Violations of this rule cause undefined behaviour which means that you may or may not see a diagnostic message when compiling. There is a language difference between the following declarations at file scope, b...
2,026,287
2,026,309
Exception handling before and after main
Is it possible to handle exceptions in these scenarios: thrown from constructor before entering main() thrown from destructor after leaving main()
You can wrap up your constructor withing a try-catch inside of it. No, you should never allow exception throwing in a destructor. The funny less-known feature of how to embed try-catch in a constructor: object::object( int param ) try : optional( initialization ) { // ... } catch(...) { // ... } Yes, this is...
2,026,305
2,026,349
std::min is being redefined, but how?
Do streflop or boost libraries change the definition of std::min? I have a project that compiles fine with g++/make UNTIL I merge it with the CMake build of another project (using add_directory). Suddenly I get: no matching function for call to min(double&,float) The line number it claims the error is on is wrong (it'...
Try std::min<double>(first, key.mTime); The two arguments seem to have different types so the compiler can't resolve the template argument to std::min EDIT3: I actually took a look at the assimp library and from your error message, it's line 280 of ScenePreprocessor.cpp that's the cause of the problems: anim->mDuratio...
2,026,437
2,026,465
Writing a filter for incoming connections
I'm using C++/boost::asio under Win7. I'm trying to "sniff" trafic over a given TCP/IP port. Hence, I'd like to listen on that port, receive messages, analyze them, but also immidately allow them to flow further, as if I never intercepted them. I want them to sink into the program that normally listens and connects on ...
what you are trying to do is basically a firewall program. On windows there is several approach to do that, you can hook winsock. The better (or not hacky) is to use TDI filter (you take a look a this) or to make a NDIS filter. Microsoft also introduced new API, WPF and LSP. I think you have better to use it because ...
2,026,516
2,027,088
How can a QToolBar know where it is?
In Qt, when moving a QToolBar, one can use the QToolBar::topLevelChanged(bool) signal to know if the the QToolBar is floating or docked. When the QToolBar is docked, how can one get the Qt::ToolBarArea (LeftToolBarArea, RightToolBarArea, TopToolBarArea, BottomToolBarArea) where the QTookBar is docked? Thanks.
I would try this : Qt::ToolBarArea QMainWindow::toolBarArea ( QToolBar * toolbar ) const; Hope this helps !
2,026,652
2,026,709
Macro's with n number of arguments
Possible Duplicate: C/C++: How to make a variadic macro (variable number of arguments) Just wondering if this is at all possible., so instead of how im currently handling logging and messages with multiple parameters im having to have a number of different macros for each case such as: #define MSG( msg ...
Well since @GMan didn't want to put that as an answer himself, have a look at variadic macros which are part of the C99 standard. Your question is tagged C++ though. Variadic macros are not part of the C++ standard but they are supported by most compilers anyway: GCC and MSVC++ starting from MSVC2005.
2,026,724
2,029,203
Eclipse CDT Editor support for altivec C++ extensions?
Does the Eclipse CDT C++ editor have a means of supporting the Altivec C++ language extensions, as implemented for example in the GNU g++ compilers when compiling with -maltivec? Specifically, can it be made to stop reporting the vector data types as syntax errors? e.g. vector unsigned char foo; declares a 128-bit vec...
The Eclipse CDT has two C++ parsers, one of which aims for GNU compatibility and currently lacks support for Altivec. The second aims for compatibility with XLC, and has syntactic support for Altivec types in program code (but not semantic support!), with support for some GNU extensions too. That can be gotten from Ecl...
2,026,853
2,065,622
Unable to attach to created process with Visual Studio 2005
I'm having problems attaching to a process spawned from one of my own processes. When I attempt to attach to the process using Visual Studio 2005 (Debug -> Attach to process) I receive the error message: "Unable to attach to the process. The system cannot find the file specified." In my program, I spawned the process t...
Ok, I finally found out what caused this problem. I'll post it here in case anyone else encounters this (from the scarcity of answers I guess it ain't that common, but hey...). The problem was that the path used to launch the executable contained a path element consisting of a single dot, like this: c:\dir1\.\dir2\prog...
2,027,079
2,027,111
Why insert from std::map doesn't want to update? [C++]
I'm trying to insert multiple times this same key into map but with different values. It doesn't work. I know that operator[] does this job, but my question is, if this behaviour of insert is correct? Shouldn't insert() inserts? I wonder what standard says. Unfortunately I don't have it(Standard for C++) so I can't che...
If you want to insert the same key with different values, you need std::multimap instead. The std::map::insert will not do anything if the key already exists. The std::map::operator[] will overwrite the old value. For STL reference you don`t necesary need the C++ standard itself; something like http://www.cplusplus.com...
2,027,363
2,027,452
using tapi to monitor multiple phones and dial or hangup
I have with a good level of success got a C# application to use TAPI to connect to my office PBX and dial and hangup calls but need to go further and be able to monitor activity and provide CTI to client pc's as well as integration back to my companies web based CRM. I am focusing on the client app for CTI popups and d...
To monitor multiple devices you will need a 3rd-party TAPI driver from your PBX manufacturer (and they don't all supply them.) The default Windows driver will probably be a 1st-party driver that can only handle one device at a time. You should consider using a central server to monitor all devices and use a hand-rolle...
2,027,472
2,028,244
Why is the type library in my dll corrupt (registering returns TYPE_E_CANTLOADLIBRARY)?
We have a mature c++ COM codebase that has been building, registering and running for many years. This includes numerous developer machines and autobuild machines. The codebase builds several dlls and exes. Some of these are COM servers. The typical setup is Xp64 using both visual studio 2005 and 2008. We have both 3...
Well I think we have nailed this as a visual studio bug. We found that the path where our autobuild runs had recently been changed - increasing the absolute pathname lengths of any files that the compiler generates. We also know that 64bit release build's target folder would have the longest pathname of any of our conf...
2,027,508
2,028,513
Simple tool for callgraph in C++
Is there are simple tool, which can be used to determine from where a function is called, which other function the function calls ...? Edit: I'm using Mac OS X (10.6) and just want to do static analysis. Thanks!
How about cscope? Check out 3rd & 4th bullet items on the page: functions called by a function functions calling a function It's been a while since I used cscope on C++, I seem to remember it being rock-solid on C code, but not as strong with C++.
2,027,556
2,027,582
c++ why is constructor in this example called twice?
I just try to understand the behaviour of the following situation: template <typename T1> struct A{ template <typename T2> A(T2 val){ cout<<"sizeof(T1): "<<sizeof(T1)<<" sizeof(T2): "<<sizeof(T2)<<endl; } T1 dummyField; }; so - the class is templated with T1 and the constructor is templated wit...
How to avoid copying? In both cases two constructors are called, however you do not see it in the first case as one of them is the compiler generated one. If you want to avoid copying, you need to use a different syntax, like this: A<bool> a(true); A<bool> a(3.5f); Why (and what) copy constructor is called? A<bool> a...
2,027,558
2,027,585
Communication between processes
I'm looking for some data to help me decide which would be the better/faster for communication between two independent processes on Linux: TCP Named Pipes Which is worse: the system overhead for the pipes or the tcp stack overhead? Updated exact requirements: only local IPC needed will mostly be a lot of short mess...
In the past I've used local domain sockets for that sort of thing. My library determined whether the other process was local to the system or remote and used TCP/IP for remote communication and local domain sockets for local communication. The nice thing about this technique is that local/remote connections are transpa...
2,027,790
2,027,852
c/c++ passing argument by pointer/argument by reference stack frame layout
Will the compiler produce the same code for both of these statements? foo1(int* val){(*val)++;} foo2(int &val){val++;} Will it simply write a pointer into the parameter part of foo's stack frame? Or, in the second case, will the callers' and foos' stack frames somehow overlap such that the callers' local variable tak...
The stacks cannot be made to overlap. Consider that the argument could be a global, a heap object, or even if stored in the stack it could be not the very last element. Depending on the calling convention, other elements might be placed in between one stack frame and the parameters passed into the function (i.e. retur...
2,027,873
2,027,914
Copy constructors and Assignment Operators
I wrote the following program to test when the copy constructor is called and when the assignment operator is called: #include class Test { public: Test() : iItem (0) { std::cout << "This is the default ctor" << std::endl; } Test (const Test& t) : iItem (t.iItem) { ...
No assignment operator is used in the first test-case. It just uses the initialization form called "copy initialization". Copy initialization does not consider explicit constructors when initializing the object. struct A { A(); // explicit copy constructor explicit A(A const&); // explicit constructor exp...
2,027,973
2,028,227
parallel Bubble sort using openmp
i write a c++ code for Bubble sort algorithm and i dont know how to make it parallel using openmp so please help me ..... this is the code : #include "stdafx.h" #include <iostream> #include <time.h> #include <omp.h> using namespace std; int a[40001]; void sortArray(int [], int); int q=0; int _tmain(int ...
Try this Parallel Bubble Sort algorithm: 1. For k = 0 to n-2 2. If k is even then 3. for i = 0 to (n/2)-1 do in parallel 4. If A[2i] > A[2i+1] then 5. Exchange A[2i] ↔ A[2i+1] 6. Else 7. for i = 0 to (n/2)-2 do in parallel 8. If A[2i+1] > A[2i+2] then 9. Exchange A[2i+...
2,027,991
2,028,018
List of standard header files in C and C++
Where could I find the list of all header files in C and C++? While I am building a library, I am getting an error like 'tree.h not found'. I suppose this is a standard header file in C and C++. This raised in me the curiosity to know all the header files and their contribution. Is there a place I can search for? I am...
Try here : http://en.cppreference.com/w/ However, you may also be refering to the header files of your OS. These can be found either on MSDN (Windows) or by man command (POSIX systems). Or another source if you're on another OS.
2,028,107
2,028,286
STL-friendly pImpl class?
I am maintaining a project that can take a considerable time to build so am trying to reduce dependencies where possible. Some of the classes could make use if the pImpl idiom and I want to make sure I do this correctly and that the classes will play nicely with the STL (especially containers.) Here is a sample of wh...
You should consider using copy-and-swap for assignment if it's possible that Foo or Bar might throw as they're being copied. Without seeing the definitions of those classes, it's not possible to say whether they can or not. Without seeing their published interface, it's not possible to say whether they will in future c...
2,028,331
2,028,385
Qt use-case for same signal to 2 slots on same object?
I am a total newbie to Qt. As I was reading the documentation, I came across this configuration: connect( Object1, Signal1, Object2, slot1 ) connect( Object1, Signal1, Object2, slot2 ) What could possibly be the use-case for this? Looks odd to me coming from an Erlang/Python background. It must have to do with C++ inh...
This is for cases when you have something like one button that changes two parts of another. It may sound silly, but it would be equivalent to calling the second slot function from the first slot. Say, clicking the play/pause button makes the stop button active or in active and also changes the tool tip. This could e...
2,028,361
2,028,398
How does Google Maps know my position?
I have a nokia 5500 sport mobile phone, and I found after i installed google map, it can automatically locate to my current position. and I want to know how google map get my position and mark it on the map ? How can I programming implement this feature with symbian C++(nokia 5500 's operate system is Symbian 3rd).
This is one of those questions where you need to know the jargon in order to find the answer. The magic word is "Location API". Using it, I found this: http://wiki.forum.nokia.com/index.php/Google_Maps_using_Location_Api_in_Symbian For mobile devices, a location API sometimes more or less hides the details of how the l...
2,028,464
2,028,481
Logic differences in C and Java
Compile and run this code in C #include <stdio.h> int main() { int a[] = {10, 20, 30, 40, 50}; int index = 2; int i; a[index++] = index = index + 2; for(i = 0; i <= 4; i++) printf("%d\n", a[i]); } Output : 10 20 4 40 50 Now for the same logic in Java class Check { public static void main(String[] a...
That is because a[index++] = index = index + 2; invokes Undefined Behavior in C. Have a look at this From the link: ..the second sentence says: if an object is written to within a full expression, any and all accesses to it within the same expression must be directly involved in the computation of the value to be wri...
2,028,561
2,028,708
c++ Garbage collection and calling destructors
Per-frame I need to allocate some data that needs to stick around until the end of the frame. Currently, I'm allocating the data off a different memory pool that allows me to mark it with the frame count. At the end of the frame, I walk the memory pool and delete the memory that was allocated in a particular frame. The...
If you don't want to force all the objects to inherit from Destructible, you can store a pointer to a deleter function (or functor) along with the pointer to the data itself. The client code is responsible for providing a function that knows how to delete the data correctly, typically something like: void xxx_deleter(v...
2,028,862
2,040,900
SSL_CTX_use_PrivateKey_file fail under Linux
I'm trying to use the SSL_CTX_use_PrivateKey_file function in OpenSSL under Linux, but it returns false. The surrounding code has been ported from Windows, where everything runs fine. Is there something that must be done differently depending on system? I've compiled the OpenSSL library myself (default config etc) unde...
To keep things simple, I removed all code from my password callback, and had simple pBuf = "mypass"; return 6; This would be the bare-minimum of the callback function. This worked fine. So what was different between the Windows code and the Linux code? Well, a call to strcpy_s and strcpy, respectively, was the only di...
2,029,258
2,029,435
How can i compare queues in cpp?
i need to compare the size of 10 queues and determine the least one in size to insert the next element in creating normal if statements will take A LOT of cases so is there any way to do it using a queue of queue for example or an array of queues ? note : i will need to compare my queues based on 2 separate things in 2...
You could do something like that std::queue<int> queue1; std::vector<std::queue<int> > queues; // Declare a vector of queue queues.push_back(queue1); // Add all of your queues to the vector // insert other queue here ... std::vector<std::queue<int> >::const_iterator minItt = queues.begin(); // Get the first ...
2,029,272
2,029,330
How to declare a global variable that could be used in the entire program
I have a variable that I would like to use in all my classes without needing to pass it to the class constructor every time I would like to use it. How would I accomplish this in C++? Thanks.
global.h extern int myVar; global.cpp #include "global.h" int myVar = 0; // initialize class1.cpp #include "global.h" ... class2.cpp #include "global.h" ... class3.cpp #include "global.h" ... MyVar will be known and usable in every module as a global variable. You do not have to have global.cpp. You could initi...
2,029,278
2,056,599
Forward declaring a function that uses enable_if : ambiguous call
I have some trouble forward declaring a function that uses boost::enable_if: the following piece of code gives me a compiler error: // Declaration template <typename T> void foo(T t); // Definition template <typename T> typename boost::enable_if<boost::is_same<T, int> >::type foo(T t) { } int main() { foo(12); ...
This is not only a problem with enable_if. You get the same error on Visual Studio and gcc with the following code: struct TypeVoid { typedef void type; }; template<typename T> void f(); template<typename T> typename T::type f() { } int main() { f<TypeVoid>(); return 0; } I think the main problem is that the ...
2,029,283
2,029,331
Reading and writing to a file in c++
I am trying to write a triple vector to a file and then be able to read back into the data structure afterward. When I try to read the file back after its been saved the first fifty values come out correct but the rest of the values are garbage. I'd be really appreciative if someone could help me out here. Thanks a lot...
Since you're writing binary data (and apparently working under Windows) you really need to specify ios::binary when you open the fstream.
2,029,507
2,029,579
How to create a map function in c++?
Say there is a list of integers [1,2,3,4,5] and a map function that multiplies each element with 10 and returns modified list as [10,20,30,40,50] , with out modifying the original list. How this can be done efficiently in c++.
Here's an example: #include <vector> #include <iostream> #include <algorithm> using namespace std; int multiply(int); int main() { vector<int> source; for(int i = 1; i <= 5; i++) { source.push_back(i); } vector<int> result; result.resize(source.size()); transform(source.begin(), source.e...
2,029,565
2,029,610
Troubleshooting compile time link errors
I'm trying to statically link to libcrypto.a (from the openssl library) after building it from source with a new toolchain. However whenever I try to use any of the functions from that library, I keep receiving "undefined reference" errors. I've made sure the right header file was included. I've also double checked the...
Undefined reference/symbol is a linker error indicating that the linker can't find the specified symbol in any of the object modules being linked. This indicates one or more of the following: The specified class/method/function/variable/whatever is not defined anywhere in the project. The symbol is inaccessible, proba...
2,029,651
2,030,018
How do you initialise a dynamic array in C++?
How do I achieve the dynamic equivalent of this static array initialisation: char c[2] = {}; // Sets all members to '\0'; In other words, create a dynamic array with all values initialised to the termination character: char* c = new char[length]; // how do i amend this?
char* c = new char[length]();
2,029,676
2,029,762
Why can't a Visual C++ interface contain operators?
As per the MSDN doc on __interface, a Visual C++ interface "Cannot contain constructors, destructors, or operators." Why can't an interface contain an operator? Is there that much of a difference between a get method that returns a reference: SomeType& Get(WORD wIndex); and the overloaded indexer operator? SomeType& o...
The __interface modifier is a Visual C++ extension to help implementing COM interfaces. This allows you to specify a COM 'interface' and enforces the COM interface rules. And because COM is a C compatible definition, you cannot have operators, Ctor or Dtors.
2,029,741
2,029,798
Why does the C++ linker require the library files during a build, even though I am dynamically linking?
I have a C++ executable and I'm dynamically linking against several libraries (Boost, Xerces-c and custom libs). I understand why I would require the .lib/.a files if I choose to statically link against these libraries (relevant SO question here). However, why do I need to provide the corresponding .lib/.so library fi...
The compiler isn't aware of dynamic linking, it just knows that a function exists via its prototype. The linker needs the lib files to resolve the symbol. The lib for a DLL contains additional information like what DLL the functions live in and how they are exported (by name, by ordinal, etc.) The lib files for DLL'...
2,030,750
2,031,002
Using DB Api in a portable manner
I need to develop some kind of application and use DB in it. Let's say i want to develop it over Windows currently, however, in a couple months i may have to migrate it to Linux. I started reading a little bit about it, but couldn't get to point i needed. Is there or isn't a generic/protable/standart api for using DB ?...
There's a bunch of C++ "wrapper" libraries for generic DB access, here's couple of top of my head: SOCI - modern C++ syntax, active development, plays nice with boost, supports multiple backends OTL - header-only (templates), very light-weight Both of these grew out of Oracle-specific work, but support at least sever...
2,031,003
2,031,269
Plugin application hangs when invoking functionality from another DLL
I am trying to render a GStreamer pipeline running on top of a XUL window. For this I wrote an XPCOM plugin. A XPCOM plugin is basically a dll file that gets loaded by the Gecko engine. My plugin links with GStreamer and as a consequence it depends on many other GStreamer plugins (also dll files). Invoking GStreamer co...
Ok, I'm embarrased... I forgot to execute the GStreamer initialization function: gst_init(NULL, NULL); Problem is fixed now.
2,031,007
2,031,091
fstream skipping characters without reading in bitmap
I am trying to read a bmp file using fstream. However it skips the values between 08 and 0E (hex) for example, for values 42 4d 8a 16 0b 00 00 00 00 00 36 it reads 42 4d 8a 16 00 00 00 00 00 36 skipping 0b like it does not even exist in the document. What to do? code: ifstream in; in.open("ben.bmp", ios::binary); unsig...
#include <fstream> #include <iostream> #include <string> int main(int argc, char *argv[]) { const char *bitmap; const char *output = "s.txt"; if (argc < 2) bitmap = "ben.bmp"; else bitmap = argv[1]; std::ifstream in(bitmap, std::ios::in | std::ios::binary); std::ofstream out(output, std::ios::o...
2,031,483
2,037,511
Using C# how to clean up MSMQ message format to work with C++ IXMLDOMDocument2
I'm trying to get a C++ service to load an XML document from a MSMQ message generated by C#. I can't really change the C++ side of things because I'm trying to inject test messages into the queue. The C++ service is using the following to load the XML. CComPtr<IXMLDOMDocument2> spDOM; CComPtr<IXMLDOMNode> spNode; CC...
Have you tried the ActiveXMessageFormatter? It might not compile with it as the formatter, i have no way to test here, but it might. EDIT: just tried and it compiles ok, whether the result is any better i still couldn't say for sure.
2,031,524
2,031,555
C++ STL data structure alignment, algorithm vectorization
Is there a way to enforce STL container alignment to specific byte, using attribute((aligned))perhaps? the target compilers are not Microsoft Visual C++. What libraries, if any, provide specialized templates of STL algorithms which have specific explicit vectorization, e.g. SSE. My compilers of interest are g++, Intel...
With STL containers, you can provide your own allocator via an optional template parameter. I wouldn't recommend writing an entire allocator from scratch, but you could write one that's just a wrapper around new and delete but ensures that the returned memory meets your alignment requirement. (E.g., if you need n byt...
2,031,746
2,031,775
C++: Continue execution after SIGINT
Okay, I am writing a program that is doing some pretty heavy analysis and I would like to be able to stop it quickly. I added signal(SIGINT, terminate); to the beginning of main and defined terminate like: void terminate(int param){ cout << endl << endl << "Exit [N]ow, or [A]fter this url?" << endl; std::string a...
From MSDN: Note SIGINT is not supported for any Win32 application, including Windows 98/Me and Windows NT/2000/XP. When a CTRL+C interrupt occurs, Win32 operating systems generate a new thread to specifically handle that interrupt. This can cause a single-thread application such as UNIX, to become multithreaded, re...
2,031,849
2,031,937
OpenCV's IplImage* as function parametr error
I am using OpenCV library and I want to clone picture in separate function, but I cannot send address to the function IplImage* image = cvLoadImage( path, CV_LOAD_IMAGE_GRAYSCALE ); // loading is ok showFoundPoints(image); // -> here it shows errors ... //my function int showFoundPoints(IplImage*image) {...} And ...
Is the definition of showFoundPoints consistent in the header and the source? It would seem you have it declared differently; one taking a std::string and the other not.
2,031,922
2,034,294
Tips for writing a DBMS
I have taken a graduate level course which is just one big project - to write a DBMS. The objective is not to reinvent the wheel and make an enterprise DBMS to rival Oracle. Only a small subset of SQL commands need to be supported. Nor is the objective to create some fancy hybrid model DBMS for storing multimedia or so...
Since your professor mentioned metaprogramming, you might want to look at the following: WAM - Warren Abstract Machine. This compiles prolog code into a set of instructions that can be executed on an abstract machine. The idea is similar to jvm and cli. You don't need to go into this in detail, just understand the ide...
2,031,940
2,032,126
How to use boost::array with unknown size as object variable
I'd like to use boost::array as a class member, but I do not know the size at compile time. I thought of something like this, but it doesn't work: int main() { boost::array<int, 4> array = {{1,2,3,4}}; MyClass obj(array); } class MyClass { private: boost::array<int, std::size_t> array; public: ...
Boost's array is fixed-size based on the second template parameter, and boost::array<int,4> is a different type from boost::array<int,2>. You cannot have instances of the same class (MyClass in your example) which have different types for their members. However, std::vectors can have different sizes without being diff...
2,032,056
2,048,266
Compilable C++ code to implement a secure SLL/TLS client using MS SSPI
As described here http://www.ddj.com/cpp/184401688 I do not have time to write this from scratch. Asked and not answered https://stackoverflow.com/questions/434961/implementing-ssl THE QUESTION IS: I am looking for some compilable working source code that implements MS SSPI (as alluded to in the thread above), procedur...
This SSPI SChannel SMTPS example should compile and run in Visual Studio 2008 as is http://www.coastrd.com/c-schannel-smtp (the original site seems dead; fortunately WaybackMachine has it archived) SChannel is the Microsoft implementation of the GSS API that wraps the SSL/TLS protocol. Advantages of utilizing SChannel:...
2,032,325
2,032,340
C++ virtual function execution efficiency
I am trying to get a better idea of performance of virtual functions here is an example code: struct Foo { virtual void function1(); virtual void function2() { function1(); } }; struct Bar : Foo { virtual void function1(); } Bar b; Foo &f = b; b.function2(); b.function1(); f.function2(); for each of t...
The calls on b are static - the compiler knows for sure at compilation time what the type of b will be at runtime (obviously a Bar) so it will directly use the addresses of the methods that will be invoked. Virtual only matters when you make a call via pointer/reference as the call could have different targets at runti...
2,032,361
2,032,368
what's polymorphic type in C++?
I found in one article saying "static_cast is used for non-polymorphic type casting and dynamic_cast is used for polymorphic type casting". I understand that int and double are not polymorphic types. However, I also found that static_cast can be used between base class and derived class. What does polymorphic type her...
First of all, the article is not completely correct. dynamic_cast checks the type of an object and may fail, static_cast does not check and largely requires the programmer to know what they're doing (though it will issue compile errors for some egregious mistakes), but they may both be used in polymorphic situations. ...
2,032,502
2,032,508
Why is Application Binary Interface important for programming
I don't understand why the ABI is important context of developing user-space applications. Is the set of system calls for an operating system considered an ABI? But if so then aren't all the complexities regarding system calls encapsulated within standard libraries? So then is ABI compatibility only relevant for runni...
An ABI defines a set of alignment, calling convention, and data types that are common to a system. This makes an ABI awfully important if you're doing any sort of dynamic linking; as without it code from one application has no way of calling code provided by another. So, no. ABI compatibility is relevant for all dyna...
2,032,651
2,032,905
Firefox basic modification
I have to modify firefox to make it an automated client for testing some personal servers. I have to:1.Have firefox connect normaly, send the GET HTTP, and run all scripts on that web page. 2.Firefox does not display the page but save it to a file. I have not yet red the documentation, or the source, sorry. I want some...
Instead of modifying the internal code of Firefox you should try implementing what you need in an extension. Better yet, use something already created, like Selenium. You generally don't get useful answers to general questions like this.
2,032,654
2,032,750
Can you call a copy constructor from another method?
/** @file ListP.cpp * ADT list - Pointer-based implementation. */ #include <iostream> #include <cstddef> // for NULL #include <new> // for bad_alloc #include "ListP.h" // header file using namespace std; List::List() : size(0), head(NULL) { } // end default constructor List::List(const List& aList) : size(aLi...
If I understand your question, you cannot do what you are trying to do. Before you can call any other methods on an object, the object must be fully constructed (there is an exception here, I'll get back to that). Furthermore, an object can only be constructed once (*). Therefore, by the time you could call your copy...
2,032,719
2,032,725
C++ cin.fail() question
When running the following code and enter a number, it works fine. But when entering a letter, the program enters an infinite loop, displaying "Enter a number (0 to exit): cin failed." My intent was to handle the cin fail case and prompt the user again. int number; do{ cout << "Enter a number (0 to exit): "; ci...
You need to clear the line from cin, using cin.ignore, in addition to clearing the stream state (which is what cin.clear does). I have several utility functions to make this easier (you'll be interested in clearline in particular, which clears the stream state and the current line) and almost an exact example of what y...
2,032,939
2,032,969
Why is COM (Component Object Model) language-independent?
I know that COM provides reusability at the binary level across languages and applications. I read that all components built for COM must adhere to a standard memory layout in order to be language-independent. I do not understand what "standard memory layout" means. What makes COM language-independent?
First, some technical background: C++ compilers usually generate something called a "vtable" for any class with virtual functions. This is basically a table of function pointers. The vtable contains a function pointer to every virtual method implemented by a class. In COM, interfaces are basically abstract base classes...
2,033,110
2,033,112
Passing a string literal as a type argument to a class template
I want to declare a class template in which one of the template parameters takes a string literal, e.g. my_class<"string">. Can anyone give me some compilable code which declares a simple class template as described? Note: The previous wording of this question was rather ambiguous as to what the asker was actually try...
Sorry, C++ does not currently support the use of string literals (or real literals) as template parameters. But re-reading your question, is that what you are asking? You cannot say: foo <"bar"> x; but you can say template <typename T> struct foo { foo( T t ) {} }; foo <const char *> f( "bar" );
2,033,258
2,033,308
Creating libraries for Arduino
I want to write a library for my Arduino(header and class files), but I don't know what tools to use for this job and how to test and debug them. The Arduino IDE just helps in writing plain programs for direct bootloading, not full project management thing (correct me if I am wrong and guide appropriately with relevant...
The compiler supports the #include directive, you can write your library, then #include it. This is expanded on in this tutorial about writing libraries for the Arduino.
2,033,306
2,033,365
Looking for a permissive and active cross-platform image processing library in C/C++
I'm looking a cross-platform image processing library in C/C++ which is under active development. One more requirement: No GPL license. Some references: Fast Cross-Platform C/C++ Image Processing Libraries Cross-platform drawing library
We used ImageMagick for some courses in university. Played quite well.
2,033,473
2,033,495
How to sort filenames with possibly unpadded numbers in c++?
I need to sort filenames that can have a common root, but are then followed by numbers that are not necessarily padded uniformely; one example is what you obtain when you rename multiple files in Windows. filenamea (1).txt filenamea (2).txt ... filenamea (10).txt ... filenamea (100).txt ... filenameb.txt ... filenamec ...
There are already similar questions, I know of Sort on a string that may contain a number and How to implement a natural sort algorithm in C. So you can also look there for more inspiration and help. Both questions' answers suggest, http://www.davekoelle.com/alphanum.html, which is basically what Pascal Cuoq suggested....
2,033,608
2,033,632
MinGW linker error: winsock
I am using MinGW compiler on Windows to compile my C++ application with sockets. My command for linking looks like: g++.exe -Wall -Wno-long-long -pedantic -lwsock32 -o dist/Windows/piskvorky { there are a lot of object files } and I have also tried g++.exe -Wall -Wno-long-long -pedantic -lws2_32 -o dist/Windows/piskv...
Put the -lws2_32 AFTER the list of object files - GCC searches libraries and object files in the order they appear on the command line. Just to help the other viewers out there: gcc hello.c -o hello.o -lws2_32
2,033,809
2,033,920
I'm using Crypto++ for RSA encryption. My plain text exceeds FixedMaxPlaintextLength. What should I do?
Should I break the text into chunks? Is RSA the wrong encryption scheme?
Wrong scheme. The standard technique for message encryption (for example, PGP and CMS) is to generate a random symmetric session key K for something like AES and encrypted the message with AES using key K. Then encrypt K with the public key of each recipient of the message.
2,033,878
2,034,182
Cross-platform redirect of standard input and output of spawned process in native C/C++ (edit with solution)
I have a string command I'd like to execute asynchronously while writing to its input and reading its output. Sounds easy, right, the devil is in the cross-platform. I'm targeting both MSVC/Win32 and gcc/Linux and obviously want to write the minimum amount of platform-specific code. My google-fu has failed me, I get to...
for converting windows HANDLEs to C file descriptors use _open_osfhandle http://msdn.microsoft.com/en-us/library/bdts1c9x%28VS.71%29.aspx EDIT: this example once helped me aswell with a similar problem: http://www.halcyon.com/~ast/dload/guicon.htm
2,033,903
2,034,131
How many palindromes can be formed by selections of characters from a string?
I'm posting this on behalf of a friend since I believe this is pretty interesting: Take the string "abb". By leaving out any number of letters less than the length of the string we end up with 7 strings. a b b ab ab bb abb Out of these 4 are palindromes. Similarly for the string "hihellolookhavealookatthispalind...
First of all, your friend's solution seems to have a bug since strchr can search past max. Even if you fix this, the solution is exponential in time. For a faster solution, you can use dynamic programming to solve this in O(n^3) time. This will require O(n^2) additional memory. Note that for long strings, even 64-bit i...
2,033,908
2,033,943
How do you determine full paths from filename command line arguments in a c++ program?
I am writing a program in c++ that accepts a filename as an argument on the command line: >> ./myprogram ../path/to/file.txt I know I can simply open an fstream using argv[1], but the program needs more information about the exact location (ie. full pathname) of the file. I thought about appending argv[1] to getcwd(),...
Pathname handling is highly OS-specific: some OS have a hierarchy with just one root (e.g. / on Unix ), some have several roots a la MS-DOS' drive letters; some may have symbolic links, hard links or other kinds of links, which can make traversal tricky. Some may not even have the concept of a "canonical" path to a fi...
2,033,997
2,034,007
How to compile for Windows on Linux with gcc/g++?
I have written some effects in C++ (g++) using freeglut on Linux, and I compile them with g++ -Wall -lglut part8.cpp -o part8 So I was wondering if it is possible to have g++ make static compiled Windows executables that contains everything needed? I don't have Windows, so it would be really cool, if I could do that o...
mingw32 exists as a package for Linux. You can cross-compile and -link Windows applications with it. There's a tutorial here at the Code::Blocks forum. Mind that the command changes to x86_64-w64-mingw32-gcc-win32, for example. Ubuntu, for example, has MinGW in its repositories: $ apt-cache search mingw [...] g++-mingw...
2,034,450
2,034,454
size of dynamically allocated array
Is it true that a pointer assigned to the starting address of a dynamically allocated array does not have the information of the size of the array? So we have to use another variable to store its size for later processing the array through the pointer. But when we free the dynamically allocated array, we don't specify ...
Yes, this is true. delete knows the size of the memory chunk because new adds extra information to the chunk (usually before the area returned to the user), containing its size, along with other information. Note that this is all very much implementation specific and shouldn't be used by your code. So to answer your la...
2,034,465
2,034,493
How to make exe in Qt?
I'm starting to learn Qt and I'm stuck on particular step, which is: I cannot create executable file. My steps are as follows: Creation of *.cpp In console typing qmake -project (this creates .pro file) In console typing qmake -makefile (now I have makefile + some other files) I'm trying to create .exe by typing qmake...
It depends on what compiler you are using. If you're using GCC or MinGW, type make. If make cannot be found, either it is not installed, or it's not in your path (more likely to be the case). Try using the command prompt shortcut Qt provides you (if on Windows). If on a POSIX-based/-like system, make should exist. If i...
2,034,635
2,034,756
explicit copy constructor or implicit parameter by value
I recently read (and unfortunately forgot where), that the best way to write operator= is like this: foo &operator=(foo other) { swap(*this, other); return *this; } instead of this: foo &operator=(const foo &other) { foo copy(other); swap(*this, copy); return *this; } The idea is that if operator=...
You probably read it from: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/ I don't have much to say since I think the link explains the rationale pretty well. Anecdotally I can confirm that the first form results in fewer copies in my builds with MSVC, which makes sense since compilers might not be able ...
2,034,835
2,034,851
linked-list in C++ how to go to "next element" using STL list
I have a very basic question. I want to use STL's list instead of creating my own linked-list ( my code is shown below) struct myList { myList *next; myList *previous; }; myList->next = NULL; Using STL list: #include <list> std::list<int> L; L.push_back(1); My question is, how to access the "next" element ...
std::list is a container. To access individual nodes, you need to use an iterator. For example, to get the head node, you use std::list<int>::const_iterator cit = L.begin(); To move to the next node, you use ++ cit;
2,034,916
2,034,936
Is it okay to inherit implementation from STL containers, rather than delegate?
I have a class that adapts std::vector to model a container of domain-specific objects. I want to expose most of the std::vector API to the user, so that they may use familiar methods (size, clear, at, etc...) and standard algorithms on the container. This seems to be a reoccurring pattern for me in my designs: class M...
The risk is deallocating through a pointer to the base class (delete, delete[], and potentially other deallocation methods). Since these classes (deque, map, string, etc.) don't have virtual dtors, it's impossible to clean them up properly with only a pointer to those classes: struct BadExample : vector<int> {}; int m...
2,034,951
2,034,971
Enforcing File Integrity
I've been working on a project in C++ using openGL and am looking to save the current scene to a text file. Something simple along the lines of, cube at x,y,z and its color etc. My question is about how to make sure that the file has not been changed by a user. I thought about calculating a checksum of the string and ...
theoretically: you can't. practically: encrypt it and obfuscate the key within your program (this is how much of DRM works) although you will never be able to stop a determined user. Why is it so important that the user can't modify it? If you want users to be able to read, but not modify make the last line a HMAC of t...
2,034,955
2,037,190
VC++ Library Clashing Problem
I am working on a C++ project that uses Qt (gui lib), VTK (graphics lib) and another library which is so obscure I won't mention its name and will instead call it LIB_X. The project uses Qt for the gui components and VTK (more precisely the QVTKWidget extension provided by VTK that supports Qt) for rendering geometry....
I encountered a bunch of LNK4006 errors when linking my app to a library (call it library LIB_Y) that made heavy use of std::vector<std::string>, which I also did in my app. After a bit of experimenting I found one solution that worked -- wrap LIB_Y in a separate DLL that calls LIB_Y (LIB_Y_WRAPPER, say), and then link...
2,035,083
2,035,104
Compile to a stand-alone executable (.exe) in Visual Studio
how can I make a stand-alone exe in Visual Studio. Its just a simple Console application that I think users would not like to install a tiny Console application. I compiled a simple cpp file using the visual studio command prompt. Will the exe work even if the .NET framework is not installed? I used native C++ code.
Anything using the managed environment (which includes anything written in C# and VB.NET) requires the .NET framework. You can simply redistribute your .EXE in that scenario, but they'll need to install the appropriate framework if they don't already have it.
2,035,243
2,035,271
Java C++ without JNI
My app is written in Java. There is a C++ library I need to utilize. I don't want to use JNI. 60 times a second, the C++ app needs to send the Java app 10MB of data; and the Java app needs to send the C++ app 10 MB of data. Both apps are running on the same machine; the OS is either Linux or Mac OS X. What is the most ...
Using mapped files is a way of hand-rolling a highly optimized rpc. You might consider starting with a web service talking over local sockets, using MTOM for attaching the data, or just dropping it into a file. Then you could measure the performance. If the data was a problem, you could then use mapping. Note that ther...
2,035,287
2,035,316
Static Runtime Library Linking for Visual C++ Express 2008
How do you tell Visual C++ Express 2008 to statically link runtime libraries instead of dynamically? My exes do not currently run on computers w/o some sort of VS installed and I would love to change that. :)
Sorry, I do not have VC++ Express to test, but in Standard edition I use Project Properties -> Configuration Properties -> C/C++ -> Code Generation -> Runtime Library. Dll and Dll Debug are for dynamic linking.
2,035,348
2,035,471
Can we design singleton by setting all the data member and method of a class to be static?
how to answer this question?
EDIT: Oops, the answer no. As others have pointed out, simply setting all methods/members to static follows the Monostate pattern (of which I was not aware). I was too eager to show off my shiny Singleton template (a simplified version of Alexandrescu's SingletonHolder, really). This answer should be downvoted. Origina...
2,035,595
2,035,779
C++ Xcode assert evaluated in release
I'm quite new to Xcode (and Mac in general). I started a little iPhone project - coding in C++ whatever possible - and just noted that my assert(); commands are executed also in release mode. Is this a known problem and how do I solve it properly? thanks!
Xcode does not add -DNDEBUG for release mode automatically. To add it, go to Project | Edit Project Settings. You need to be on the Build tab and choose Configuration Release. Add a new Preprocessing Macro of NDEBUG.
2,035,609
2,037,177
How do I implement port redirecting/mapping on windows?
I am programming a web proxy that is installed on client machines (same machine as the web browser). I would like for all traffic that is web traffic to get redirected into my proxy server. I am using a windows operating system (XP, Windows 2003, Windows 2008, Vista, Windows 7). What would I need to do, to redirect al...
Your options are Application Layer Proxy (= browser proxy settings), Layered Service Provider; TDI driver (or more modern equivalent?); NDIS driver. There is no simple answer to what is best or easiest. You need to take your own skill set into account, as well as the potential compatibility issues. Lots of other progra...
2,035,838
2,035,850
What language do they build other languages with?
What language is used to build low level languages like c++ and java? How could you build the first language with no language?
In the context of compilers, this operation is often called bootstrapping. In particular, see the "Chicken and egg problem" section for a direct answer to your question. The very first compiler would have been hand-written in assembly language. If your next question is "how was the first assembler written?" then the an...