Reference parameter lifetime

倖福魔咒の 提交于 2019-12-24 03:01:38

问题


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


回答1:


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.




回答2:


in myMethod you invoke the assignment operator of ParamClass which by default makes a bitwise copy of the object (you can define your own operator). So you create a copy of p, which will be accessible




回答3:


A reference is like an alias to an object. The reference has no lifetime of its own. The lifetime to consider is the lifetime of the object referenced.

In your example, _myPrivate is an object so the operator= will copy the reference-passed objet p. p will be destroyed, and the parameter reference will reference nothing, but _myPrivate, as a copy will be OK.

It would be a problem if _myPrivate was declared as :

ParamObject& _myPrivate;

In this case, you end up with a "dangled" reference : Undefined behavior :)

my2c




回答4:


Take a look at:

_myPrivate = param;

In this statement assignment operator (ParamClass::operator=) copies values of each member of the object referred by param into members of _myPrivate. When some_function returns, p is moved from stack - it disappears. But _myPrivate now contains copies of p's members' values.

If ParamClass has members that are pointers to dynamically allocated memory, you must make sure that ParamClass::operator= performs deep copy, otherwise you might have problems with dangling pointers - ParamClass's destructor might free that memory but _myPrivate will have a member that still points to it!



来源:https://stackoverflow.com/questions/4864022/reference-parameter-lifetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!