I have following code
class base
{
private:
int k;
public:
base(const base& b){ this->k = b.k; cout<<" c-ctor "<<endl; }
base(int a = 10){ k = a; cout<<" a = "<<a<<endl; }
friend const ostream& operator<<(ostream& out, base& b)
{
return out<<b.k<<endl;
}
};
int main()
{
base b, b1(2);
vector<base> vec = {b, b1};
cout<<" check point "<<endl;
for(auto& elem : vec)
cout<<" "<<elem;
cout<<endl;
return 0;
}
Output :
1- a = 10
2- a = 2
3- c-ctor
4- c-ctor
5- c-ctor
6- c-ctor
7- check point
8- 10
9- 2
Could anybody please explain why 4 calls for copy constructor, i understand 2 calls while copying object in container. How 4?
The reason being that the initialization vector<base> vec = {b, b1};
creates a std::initializer_list<base>
and passes it to the appropriate vector constructor. Which then proceeds to copy it further.
You can limit the number of copies by directly initializing the members of the std::initializer_list<base>
, instead of creating named objects. Something like this:
vector<base> vec = {{}, {2}};
Or eliminate the superfluous copying completely by reserve
ing memory in the vector first, and then emplace
ing the objects into it.
vector<base> vec;
vec.reserve(2);
vec.emplace_back();
vec.emplace_back(2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With