dimanche 5 juin 2022

C++ left and right reference for return value

The following code is running in MSVC and I write my question inline the code below.

#include <iostream>

struct Object
{
    Object() = default;

    Object(const Object &o)
    {
        std::cout << "left value constructor" << std::endl;
    }

    Object(Object &&o)
    {
        std::cout << "right value constructor" << std::endl;
    }
};

void jn(Object &o)
{
    std::cout << "left reference jn" << std::endl;
}

void jn(Object &&o)
{
    std::cout << "right reference jn" << std::endl;
}

Object go;

Object gn()
{
    Object &&rgo = std::move(go);
    jn(rgo); // left reference jn is called, so rgo should be left reference
    return rgo; // right reference constructor is called, so rgo should be right reference
    // Question: rgo is left reference or right reference? Why left reference version jn is called while Object move constructor is called in return statement?
}

int main()
{
    gn();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire