Allan Jiang
Allan Jiang

Reputation: 11351

Object create in C++


I have a little question about a code example in C++.

vector<Cat> v;
Cat c;
v.push_back(c);
Cat d = v[0];

In this piece of code, how many objects are created?

Upvotes: 0

Views: 151

Answers (2)

Michael Anderson
Michael Anderson

Reputation: 73600

Add some logging to the constructor of Cat and test it yourself:

class Cat
{
  Cat() 
  {
    std::cout<<"Constructing a Cat"<<std::endl;
  }
  Cat( const Cat & cat )
  {
    std::cout<<"Copy Constructing a Cat"<<std::endl;
  }
};

Here's what I get: http://codepad.org/Pzs9kOlH

Note that under certain conditions the compiler is free to remove chunks of code that do nothing. So some copies may get removed. With a hypothetical very agressive compiler it might notice that nothing is done by your code and completely strip out any such constructions altogether. Since my constructors now change the output the compiler is less free to remove calls to them.

Upvotes: 1

bitmask
bitmask

Reputation: 34714

At least three:

vector<Cat> v;
Cat c;  // default construction
v.push_back(c); // copy construction of v[0] from c
Cat d = v[0];  // copy construction of d from v[0]

Edit: Note that I only count Cat objects here, because it doesn't make sense to ask how many objects in total are created, because that would be implementation specific (how is std::vector implemented? What does Cat do? ...)

Upvotes: 1

Related Questions