vector and constructor in C++

Below code is surprising me because constructor has not been called as expected while storing my class object into vector. Pls throw some light.

class Sample
{
public:
sample () { cout<<"\ninside Sample()"; }
~sample() { cout<<"\ninside ~Sample()"; }

};

int main()
{ vector<Sample> s(2); return 0; }

**Output:**
inside Sample()
inside ~Sample()
inside ~Sample()
inside ~Sample()


As you can see here, constructor has been called only once but destructor has been called 3 times. Please explain it .
C++98 specific:
The default constructor has been called once, the copy constructor has been called (trivially) twice, and destructor has been called 3 times.

Add a copy constructor which prints out something, and you would see what is going on.
Last edited on
Thank you JLBorges.

Yes you are correct. I just verified and found copy constructor called twice after default constroctor.
But didn't understand why copy constructor is getting called here?Can you please explain or redirect me to correct place on web ?

Regards,
Rakesh
With C++98, the constructor that you are using is:
explicit vector( size_type count, const T& value = T(), const Allocator& alloc = Allocator());
http://en.cppreference.com/w/cpp/container/vector/vector

This constructor creates a vector of size 'count' by copying 'value' count 'times'.
Since you used a default value for the second argument:
a. Initialize 'value' using the default constructor.
b. Copy the value into the vector 'count' times using the copy constructor.
c. Destroy the default constructed object.

With C++11, the constructor is explicit vector( size_type count );. This constructor eliminates the gratituous default construct - copy - copy ... - destroy sequence; it directly default constructs the objects in situ.

If you have a choice, prefer C++11 over the obsoleted C++98.
Last edited on
Topic archived. No new replies allowed.