Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is copy constructor called twice in this code? [duplicate]

Tags:

c++

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
like image 417
user7024 Avatar asked Oct 14 '25 14:10

user7024


1 Answers

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.

like image 103
j6t Avatar answered Oct 17 '25 04:10

j6t



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!