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
836,342
839,592
Mark class/method obsolete or deprecated in C++
Is there a way of marking methods/classes in C++ as obsolete? In c# you can write: [Obsolete("You shouldn't use this method anymore.")] void foo() {} I use the GNU toolchain/Eclipse CDT if that matters.
The easiest way is with a #define DEPRECATED. On GCC, it expands to __attribute__((deprecated)), on Visual C++ it expands to __declspec(deprecated), and on compilers that do not have something silimar it expands to nothing.
836,469
836,485
Cross platform programming
I need to write a small program for the university. The problem is, it has to be in C/C++ under linux, and I've never used linux, I anticipate having a lot of problems with the IDE, compilation, and all that. Is it possible to code it under windows and then "copy/paste" the code and compile it under linux? What are lim...
I think you should go ahead and do it under Linux (gcc?). This will teach you some stuff about 'old school' programming. Forget about using an IDE, use vim (if you already get it) or nedit (more like notepad). Compile on the command line. Link it yourself. Write a make file to do this. This is the basics. You need to u...
836,511
6,153,500
What are some techniques for migrating a large MFC application to WPF/.NET?
I am currently working on a very large legacy MFC MDI application. It has a large number of UI elements - dockable toolbars, custom tree controls, context menus, etc. It is an image processing application so the main views render themselves using DirectX and OpenGL. The product is about 10 years old and one of the p...
Revisiting this because I have successfully replaced our top level MFC UI (the main frame, windows, and toolbars) with WPF. As it turns out, our core drawing code merely needs to be handed an HWND to render into. This made it really easy to reuse the bulk of our existing C++ codebase. Here's a quick rundown on the key...
836,551
836,613
Forward declare a class's public typedef in c++
I'm trying to simplify a bunch of header file "include spaghetti" by using forward declarations and moving #includes into the implementation file. However, I keep coming upon the following scenario: //Foo.h #include "Bar.h" class Foo { public: void someMethod(Bar::someType_t &val); }; //Bar.h . . . class Bar { pub...
Unfortunately you don't have many choices and none is perfect. First, the two obvious and unacceptable solutions: You can forward declare the typedef which totally defeats the purpose of using a typedef. You include the file which contains the typedef, which you want to avoid. The more interesting solutions: Have al...
836,705
836,841
Why all java methods are implicitly overridable?
In C++, I have to explicitly specify 'virtual' keyword to make a member function 'overridable', as there involves an overhead of creating virtual tables and vpointers, when a member function is made overridable (so every member function is implicitly not overridable for performance reasons). It also allows a member fu...
The better question might be "Why does C# have non-virtual methods?" Or at the very least, why aren't they virtual by default with the option to flag them as non-virtual? In C++, there is the idea (as Brian so nicely pointed out) that if you don't want it, you don't pay for it. The problem is that if you do want it, ...
837,073
844,430
Error C1047: Object file created with an older compiler than other objects
I have a project that I'm building in C++ in Release mode in Visual Studio 2008 SP1 on Windows 7 and when I build it I keep getting: fatal error C1047: The object or library file '.\Release\foobar.obj' was created with an older compiler than other objects; rebuild old objects and libraries. The error occurs w...
I would suggest reinstalling VS 2008 SP1. Have you installed a different VS (e.g. VS Express) in the meantime? This is known to cause interference with an existing VS installation. You could try checking the compiler and linker versions by running cl.exe and link.exe from the Visual Studio command prompt.
837,088
846,589
Problems with Static Initialization
I'm having some weird issues with static initalization. I'm using a code generator to generate structs and serialization code for a message passing system I wrote. In order to have a way of easily allocating a message based on it's message id I have my code generator ouput something similar to the following for each me...
Turns out that the object files containing the static initializers were not included by the linker because nothing referenced any functions in them. To work around this I extern "C"-ed one of the generated functions so that it would have a predictable non-mangled name and then forced a reference to it using a pragma li...
837,203
837,243
Using Hash Maps to represent an extremely large data source
I have a very large possible data set that I am trying to visualize at once. The set itself consists of hundreds of thousands of segments, each of which is mapped to an id. I have received a second data source that gives more real-time information for each segment, but the id's do not correspond to the id's I have. I ...
If you're only dealing with hundreds of thousands of datapoints, it will likely not be a problem to go with the naive way and just stick with a hash-map. Even if you have 500,000 9-character strings and an equal number of longs, that still only 16ish bytes per item, or 8,000,000 bytes total. Even if you double that fo...
837,265
837,446
Why is there no ^^ operator in C/C++?
& has &&. | has ||. Why doesn't ^ have ^^? I understand that it wouldn't be short-circuiting, but it would have different semantics. In C, true is really any non-zero value. Bitwise XOR is not always the same thing as logical XOR: int a=strcmp(str1,str2);// evaluates to 1, which is "true" int b=strcmp(str1,str3);// eva...
Dennis Ritchie answers There are both historical and practical reasons why there is no ^^ operator. The practical is: there's not much use for the operator. The main point of && and || is to take advantage of their short-circuit evaluation not only for efficiency reasons, but more often for expressiveness and correctn...
837,267
837,291
Safe to store list::iterator for later use?
Suppose I have a list, in which no new nodes are added or deleted. However, the nodes may be shuffled around. Is it safe to save an iterator, pointing to a node in the list, and access it at some arbitrarily later time? Edit (followup question): The documentation for list::splice() says that it removes elements from t...
Yes, std::list iterators are just pointers to a node. You can insert, delete (other nodes), and rearrange nodes in the list and the iterator is not invalidated.
837,521
837,601
C++ STL's String eqivalent for Binary Data
I am writing a C++ application and I was wondering what the C++ conventional way of storing a byte array in memory. Is there something like a string, except specifically made for binary data. Right now I am using a *unsigned char** array to store the data, but something more STL/C++ like would be better.
I'd use std::vector<unsigned char>. Most operations you need can be done using the STL with iterator ranges. Also, remember that if you really need the raw data &v[0] is guaranteed to give a pointer to the underlying array.
837,671
837,696
Which libraries must be linked with protocol-buffers generated C++ code
I have the mytest.cc and mytest.h output from a mytest.proto file, but I can't find any reference on to how to compile a object using g++ for this. (the .proto is fine as I got it working with Python) g++ mytest.cc -l??????? what libraries to include?
I think you may need to link to libprotobuf g++ mytest.cc -lprotobuf -o mytest
837,772
840,468
How do I pass a list of objects from C++ to Lua?
I'm the lead dev for Bitfighter, and am adding user-scripted bots using Lua. I'm working with C++ and Lua using Lunar to glue them together. I'm trying to do something that I think should be pretty simple: I have an C++ object in Lua (bot in the code below), and I call a method on it that (findItems) which causes C++ ...
So you need to fill a vector and push that to Lua. Some example code follows. Applications is a std::list. typedef std::list<std::string> Applications; I create a table and fill it with the data in my list. int ReturnArray(lua_State* L) { lua_createtable(L, applications.size(), 0); int newTable = lua_gettop(L)...
838,098
838,125
CListControl selection (MFC)
In report view in a CListCtrl in MFC, how do I detect if there is no current highlighted selection? Using GetFirstSelectedItemPosition doesn't work because if an item was previously selected and then clicked somewhere else on the list control, GetFirstSelectedItemPosition still reports the last position selected instea...
Did you try CListCtrl::GetSelectedCount?
838,345
838,363
How to reduce code duplication on class with data members with same name but different type?
I have trouble when designing classes like this class C1 { public: void foo(); } class C2 { public: void foo(); } C1 and C2 has the same method foo(), class Derived1 : public Base { public: void Update() { member.foo(); } private: C1 member; } class Derived2 : public Base { public: void Update() ...
This is exactly the sort of application that class templates are designed for. They allow functions within a class to operate on different data types, without the need to copy algorithms and logic. This Wikipedia page will give you a good overview of templates in programming. Here's the basic idea to get you started: ...
838,384
1,267,878
Reorder vector using a vector of indices
I'd like to reorder the items in a vector, using another vector to specify the order: char A[] = { 'a', 'b', 'c' }; size_t ORDER[] = { 1, 0, 2 }; vector<char> vA(A, A + sizeof(A) / sizeof(*A)); vector<size_t> vOrder(ORDER, ORDER + sizeof(ORDER) / sizeof(*ORDER)); reorder_naive(vA, vOrder); // A is now { 'b', '...
This algorithm is based on chmike's, but the vector of reorder indices is const. This function agrees with his for all 11! permutations of [0..10]. The complexity is O(N^2), taking N as the size of the input, or more precisely, the size of the largest orbit. See below for an optimized O(N) solution which modifies the i...
838,460
838,468
Java Exception vs C++ Exceptions
Where are exceptions stored ? Stack, Heap. How is memory allocated and deallocated for Exceptions? Now if you have more than one exception which needs to be handled are there objects of all these exceptions created?
I would assume that memory for exceptions is allocated the same way as for all other objects (on the heap). This used to be a problem, because then you cannot allocate memory for an OutOfMemoryError, which is why there was no stack trace until Java 1.6. Now they pre-allocate space for the stacktrace as well. If you ar...
838,639
838,720
What cast occurs when there is a signed/unsigned mismatch?
When a compiler finds a signed / unsigned mismatch, what action does it take? Is the signed number cast to an unsigned or vice versa? and why?
If operand are integral and there is an unsigned value, then conversion to unsigned is done. For example: -1 > (unsigned int)1 // as -1 will be converted to 2^nbits-1 Conversion int->unsigned int is: n>=0 -> n; n<0 -> n (mod 2^nbits), for example -1 goes to 2^nbits-1 Conversion unsigned int->int is: n <= INT_MAX -> n;...
838,670
838,842
Is there a way to forbid casting to subclass that is non-const in C++?
Here is a complete example. I want to forbid using A::set from objects casted from B to A by allowing only casting B to const A. How to do it? (I can't use virtual functions) #include <iostream> #include <cassert> using namespace std; class A { public: int get() const { return i_; } void set(int i) { i_ = i; }...
You could make the inheritance private and provide a member function in B to use instead of casting. const A& B::convert_to_A() const { return *this; }
838,674
838,785
Throwing Destructors, Memory Corruption?
We have a class whose semantic behaviour is like the following :- struct Sample { ~Sample() throw() { throw 0; } }; void f () { try { delete new Sample; } catch (...){ } } I know that throwing exceptions in dtors is evil; but the relinquishment of a 3rd Party library resource is throwing an e...
There are two things that could happen in this situation: terminate() is called undefined behaviour In neither case can dynamically allocated memory be guaranteed to be released (except that application termination will of course return all resources to the OS).
838,721
838,986
C++ iterators considered harmful?
At the Boost library conference today, Andrei Alexandrescu, author of the book Modern C++ Design and the Loki C++ library, gave a talk titled "Iterators Must Go" (video, slides) about why iterators are bad, and he had a better solution. I tried to read the presentation slides, but I could not get much out of them. Are...
First, to answer your questions: No. In fact, I argued elsewhere that iterators are the most important/fundamental concept of computer science ever. I (unlike Andrei) also think that iterators are intuitive. Yes, definitely but that shouldn't come as a surprise. Hmm. Looking at Boost.Range and C++0x – haven't they alr...
838,816
838,859
Call C++ code from a C# application or port it?
I've recently been wrestling with an algorithm which was badly implemented (i.e. the developer was pulled off onto another project and failed to adequately document what he'd done) in C#. I've found an alternative (from numerical recipes) which works but is written in C++. So I'm thinking probably the safest way to ge...
I tried linking to c-dll's from c# code with quite good results, even though I had some problems sending data between the environments. Otherwise the procedure is quite straight forward. The more data you send back and forth (both amount and frequency) the slower your program will run, but you have probably already fig...
838,917
838,932
How does the compiler resolve infinite reference loops?
// edited by Neil Butterworth to conserve vertical space #include <stdio.h> struct A; struct B; A& GetAInstance(); B& GetBInstance(); struct A { A() { printf( "A\n" ); } ~A() { printf( "~A\n" ); B& b = GetBInstance(); } }; struct B { B() { printf( "B\n" ); }...
The compiler effectively stores a bool with each static to remember whether it has been initialised. This is the order: Inside main: Construct A Destruct A Construct static B Clean-up of statics: Destruct static B Construct static A Destruct static A 3.6.3/1 in the Standard specifies it should work this way, ev...
839,257
864,834
How do I make a CMFCToolBar recognize image masks?
I have a CMFCToolBar-derived class and an insance thereof is the member of a CDockablePane-derived class. I looked at the VisualStudioDemo sample to see how it's done and have this so far: int CMyPane::OnCreate(LPCREATESTRUCT lpCreateStruct) { // Removed all "return -1 on error" code for better readability CDo...
I don't know if this works every time but I use RGB(192, 192, 192) as the mask color and it does get recognized. (Seems like the CMFCToolBar control is prepared to use ::GetSysColor(COLOR_BTNFACE) as the transparent color...)
839,276
839,286
object returned after an exception?
int somefunction(bool a) { try { if(a) throw Error("msg"); return 2; } catch (Error const & error) { //do i need to return anything here?? //return -1; } }
You need to either return something or re-throw the exception (or throw a new one). You can rethrow the same exception by just using the keyword throw in the catch block with no exception or arguments afterwards.
839,455
839,531
Aggregating contributions from multiple donors
As I try to modernize my C++ skills, I keep encountering this situation where "the STL way" isn't obvious to me. I have an object that wants to gather contributions from multiple sources into a container (typically a std::vector). Each source is an object, and each of those objects provides a method get_contributions(...
Option 3 is the most idiomatic way. Note that you don't have to use back_insert_iterator. If you know how many elements are going to be added, you can resize the vector, and then provide a regular vector iterator instead. It won't call push_back then (and potentially save you some copying) back_insert_iterator's main a...
839,468
839,520
Hints and tools for finding unmatched braces / preprocessor directives
This is one of my most dreaded C/C++ compiler errors: file.cpp(3124) : fatal error C1004: unexpected end-of-file found file.cpp includes almost a hundred header files, which in turn include other header files. It's over 3000 lines. The code should be modularized and structured, the source files smaller. We should ref...
If the #includes are all in one place in the source file, you could try putting a stray closing brace in between the #includes. If you get an 'unmatched closing brace' error when you compile, you know it all balances up to that point. It's a slow method, but it might help you pinpoint the problem.
839,530
839,536
How to add search functionality to my application
I am writing Windows application (with Borland C++ Builder), which stores large number of text files. I want users to be able to search these files very fast, so I need an indexing and search library. I do not use database, but my own file format for storing the documents (all are in a single file). Are there such libr...
CLucene is a C-Port of the lucene (java) library. I have only used the original java version, but lucene is able to do what you are asking for.
839,644
872,971
Get std::fstream failure error messages and/or exceptions
I'm using fstream. Is there any way to get the failure message/exception? For example if I'm unable to open the file?
From checking it out I found that also errno and also GetLastError() do set the last error and checking them is quite helpful. For getting the string message use: strerror(errno);
839,667
839,719
How much should I worry about the Intel C++ compiler emitting suboptimal code for AMD?
We've always been an Intel shop. All the developers use Intel machines, recommended platform for end users is Intel, and if end users want to run on AMD it's their lookout. Maybe the test department had an AMD machine somewhere to check we didn't ship anything completely broken, but that was about it. Up until a few ...
Buy an AMD box and run it on that. That seems like the only responsible thing to do, rather than trusting strangers on the internet ;) Apart from that, I believe part of AMD's lawsuit against Intel is based on the claim that Intel's compiler specifically produces code that runs inefficiently on AMD processors. I don't ...
839,705
839,770
qt trouble overriding paintEvent
I'm subclassing QProgressBar in a custom widget, and I overwrote the paintEvent method with the following code : void myProg::paintEvent(QPaintEvent *pe) { QProgressBar::paintEvent(pe); QRect region = pe->rect(); QPainter *painter = new QPainter(this); QPen *pen = new QPen; painter->begin(this); ...
The coordinate system you need to use is relative to the top-left of the widget, but you're apparently using one relative to the widget's parent. (Widget's x and y coords are relative to their parent). So your line will be getting clipped. Also, it's unnecessary to call QPainter::begin and QPainter::end when you constr...
839,739
1,004,869
With CDatabase, can I send SQL without using CRecordSet?
When using the MFC class CDatabase to connect to a data source, is there any way to execute SQL statements without having to open a CRecordSet object? I ask because CRecordSet::Open() appears to throw an exception when I use it to call stored procedures that don't return anything - and there's no reason to expect resu...
I use CDatabase::ExecuteSQL() CDatabase database; //database is connected somewhere database.ExecuteSql("Drop table [users]"); // sql statement from little Johnny Drop tables
839,765
839,818
The right type for handles in C interfaces
I'm creating a C api that hides some functionality in a DLL file. Since everything is C++ on the inside most of the functions works against handles which maps directly to this pointers on the inside of the API. To get a some degree of type safety for those handles I define them like this: typedef struct MyType1* MyType...
If you look at how Microsoft defines it's winapi handles (winnt.h) it actually looks like this: struct HWND__ { int unused; }; typedef struct HWND__ *HWND in fact they have a macro for this: #define DECLARE_HANDLE(name) struct name##__{int unused;}; typedef struct name##__ *name so.. this seems to be a common practic...
839,856
839,897
Using std:fstream how to deny access (read and write) to the file
How can I deny access to a file I open with fstream? I want to unable access to the file while I'm reading/writing to it with fstream?
You cannot do it with the standard fstream, you'll have to use platform specific functions. On Windows, you can use CreateFile() or LockFileEx(). On Linux, there is flock(), lockf(), and fcntl() (as the previous commenter said). If you are using MSVC, you can pass a third parameter to fstream's constructor. See the doc...
839,958
840,055
Custom Iterator in C++
I have a class TContainer that is an aggregate of several stl collections pointers to TItems class. I need to create an Iterator to traverse the elements in all the collections in my TContainer class abstracting the client of the inner workings. What would be a good way to do this?. Should I crate a class that extends...
When I did my own iterator (a while ago now) I inherited from std::iterator and specified the type as the first template parameter. Hope that helps. For forward iterators user forward_iterator_tag rather than input_iterator_tag in the following code. This class was originally taken from istream_iterator class (and modi...
839,975
840,245
How does c++ by-ref argument passing is compiled in assembly?
In the late years of college, I had a course on Compilers. We created a compiler for a subset of C. I have always wondered how a pass-by-ref function call is compiled into assembly in C++. For what I remember, a pass-by-val function call follows the following procedure: Store the address of the PP Push the arguments o...
int byRef(A& v){ v = A(3); return 0; } This invokes the assignment of the temporary object to the object passed by reference, the object used in the function call is modified. A shallow copy will be performed if no assignment operator is provided. int byP (A* v){ v = &A(4); //OR new A(4) return 0; } This co...
840,023
840,069
Efficient coding help
I am currently writing code in C++ to find all possible permutations of 6 integers and store the best permutation (i.e. the one whose total is closest to a given value). I am trying to write this code as efficiently as possible and would apreciate any advice or examples. I was considering storing the integers in an arr...
They already thought of this one for you: #include <algorithm> int ra[6] = { 1, 2, 3, 4, 5, 6 }; do { // whatever } while (std::next_permutation(ra, ra+6)); Note that the elements have to start in increasing order (by comparison via operator<), or else the loop will terminate before you've seen every permutation...
840,081
840,389
What does floating point error -1.#J mean?
Recently, sometimes (rarely) when we export data from our application, the export log contains float values that look like "-1.#J". I haven't been able to reproduce it so I don't know what the float looks like in binary, or how Visual Studio displays it. I tried looking at the source code for printf, but didn't find an...
It can be either negative infinity or NaN (not a number). Due to the formatting on the field printf does not differentiate between them. I tried the following code in Visual Studio 2008: double a = 0.0; printf("%.3g\n", 1.0 / a); // +inf printf("%.3g\n", -1.0 / a); // -inf printf("%.3g\n", a / a); // NaN which re...
840,321
840,363
How can I see the assembly code for a C++ program?
How can I see the assembly code for a C++ program? What are the popular tools to do this?
Ask the compiler If you are building the program yourself, you can ask your compiler to emit assembly source. For most UNIX compilers use the -S switch. If you are using the GNU assembler, compiling with -g -Wa,-alh will give intermixed source and assembly on stdout (-Wa asks compiler driver to pass options to assembl...
840,522
840,532
Given a pointer to a C++ object, what is the preferred way to call a static member function?
Say I have: class A { public: static void DoStuff(); // ... more methods here ... }; And later on I have a function that wants to call DoStuff: B::SomeFunction(A* a_ptr) { Is it better to say: a_ptr->DoStuff(); } Or is the following better even though I have an instance pointer: A::DoStuff() } This...
I think I'd prefer "A::DoStuff()", as it's more clear that a static method is being called.
840,888
841,029
How does code written in one language get called from another language
This is a question that I've always wanted to know the answer, but never really asked. How does code written by one language, particularly an interpreted language, get called by code written by a compiled language. For example, say I'm writing a game in C++ and I outsource some of the AI behavior to be written in Schem...
There is no single answer to the question that works everywhere. In general, the answer is that the two languages must agree on "something" -- a set or rules or a "calling protocol". In a high level, any protocol needs to specify three things: "discovery": how to find about each other. "linking": How to make the conne...
840,960
840,971
What does it mean when "virtual" is in "class Foo : public virtual Bar" as opposed to "virtual void frob()"?
I understand virtual in the context of a member function, like virtual void frob(). But what does it mean in the context of the class declaration, like class Foo : public virtual Bar? For a given method there are 8 cases stemming from the presence or absence of virtual in the following three locations: 1) a superclass'...
That's virtual inheritance, you do it when you know you'll be doing multiple inheritance. That page goes into way more detail.
841,038
841,046
Large buffers vs Large static buffers, is there an advantage?
Consider the following code. Is DoSomething1() faster then DoSomething2() in a 1000 consecutive executions? I would assume that if I where to call DoSomething1() it 1000 times it would be faster then calling DoSomething2() it 1000 times. Is there any disadvantage to making all my large buffers static? #define MAX_BUFF...
Disadvantage of static buffers: If you need to be thread safe then using static buffers probably isn't a good idea. Memory won't be freed until the end of your program hence making your memory consumption higher. Advantages of static buffers: There are less allocations with static buffers. You don't need to allo...
841,075
841,083
Best C++ Code Formatter/Beautifier
There are lots of source code formatting tools out there. Which ones work best for C++? I'm interested in command-line tools or other things that can be automatically run when checking code in/out, preferably without needing to launch an editor or IDE. (If you see the one you like already listed as an answer, vote it ...
AStyle can be customized in great detail for C++ and Java (and others too) This is a source code formatting tool. clang-format is a powerful command line tool bundled with the clang compiler which handles even the most obscure language constructs in a coherent way. It can be integrated with Visual Studio, Emacs, Vim ...
841,434
2,690,211
How do you manually insert options into boost.Program_options?
I have an application that uses Boost.Program_options to store and manage its configuration options. We are currently moving away from configuration files and using database loaded configuration instead. I've written an API that reads configuration options from the database by hostname and instance name. (cool!) H...
My answer comes a little too late, but I spent some time trying to do something similar and found an annoyingly obvious solution (incase anyone else is looking for this)... Recalling that boost::program_options::variables_map derives from std::map<std::string, boost::program_options::variable_value>, you can do perfect...
841,471
853,791
wxwidgets // g++ Compiler error: no matching function for call to 'operator new(..'
At the moment I am trying to port a Visual C++ application to Linux. The code compiles without errors in Visual Studio, but I get many compiler errors under Linux. One of these errors is: ../src/wktools4.cpp:29: error: no matching function for call to 'operator new(unsigned int, const char[40], int)' More information:...
I found the error: #ifdef __WXDEBUG__ #define new WXDEBUG_NEW #endif When I remove these lines, I don't get the errors any more. The code was generated from a wxwidgets wizard for VisualStudio. I have no idea what it does... Thank you all for your help! Now I have to fix the linker errors ;)
841,619
841,666
C++ constructor problem
#include <iostream> using namespace std; // This first class contains a vector and a scalar representing the size of the vector. typedef class Structure1 { int N; double* vec; public: // Constructor and copy constructor: Structure1(int Nin); Structure1(const Structure1& structurein); // Accessor functions: int...
By the way, I think you need to fix the copy constructor: Structure1::Structure1(const Structure1& structurein) { ///!!!! Initialize N N = structurein.N; vec = new double[structurein.N]; for(int i = 0; i < structurein.N; i++) { vec[i] = structurein.vec[i]; }; }
841,705
841,716
C++: Trying to import class as a class member into another class, does not copy properly
Thanks to all that responded to my previous thread. There is still a problem with this simple program that I would like to solve. I am trying to import one class into another as a member object. The output of this program is confusing, though. As a test of the code, I output the scalar contained within the first cl...
Looks like you don't set N in Structure1's copy constructor. You need: Structure1::Structure1(const Structure1& structurein){ N = structurein.N; vec = new double[structurein.N]; for(int i = 0; i < structurein.N; i++) { vec[i] = structurein.vec[i]; } } (Also, you don't need a semicolon after a for-loop. But that'...
841,718
848,157
Programmatically Add/Remove tabs on wxNotebook by PageText
I need to be able to programmatically add and remove tabs on a wxNotebook by the text/label that is displayed on each tab. In windows, using a tab control and tab pages, I would be able to reference each tab by a key. The tab control has a map of tab pages keyed on the text of each tab.
Use the following helper method to convert from the tab label/text to the corresponding index of the wxNotebookPage. After you have the index of the wxNotebookPage, then you can use all of the wxNotebook's methods that expect the page index as an argument. int TabTestFrame::GetIndexForPageName( wxString tabText) { ...
841,966
847,763
How can I disambiguate this template code?
I'm having trouble figuring out how to solve a compiler error I'm running into. I've reduced it down to this simplest-case representation: enum EAtomId { EAtomId_Test }; int StringFormat(char* o_dest, size_t i_destSizeChars, const char* i_format, ...); template <size_t SIZE> int StringFormat(char (&o_dest)[SIZE], EAt...
The problem with the above code is due to ordinary overload resolution rules, and is not specific to templates. The following code with two ordinary functions still shows the ambiguity: enum EAtomId { EAtomId_Test }; const int SIZE=1000; int StringFormat(char * s , size_t i_destSizeChars , const char* i_format ...
842,268
842,278
Need help appending one wchar_t to another! C++
I have tried wcscat() but i get a runtime access violation. wchar_t* a = L"aaa"; wchar_t* b = L"bbb"; wchar_t* c; c = wcscat(a, b); Can somebody tell me what is wrong here? Or another way to solve my problem? Thanks
wcscat doesn't create a new string - it simply appends b to a. So, if you want to make sure you don't cause a runtime access violation, you need to make sure there's space for b at the end of a. In the case above: wchar_t a[7] = L"aaa"; wchar_t b[] = L"bbb"; wchar_t* c; c = wcscat(a, b); You can still get a return va...
842,273
842,311
How to determine whether a C++ template has specified method
Let's suppose I am writing a function template GCD which uses both operator/ and operator%. For some types, for example, complex numbers or polynomials both can be computed efficiently (i.e. when dividing polynomials you get remainder "for free"). So some of my class templates have divmod implemented, which returns a p...
I would go for type traits and template specializations based on that. You can use metaprogramming to determine if the type has divmod, and based on that provide specific parts of a general algorithm. That is, extract the common part of the algorithm into a generic piece of code that calls specialized functions for the...
842,387
842,427
how do I dynamically cast between vectors of pointers?
I have: class T {}; class S: public T {}; vector<T*> v; vector<S*> w; transform(v.begin(), v.end(), dynamic_cast_iterator<S*>(w.begin())); But, of course, dynamic_cast_iterator doesn't exist.
Here is one solution (using boost lambda): #include <boost/lambda/lambda.hpp> #include <boost/lambda/casts.hpp> #include <algorithm> #include <iterator> #include <iostream> namespace bll = boost::lambda; struct A { virtual ~A() { } }; struct B : A { void f() { std::cout << "hello, world" << std::endl; } }; int main(...
842,407
842,453
How can I sort a singly linked list in constant space?
I have a singly linked list and I need to sort it in constant space due to memory limitations (in other words, no extra space should be used that is proportional to the number of items in the list). The structure of the linked list is: head.item = the payload you want to sort on; and head.next = the next item. The re...
Sorting a linked list in constant space is easy, you just have to adjust the pointers. The easiest way to do this is to use a sort algorithm that only swaps adjacent elements. I'm going to provide a bubble-sort, just because you've made no requirement for efficiency: # Enter loop only if there are elements in list. sw...
842,563
842,682
LSB AppChecker: GCC links against unused libraries
I'm checking the portability of a shared object (.so) with the LSB AppChecker. One of the problems it reports is that there is one external library (libm.so.6) that is not being used but is linked against anyways. How can I prevent GCC from linking to this unneeded library? EDIT: The output of the ldd command against m...
Pass the -Wl,-as-needed argument as part of the linker command line. This will automatically drop any direct library dependencies you're not actually using symbols from. $ g++ -o test test.cpp -lm; readelf -d test|grep '(NEEDED)' 0x0000000000000001 (NEEDED) Shared library: [libstdc++.so.6] 0x0000000000000...
842,753
842,771
Operator Overloading
I'm new to C++, this is my first week since the upgrade from fortran. Sorry if this is a simple question, but could someone help me with operator overloading. I have written a program which has two classes. One object contains a vector and two scalars, the other class simply contains the first object. In a test imp...
it looks like vec0 isn't initialized by your copy constructor... Try modifying your copy constructor to: Structure1::Structure1(const Structure1& structurein) { N = structurein.N; vec = new double[N]; for (int i = 0; i < N; i++) { vec[i] = structurein.vec[i]; } // ADD THIS LINE vec0 ...
842,843
843,920
Window Hooking Questions
Is am using this: SetWindowsHookEx(WH_CALLWNDPROC, ...); I can see the messages I want to process, but I want to prevent those message from reaching the target window. So I tried this: SetWindowsHookEx(WH_GETMESSAGE, ...); When I do this I can modify the message, and prevent the target window from processing it, but ...
You can't subclass a window in a another process, but the hook DLL should be able to subclass the window you're interested in. WH_GETMESSAGE and WH_CALLWNDPROC hooks run in the context of the process receiving the message, so at that point you have an "in" to subclass the target's window.
842,935
842,958
memcpy not doing as it is supposed to
I have this bit of code that is outputting the wrong results. #include <stdio.h> #include <string.h> int main() { unsigned char bytes[4]; float flt=0; bytes[0]=0xde; bytes[1]=0xad; bytes[2]=0xbe; bytes[3]=0xef; memcpy( &flt, bytes, 4); printf("bytes 0x%x float %e\n", flt, flt); return 0; } the o...
It is not problem of memcpy. float is allways converted to double when passed over ... of printf, so you just can't get 4 bytes on most of intel architectures. when you expacting 0xdeadbeef in this code, you assume that your architecture is BIG endian. There are many little endian architectures, for example Intel x86....
843,154
843,161
Fastest way to find the number of lines in a text (C++)
I need to read the number of lines in a file before doing some operations on that file. When I try to read the file and increment the line_count variable at each iteration until I reach EOF. It was not that fast in my case. I used both ifstream and fgets. They were both slow. Is there a hacky way to do this, which is a...
The only way to find the line count is to read the whole file and count the number of line-end characters. The fastest way to do this is probably to read the whole file into a large buffer with one read operation and then go through the buffer counting the '\n' characters. As your current file size appears to be about ...
843,238
843,249
SQLite3 - Cannot Open Database
I have the following code: #include <iostream> #include <string> #include "sqlite3.h" int main() { sqlite3* db; int rc = sqlite3_open("testing.db", &db); std::cout << rc << std::endl; std::cout << sqlite3_errmsg(db); std::cin >> rc; } When I run it, the program outputs "21" and "library routine c...
Call sqlite3_errmsg() to get the actual error message. Edit: When I run your code, it returns 0. Seems to work fine here. Which system are you running the code on? How was your code compiled?
843,247
843,254
type/value mismatch in template C++ class declaration
I am trying to compile the following code on Linux using gcc 4.2: #include <map> #include <list> template<typename T> class A { ... private: std::map<const T, std::list<std::pair<T, long int> >::iterator> lookup_map_; std::list<std::pair<T, long int> > order_list_; }; When I compile this class I receive the...
You need to write typename before std::list<...>::iterator, because iterator is a nested type and you're writing a template. Edit: without the typename, GCC assumes (as the standard requires) that iterator is actually a static variable in list, rather than a type. Hence the "parameter type mismatch" error.
843,389
843,414
The Pimpl Idiom in practice
There have been a few questions on SO about the pimpl idiom, but I'm more curious about how often it is leveraged in practice. I understand there are some trade-offs between performance and encapsulation, plus some debugging annoyances due to the extra redirection. With that, is this something that should be adopted on...
I'd say that whether you do it per-class or on an all-or-nothing basis depends on why you go for the pimpl idiom in the first place. My reasons, when building a library, have been one of the following: Wanted to hide implementation in order to avoid disclosing information (yes, it was not a FOSS project :) Wanted to h...
843,506
843,521
Shell Icon Overlay (C#)
I need a method to create Icon Overlay's for Folders and Files in Windows XP/Vista, using C# or C++? Any examples? Thanks, -Sean!
Tigris' TortoiseSVN product heavily uses icon overlays provided by library shared by several Tortoise products, the overlays themselves are written in C++ rather than C#. The documentation for the TortoiseOverlays project explains how they use it and the problems they have encountered (username: guest, empty password),...
843,618
843,628
Failing to use stl containers in templated functions/classes
When I try and compile the following code... #include <vector> template <class T> void DoNothing() { std::vector<T>::iterator it; } int main(int argc, char**argv) { return 0; } g++ says: test.cpp:5: error: expected `;' before ‘it’ And I don't understand why this is a problem. If I replace it with std::ve...
You need to use the typename keyword because the std::vector<T>::iterator type is dependent on the template parameter: template <class T> void DoNothing() { typename std::vector<T>::iterator it; } It can actually be confusing when you need to use typename and when you don't need it (or are even not permitted to us...
843,705
843,747
Large initial memory footprint for native app
I've noticed that the native C++ application I'm working on has quite a large memory footprint (20MB) even before it enters any of my code. (I'm referring to the "private bytes" measure in Windows, which as I understand it is the most useful metric). I've placed a break point on the first line of the "main()" function...
It might be that you're pulling a lot of libraries with your app. Most of them get initialized before execution is handed over to your main(). Check for any non-standard libraries you're linking against. EDIT: A very straightforward solution would be to create a new project and just link the libraries you're using one ...
843,711
843,799
How do I intercept messages being sent to a window?
I want to intercept messages that are being sent to a window in a different process. What is the best way to do this? I can't see the messages when I use the WH_GETMESSAGE hook, and I'm not sure if I can subclass across processes? Any help would be much appreciated.
You need to inject your own code into the process that owns the windows you wish to intercept messages from. Fortunately, SetWindowsHookEx() makes this fairly easy, although you may have a bit of trouble at first if you've only used it for in-process hooking up to now. I can recommend two excellent articles on the sub...
843,714
843,850
Which one to use c++ stl container or the MFC container?
For every stl container there is a MFC container available in visual c++.Which is better than the other one in what sense and what do you use? I always use STL container is that wrong?
MFC collection classes do have some advantages if you are working within confines of MFC land. E.g. you get things like serialization (if your container elements inherit from CObject or similar) and some debugging support for "free". MSDN has a breakdown of how to choose between different MFC collection types [here](ht...
843,996
844,078
What's wrong with passing C++ iterator by reference?
I've written a few functions with a prototype like this: template <typename input_iterator> int parse_integer(input_iterator &begin, input_iterator end); The idea is that the caller would provide a range of characters, and the function would interpret the characters as an integer value and return it, leaving begin at ...
There is nothing really wrong, but it will certainly limit the use of the template. You won't be able to just put an iterator returned by something else or generated like v.begin(), since those will be temporaries. You will always first have to make a local copy, which is some kind of boilerplate not really nice to hav...
844,169
844,172
AccessViolationException on calling the most basic c++ function I can think of from managed code
I'm trying to learn how to use managed/unmanaged code interop, but I've hit a wall that 4 hours of googling wasn't able to get over. I put together 2 projects in visual studio, one creating a win32 exe, and one creating a windows forms .NET application. After a bunch of mucking around I got the C# code to call into t...
You can't call functions in executables from outside those executables. You need to compile your code into a DLL.
844,241
844,256
Why are C++0x rvalue reference not the default?
One of the cool new features of the upcoming C++ standard, C++0x, are "rvalue references." An rvalue reference is similar to an lvalue (normal) reference, except that it can be bound to a temporary value (normally, a temporary can only be bound to a const reference): void FunctionWithLValueRef(int& a) {…} void Function...
It would be pointless. You would change the thing in the function, and the change would be lost immediately because the thing was actually a temporary. The reason for the new type stems from the need to be able to decide what actually is an rvalue and what not. Only then you can actually use them for the cool things t...
844,602
844,613
C GUI, with a C++ backbone?
I have a simple (and also trivial) banking application that I wrote in C++. I'm on ubuntu so I'm using GNOME (GTK+). I was wondering if I could write all my GUI in C/GTK+ and then somehow link it to my C++ code. Is this even possible? Note: I don't want to use Qt or GTKmm, so please don't offer those as answers.
Yes, it's a very easy thing to do. All you have to do is expose some of the C++ functions as "extern C" so that the event handlers and callbacks in your UI code can call them. In the case that you can't change the existing C++ source - no problem. just write a C++ shim for your UI, extern those functions, and call ba...
844,751
966,348
How to integrate native applications with eclipse?
I have a couple of native applications written in C++ and C#. These are legacy applications that require data sharing between them. Currently, data sharing is through import/export of text file in some proprietary format. We are currently looking at integrating these two applications using eclipse. My questions are: H...
If you can write a JNI wrapper around your C++/C# applications, then you can use them from an Eclipse plugin. The simplest approach is to: repackage your C++/C# applications as DLLs (if they aren't already) wrap them with a JNI layer place the DLLs in the root folder of your plugin call System.LoadLibrary() from a st...
844,768
844,779
How is STL iterator equality established?
I was wondering, how is equality (==) established for STL iterators? Is it a simple pointer comparison (and thus based on addresses) or something more fancy? If I have two iterators from two different list objects and I compare them, will the result always be false? What about if I compare a valid value with one that'...
Iterator classes can define overloaded == operators, if they want. So the result depends on the implementation of operator==. You're not really supposed to compare iterators from different containers. I think some debug STL implementations will signal a warning if you do this, which will help you catch cases of this er...
844,914
844,927
How to get form data from HTML page using c++
How do I get form data from HTML page using c++, as far as the basics of post and get? EDIT: CGI is using apache 2 on windows, I got c++ configured and tested with with apache already.
The easiest way to access form data from an HTTP request is via CGI. This involves reading environment variables which is done using the getenv function.
845,447
845,533
Winsock uncontrollably spawns several, persistent threads
I'm designing a networking framework which uses WSAEventSelect for asynchronous operations. I spawn one thread for every 64th socket due to the max 64 events per thread limitation, and everything works as expected except for one thing: Threads keep getting spawned uncontrollably by Winsock during connect and disconnect...
Download the sysinternals tool process explorer. Install the appropriate debugging tools for windows. In process explorer, set Options -> Symbols path to: SRV*C:\Websymbols*http://msdl.microsoft.com/download/symbols Where C:\Websymbols is just a place to store the symbol cache (I'd create a new empty directory for it...
845,705
846,348
Memory Based Data Server for local IPC
I am going to be running an app(s) that require about 200MB of market data each time it runs. This is trivial amount of data to store in memory these days, so for speed thats what i want to do. Over the course of a days session I will probably run, re-run, re-write and re-run etc etc one or more applications over and o...
If you have enough memory and nothing else asks for memory, that might reduce your startup time. To guarantee access to the memory, you probably want to have a memory mapped file in named shared memory, as described here. You can have a simple program create the share and manage it so you can guarantee it remains in ...
845,706
845,785
Is there a way to automatically make a library either static or dynamic?
I know this might be a long shot, but here it goes. I have several active projects and each has sub project library which gets compiled when the main project compiles. These libraries are dynamic ones, but recently there was an issue that might arise a need for those libraries (most of them are shared between projects)...
I like to use CMake to avoid these type of problems.
845,710
845,713
Is there a function that returns the ASCII value of a character? (C++)
I need a function that returns the ASCII value of a character, including spaces, tabs, newlines, etc... On a similar note, what is the function that converts between hexadecimal, decimal, and binary numbers?
char c; int ascii = (int) c; s2.data[j]=(char)count; A char is an integer, no need for conversion functions. Maybe you are looking for functions that display integers as a string - using hex, binary or decimal representations?
845,772
845,786
How to check if the binary representation of an integer is a palindrome?
How to check if the binary representation of an integer is a palindrome?
Since you haven't specified a language in which to do it, here's some C code (not the most efficient implementation, but it should illustrate the point): /* flip n */ unsigned int flip(unsigned int n) { int i, newInt = 0; for (i=0; i<WORDSIZE; ++i) { newInt += (n & 0x0001); newInt <<= 1; ...
845,819
845,830
How can I return an array?
Is there any way to return an array from a function? More specifically, I've created this function: char bin[8]; for(int i = 7; i >= 0; i--) { int ascii='a'; if(2^i-ascii >= 0) { bin[i]='1'; ascii=2^i-ascii; } else { bin[i]='0'; } } and I need a way to return bin[]...
Your array is a local variable allocated on the stack. You should use new [] to allocate it on the heap. Then you can just say: return bin;. Beware that you will have to explicitly free it with delete [] when you are done with it.
845,912
845,917
What is the C++ function to raise a number to a power?
How do I raise a number to a power? 2^1 2^2 2^3 etc...
pow() in the cmath library. More info here. Don't forget to put #include<cmath> at the top of the file.
845,957
845,968
Question About & operator in C++
I am looking at the .h file of a Wrapper class. And the class contains one private member: T* dataPtr; (where T is as in template < class T > defined at the top of the .h file) The class provides two "* overloading operator" methods: T& operator*() { return *dataPtr; } const T& operator*() const { return *dataPt...
The return type T& states that you are returning a reference of an instance of a T object. dataPtr is a pointer, which you "dereference" (get the reference value/instance of a pointer) using *.
846,044
846,055
How to get the filename of a DLL?
I have a C++ Windows application myapp.exe which loads several plug-ins. Plug-ins need to find the path to their DLLs. I can use GetModuleFileName for this, but it need the handle for the plug-in DLL. I don't know where to get this handle. GetModuleHandle(NULL) returns the handle to the executable. One option is to use...
I don't know where to get this handle It's passed as a parameter to your DLLMain() entry function. If the plugin can't access its DLLMain() entry function, it can use the VirtualQuery function on a piece of its own memory and use the AllocationBase field of the filled-in MEMORY_BASIC_INFORMATION structure as its HMOD...
846,121
846,170
C++ adding a carriage return at beginning of string when reading file
I have two questions: 1) Why is my code adding a carriage return at the beggining of the selected_line string? 2) Do you think the algorithm I'm using to return a random line from the file is good enough and won't cause any problems? A sample file is: line number one # line number two My code: int main() { srand(t...
What you probably want is something like this: std::vector<std::string> allParagraphs; std::string currentParagraph; while (std::getline(read, line)) { if (line == "#") { // modify this condition, if needed // paragraph ended, store to vector allParagraphs.push_back(currentParagraph); ...
846,259
846,272
Array of linked lists in C++
Some code for context: class WordTable { public: WordTable(); ~WordTable(); List* GetListByAlphaKey(char key); void AddListByKey(char key); bool ListExists(char key); bool WordExists(string word); void AddWord(string word); void IncrementWordOccurance...
An initialization for _listArray would look like this: WordTable::WordTable() { for (int i=0; i<33; i++) _listArray[i] = new List(); } You don't really say what exactly the problem is so I'm not sure if this helps...
846,444
846,456
C++ question... definition doesn't recognize vectors specified in declaration
I'm working on a class assignment that started small, so I had it all in one file. Now it's gotten bigger and I'm trying to separately compile main, functions, and classes (so all the classes are together in one .h and one .cpp) I have one class B, which is the parent of a lot of others and comes first in the file. One...
It's not just vector. It's std::vector because it is within the namespace called std. That's why the compiler moans. It doesn't know what vector<A*> means. Say std::vector<A*> instead. Do not add using namespace std; now into the header because of this. It may be OK for the assignment to put it into the .cpp file to sa...
846,566
846,625
Using Boost on ubuntu
I've heard a lot of good comments about Boost in the past and thought I would give it a try. So I downloaded all the required packages from the package manager in Ubuntu 9.04. Now I'm having trouble finding out how to actually use the darn libraries. Does anyone know of a good tutorial on Boost that goes all the way fr...
Agreed; the boost website has good tutorials for the most part, broken down by sub-library. As for compiling, a good 80% of the library implementation is defined in the header files, making compiling trivial. for example, if you wanted to use shared_ptr's, you'd just add #include <boost/shared_ptr.hpp> and compile...
846,576
846,582
Is there a C++ function to turn off the computer?
Is there a C++ function to turn off the computer? And since I doubt there is one (in the standard library, at least), what's the windows function that I can call from C++? Basically, what is the code to turn off a windows xp computer in c++?
On windows you can use the ExitWindows function described here: http://msdn.microsoft.com/en-us/library/aa376868(VS.85).aspx and here's a link to example code that does this: http://msdn.microsoft.com/en-us/library/aa376871(VS.85).aspx
846,812
847,177
What is R-Value reference that is about to come in next c++ standard?
What is R-Value reference that is about to come in next c++ standard?
Here is a really long article from Stephan T. Lavavej
846,899
846,946
Windows 7 and the case of the missing regtlib
I've just discovered that regtlib.exe appears to be missing from Windows 7 (and apparently from Vista as well). I've just installed Windows 7 RC in a VM and I'm attempting to build our existing projects on the new OS. The projects are c/c++ based and I'm using visual studio 2008. In order to build these projects I need...
Yeah regtlib was removed from vista and up. As far as I know, all it does is call LoadTypeLibEx with the REGKIND_REGISTER flag (http://msdn.microsoft.com/en-us/library/ms221249.aspx). Maybe you could write a simple replacement.
847,092
847,107
Partial builds versus full builds in Visual C++
For most of my development work with Visual C++, I am using partial builds, e.g. press F7 and only changed C++ files and their dependencies get rebuilt, followed by an incremental link. Before passing a version onto testing, I take the precaution of doing a full rebuild, which takes about 45 minutes on my current proj...
Hasn't everyone come across this usage pattern? I get weird build errors, and before even investigating I do a full rebuild, and the problem goes away. This by itself seems to me to be good enough reason to do a full rebuild before a release. Whether you would be willing to turn an incremental build that completes with...
847,157
847,182
Qt: having problems responding on QWebView::linkClicked(QUrl) - slot signal issue
I am pretty new with Qt. I want to respond to linkClicked in QWebView. I tried connect like this: QObject::connect(ui->webView, SIGNAL(linkClicked(QUrl)), MainWindow,SLOT(linkClicked(QUrl))); But I was getting error: C:/Documents and Settings/irfan/My Documents/browser1/mainwindow.cpp:9: error: expec...
I changed QObject::connect to only connect and it works. So this code works: connect(ui->webView,SIGNAL(linkClicked(const QUrl)),this,SLOT(linkClicked(const QUrl)),Qt::DirectConnection); But I don't know why?
847,279
847,316
Code reuse in exception handling
I'm developing a C api for some functionality written in C++ and I want to make sure that no exceptions are propagated out of any of the exported C functions. The simple way to do it is making sure each exported function is contained in a: try { // Do the actual code } catch (...) { return ERROR_UNHANDLED_EXCEPTI...
You can use only one handler function for all possible exceptions, and call it from each or your API implementation functions, as below: int HandleException() { try { throw; } // TODO: add more types of exceptions catch( std::bad_alloc & ) { return ERROR_BAD_ALLOC; } c...
847,313
847,452
How to read 3rd party application's variables from memory?
I'm trying to read variables from memory. Variables, that doesn't belong to my own program. For instance, let's say I have this Adobe Shockwave (.dcr) application running in browser and I want to read different variables from it. How it's being done? Do I need to hook the process? But it's running under virtual machine...
If you're trying to do it manually just for one or two experiments, it's easy. Try a tool like Cheat engine which is like a free and quick and simple process peeker. Basically it scans the process's memory space for given key values. You can then filter those initial search hits later as well. You can also change those...
847,396
847,525
Compile a DLL in C/C++, then call it from another program
I want to make a simple, simple DLL which exports one or two functions, then try to call it from another program... Everywhere I've looked so far, is for complicated matters, different ways of linking things together, weird problems that I haven't even begun to realize exist yet... I just want to get started, by doing ...
Regarding building a DLL using MinGW, here are some very brief instructions. First, you need to mark your functions for export, so they can be used by callers of the DLL. To do this, modify them so they look like (for example) __declspec( dllexport ) int add2(int num){ return num + 2; } then, assuming your function...
847,535
1,141,745
Avoiding unneccessry recompilations using "branchy" development model
I'm using Mercurial for development of quite a large C++ project which takes about 30 minutes to get built from the scratch(while incremental builds are very quick). I'm usually trying to implement each new feature in the new branch(using "hg clone") and I may have several new features developed during the day and it'...
My Localbranch extension was designed partly around this use case. It uses a single working directory, but I think it's simpler than git. It's essentially a mechanism for maintaining multiple repository clones under one working directory, where only one is active at a given time.
847,721
847,766
How to identify if a library is DEBUG or RELEASE build?
Our project is using many static libraries to build the application. How can we make sure we are using release version of libraries in release build of application? We are making mistakes by taking debug library in release application build. I am looking for an elegant way in which I can write a module in that we can...
The normal approach is eithr to give the libraries different names or store them in different directories, such as Debug and Release. And if your build is correctly automated, I can't see how you can make mistakes.
847,876
847,908
Is there any performance difference between for() and while()?
Or is it all about semantics?
Short answer: no, they are exactly the same. Guess it could in theory depend on the compiler; a really broken one might do something slightly different but I'd be surprised. Just for fun here are two variants that compile down to exactly the same assembly code for me using x86 gcc version 4.3.3 as shipped with Ubuntu. ...
847,967
848,001
How do you determine the last valid element in a STL-Container
If i iterate over a STL container i sometimes need to know if the current item is the last one in the sequence. Is there a better way, then doing something like this? Can i somehow convert rbegin()? std::vector<int> myList; // .... std::vector<int>::iterator lastit = myList.end(); lastit--; for(std::vector<int>::it...
Try the following std::vector<int>::iterator it2 = (++it); if ( it2 == myList.end() ) { ... } The following should work as well if ( it+1 == myList.end() ) { // it is last ... }
847,974
848,000
The benefits / disadvantages of unity builds?
Since starting at a new company I've noticed that they use unity cpp files for the majority of our solution, and I was wondering if anyone is able to give me a definitive reason as to why and how these speed up the build process? I would've thought that editing one cpp file in the unity files will force recompilation o...
Very similar question and good answers here: #include all .cpp files into a single compilation unit? The summary seems to be that less I/O overhead is the major benefit. See also The Magic Of Unity Builds as linked in the above question as well.