Passing references to a C++ constructor and saving them to reference or non-reference types
Solution 1
ExampleClass
is fine, as it takes a copy of the object referenced in its constructor argument.
ExampleClass2
requires that the object referenced in its constructor argument exist for the lifetime of the ExampleClass2
instance (as it stores a reference to the object, it does not copy it). If it does not, then the ExampleClass2
instance will have a dangling reference as soon as the object to which it refers is destructed. This is the case with the getExample2Object()
function as obj
is destructed when getExample2Object()
returns.
Solution 2
I'd like to know if these are basically the same thing.
No, they are not. Example
's constructor takes an object reference and constructs a member object to using the object passed. This object is not a reference but a copy. In case of Example2
, you are actually making objReference
refer to object passed in ctor's parameter. You are good only as long as newObj
's lifetime.
The
Object obj;
return new ExampleClass2(obj);
is the classic case when it will fail. Once the function returns, you will have a dangling reference.
user1468729
Updated on June 04, 2022Comments
-
user1468729 about 2 years
I'd like to know if these are basically the same thing.
class ExampleClass { public: ExampleClass(Object& newObj) : obj(newObj) {} private: Object obj; } class ExampleClass2 { public: ExampleClass2(Object& newObj) : objReference(newObj) {} private: Object& objReference; }
So would this not work with either of the classes?
ExampleClass* getExampleObject() { Object obj; return new ExampleClass(obj); } ExampleClass2* getExample2Object() { Object obj; return new ExampleClass2(obj); } void main() { ExampleClass* ec = getExampleObject(); ExampleClass2* ec2 = getExample2Object(); //Do something involving the member objects of ec and ec2 }
So are the member objects invalid after both getExampleObject methods? Doesn't the constructor of ExampleClass save a copy of the object referenced in its constructor?