简体   繁体   中英

Constructor and destructor calls when pushing on to a C++ vector

For the following code

struct MyInt {

  MyInt() { 
    std::cout << "I am the constructor for " << val << "\n";
  }
  ~MyInt() {
    std::cout << "I am the destructor for " << val << "\n";
  }

  int val;

};

int main() {

    using namespace std;

    cout << "Constructing l:" << endl;

    vector<MyInt /*, Mallocator<MyInt>*/ > l;

    MyInt int1;
    MyInt int2;
    int1.val = 1729;
    int2.val = 2161;

    cout << "Push back the item\n";

    l.push_back(int1);
    l.push_back(int2);

  return 0;
}

Why I get the following outputs?

Constructing l:
I am the constructor for 1558899544 (garbage)
I am the constructor for 47517696 (garbage)
Push back the item
I am the destructor for 1729
I am the destructor for 2161
I am the destructor for 1729
I am the destructor for 1729
I am the destructor for 2161

I was assuming to have four constructors (two for int1 and int2, two for push_back) and four destructors. Having five destructors surprises me.

You see only two " I am the constructor for... " because you forgot to add the copy constructor:

MyInt(const MyInt& rhs) 
{ 
    std::cout << "I am the constructor copy\n";
    val = rhs.val;
}

You see 5 destructors because of reallocation, as Barry mentioned in his answer. You can reserve the size on your vector and you will see only the 4 destructors you expected:

l.reserve(2); // 2 will suffice for the example at hand

Adding that to your code may output (as pointed out by PaulMcKenzie , compilers are free to remove copy construction, so the final output can depend on compiler, compiler settings, optimizations):

Constructing l:
I am the constructor default
I am the constructor default
Push back the item
I am the constructor copy
I am the constructor copy
I am the destructor
I am the destructor
I am the destructor
I am the destructor 

Five destructors:

  • Two each for int1 and int2 in main()
  • One for the object inside of l , when it had to get reallocated to accommodate more members.
  • Two for the MyInt s held by l .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM