#include <vector>
#include <iostream>
using namespace std;
struct foo
{
//constructor 1
foo() { std::cout << "foo()" << endl; }
~foo() { std::cout << "~foo()" << endl; }
//constructor 2
foo(const foo&) { std::cout << "foo(const foo&)" << endl; }
//constructor 3
foo(foo&) { std::cout << "foo(foo&)" << endl; }
//constructor 4
foo(foo&&) { std::cout << "foo(foo&&)" << endl; }
};
int main()
{
std::vector<foo> v;
foo f0; // constructor 1 is be called
v.push_back(f0); // constructor 2 is be called
foo f1 = f0; // constructor 3 is be called
cout << "-Action-4-" << endl;
v.push_back(foo{}); // constructor 1,4,2 is called and 2 Desctrunctors
cout << "Destructors will be called" << endl;
return 0;
}
The above code snippet calls contructor thrice for Action 4. Can somebody explain why?
1) for foo f0;
constructor 1 (Default Constructor) is called
2) for v.push_back(f0);
constructor 2 is be called because push_back
overloaded for const foo&
3) foo f1 = f0;
constructor 3 is called because of assignment operator prefer Lvalue reference foo&
4) v.push_back(foo{});
constructor 1,4,2 is called and 2 Destructors
Please explain this behaviour.
Modifying code as std::vector v; v.reserve(10); has done the trick, Now action 4 calls constructor 1,4 is and 1 Destructors