문제

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;
}
도움이 되었습니까?

해결책

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.

다른 팁

In the both cases

AP const& a = get();

and

AP const& a = get2();

You bind a temporary object with a const reference. The object will be alive while there will be alive the reference. So there is no problem with your code.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top