Search code examples
c++functionstackshared-ptr

Obtaining object from function by reference instead by value


I wonder if code below is correct - it works in this case but it may be just because of its simplicity. What makes me wonder: function (f1) returns object by value but in function which called it (f2) I obtain this object by reference not by value. Is this a problem? I wonder because it looks a bit weird to me but it works and i think it should works. Because object is created on the stack of f1 and then returned (by value) to stack f2 and after that a reference is obtained to this object on f2 stack which was created on f1 stack. What do you think about this?

class A {
public:
    A(){a=100; b=200;}
    int a;
    int b;
};
typedef boost::shared_ptr<A> AP;

AP get(){
    AP a = AP(new A());
    return a;
}


AP get2(){
    AP const& a = get();
    return a;
}

int main() {
    AP const& a = get2();
    std::cerr << a->a << std::endl;
    return 0;
}

Solution

  • It's weird, but safe.

    Binding a temporary object to a reference extends its lifetime to that of the reference; so what you're doing is equivalent to creating a local object variable. The use of a reference adds obfuscation, requiring the reader to know these odd rules to understand what's happening, but doesn't change the program's validity or behaviour.