When I execute the below code, a copy constructor of AAA
is called twice between boo
and foo
.
I just wonder when each of them is called exactly.
Code:
#include <iostream>
#include <vector>
class AAA
{
public:
AAA(void)
{
std::cout<<"AAA ctor"<<std::endl;
}
AAA(const AAA& aRhs)
{
std::cout<<"AAA copy ctor"<<std::endl;
}
AAA(AAA&& aRhs) = default;
};
void foo(std::vector<AAA>&& aVec)
{
std::cout<<"----foo"<<std::endl;
}
void boo(const AAA& a)
{
std::cout<<"----boo"<<std::endl;
foo({a});
std::cout<<"----boo"<<std::endl;
}
int main(void)
{
AAA a;
boo(a);
return 0;
}
Output:
AAA ctor
----boo
AAA copy ctor
AAA copy ctor
----foo
----boo
The copy constructor is invoked twice here:
foo({a});
First to construct the elements of the initializer list, and second to copy the values from the initializer list to the std::vector
.
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