4

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
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
user7024
  • 311
  • 2
  • 10

1 Answers1

6

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.

j6t
  • 9,150
  • 1
  • 15
  • 35