This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

std::vector does not independently call default constructors


When I run the following code it looks like a std::vector<thing>(5) calls the default constructor for 'thing' once, then calls thing's copy constructor 4 more times. This may not result in 5 default constructed 'things'.

g++ --version
g++ (GCC) 4.0.0
Copyright (C) 2005 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


#include <vector> #include <iostream>

using namespace std;

typedef vector<double> dVector;
typedef unsigned int uint;

class vh{    // 'vector holder'
// compiler generated copy constructor copies pointer, which we want
// to have happen for efficiency reasons.
public:
 vh() : V(new dVector){}
 void push_back(double x){V->push_back(x);}
 uint size()const{return V->size();}
private:
 dVector * V;
};

int main(){
 vh x, y;
 x.push_back(1.0);
 y.push_back(2.0);
 cout << x.size() << endl;   // prints '1' the right answer

 vector<vh> v(2);    // should have two independent copies of vh's
 v[0].push_back(1.0);
 v[1].push_back(2.0);
 cout << v[0].size() << endl;   // prints '2' the wrong answer.
}


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]