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

有帮助吗?

解决方案

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.

其他提示

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

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

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!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top