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?