jeudi 10 août 2017

Why does compiler use move constructor instead of the copy constructor

Is it ok that the following code

#include <iostream>

struct Foo
{
    Foo() { std::cout << "Foo::Foo" << std::endl; }
    ~Foo() { std::cout << "Foo::~Foo" << std::endl; }

    Foo(const Foo&) { std::cout << "Foo::Foo(const Foo&)" << std::endl; }
    Foo& operator=(const Foo&) { std::cout << "Foo::operator=(const Foo&)" << std::endl; return *this; }

    Foo(Foo&&) { std::cout << "Foo::Foo(Foo&&)" << std::endl; }
    Foo& operator=(Foo&&) { std::cout << "Foo::operator=(Foo&&)" << std::endl; return *this; }
};

Foo foo()
{
    Foo second;
    return second;
}

int main()
{
    foo();
}

produces such output:

Foo::Foo
Foo::Foo(Foo&&)
Foo::~Foo
Foo::~Foo

Why does it call move constructor instead of the copy constructor?

Aucun commentaire:

Enregistrer un commentaire