mardi 2 avril 2019

Reference member to constructor argument pass by value

Here is an example code with a reference member to the constructor argument pass by value:

struct A
{
    A(std::string name): name_(name){}
    std::string name_;
};

struct B
{
    B(A a): a_(a)
    {
    }
    A& a_;
};

int main()
{
    std::unique_ptr<B> b;
    {
        A a("a");
        b.reset(new B(a));
    }
    b->a_.name_ = "b";

    return 0;
}

Does a_ still refer to a valid object in this line b->a_.name_ = "b" ? Is it the similar case as returning a reference to the function local object ?

Aucun commentaire:

Enregistrer un commentaire