STL vector construction

I was benchmarking various formats for storing maps of object lists and I noticed something unusual about std::vector.

When you push an object onto the back of the vector, it calls the default constructor for the object to create an empty instance, and then the copy constructor to copy it into the vector.

struct Foo { 
  Foo() { cout << "ctor " << this << endl ; } 
  Foo(const Foo& rhs) { cout << "copytor " << this << " from " << &rhs << endl ; } 
  ~Foo() { cout << "dtor " << this << endl ; } 
} ; 
typedef vector<Foo> FOO ;
int main(int argc, char* argv[]) { 
 FOO bar ; 
 bar.push_back(Foo()) ; 
 cout << "end of program" << endl ; 
}

Produces something like this:

ctor 0xbf8ea997 (empty object) 
copyctor 0x8892008 from 0xbf8ea997(copy into array) 
dtor 0xbf8ea997 (destruction of empty object) 
end of program   

dtor 0x8892008 (destruction of the list by exit)

If you call resize it uses the same trick, creates a default object, copies it into all the slots of the array and the destructs the constructed default object. I’ve spent about an hour trying to find an explanation; maybe its just a side-effect of the classes/templates vector derives from. I get why push_back does this, but I don’t get why resize() doesn’t use an in-place construction. (It’s probably doing Foo& tempFoo and then pushing tempFoo into the empty slots, but I don’t understand why)

I wonder if because its unavoidable for push_back it just got overlooked for resize()?

Admittedly the overhead is small, negligible for something trivial like my class Foo.

The reason that push_back(Foo()) invokes an additional constructor/destructor is because it has to do this:

Foo& tempFoo ;
bar.push_back(tempFoo) ;
tempFoo.~Foo() ;

4 Comments

You’ve got mail.

;)

Bleah. Edited the post to clarify I am puzzled by resize — not push_back(Foo()).

FWIW: push_back(Foo()) expands to:

Foo& temporary ;
push_back(temporary) ;
temporary.~Foo() ;

I don’t understand your push_back code. How can you make an empty reference and then destruct it?

Its not an empty reference, its an “empty” instance of the object (default constructed) for the reference.

Leave a Reply

Name and email address are required. Your email address will not be published.

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

You may use these HTML tags and attributes:

<a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <pre> <q cite=""> <s> <strike> <strong> 

%d bloggers like this: