Search code examples
c++object-lifetime

Reference parameter lifetime


Given the following:

class ParamClass {...};

class MyObject {
public:
    void myMethod(ParamClass const& param) { _myPrivate = param; }

private:
    ParamClass _myPrivate;
}

[...]

MyObject obj;

void some_function(void)
{
    ParamClass p(...);
    obj.myMethod(p);
}

What will happen to _myPrivate at the end of the lifetime of object p? EDIT: will I still be able to use _myPrivate to access a copy of object p?

Thanks!

Dan


Solution

  • Since _myPrivate is not a reference, in the assignment _myPrivate = param, its value will be copied over from whatever the reference param points to, which in this case is the local variable p in some_function().

    So if the assignment operator for ParamClass is implemented correctly, the code should be fine.

    will I still be able to use _myPrivate to access a copy of object p?

    With the above caveat, yes. But to be precise, _myPrivate can not be used to access a copy of p; it is a variable containing a copy of the data in (the now extinct) p.