1

Here is my code:

class Base
{
public:
    Base() {
        cout << "constructor" << endl;
    }
    ~Base() {
        cout << "destructor" << endl;
    }
};

int main(int argc, char **argv)
{
    vector<Base> vec;
    // vec.push_back(Base());
    // vec.push_back(Base());
    vec.emplace_back();
    vec.emplace_back();

    return 0;
}

The output is as below:

constructor
constructor
destructor
destructor
destructor

To add an element into a vector, we can use push_back or emplace_back. I know their difference. But no matter which one I use, the destructor will be always called more times than the constructor.

May I know why and how to avoid this?

Yves
  • 11,597
  • 17
  • 83
  • 180
  • 1
    Add some explicit copy and move constructors, maybe that will provide illumination (or delete them and see what happens). – Konrad Rudolph Dec 12 '19 at 11:58
  • My assumption would be a move happening; if you add a `reserve(5)`, then it just does twice. – ChrisMM Dec 12 '19 at 11:58
  • 2
    TL;DR - you are not logging *all* of your constructor calls. You also need copy constructor (or move constructor). And then there will be precisely 1 destructor call for each constructor call. – Yksisarvinen Dec 12 '19 at 11:58
  • Reserve space for the items so that `vec` doesn't need to grow – acraig5075 Dec 12 '19 at 12:03

0 Answers0