Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing references to a C++ constructor and saving them to reference or non-reference types

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?

like image 972
user1468729 Avatar asked Jun 20 '12 10:06

user1468729


1 Answers

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.

like image 100
hmjd Avatar answered Sep 18 '22 00:09

hmjd