Why do const references extend the lifetime of rvalues?

不羁的心 提交于 2019-11-28 23:22:25

It was proposed in 1993. Its purpose was to eliminate the inconsistent handling of temporaries when bound to references.

Back then, there was no such thing as RVO, so simply banning the binding of a temporary to a reference would have been a performance hit.

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1993/N0345.pdf

Leon

You are not questioning why const references are allowed to bind to temporaries, but merely why they extend the lifetime of those temporaries.

Consider this code:

struct A
{
    void foo() const;
};

A bar();

const A& a = bar();

a.foo();               // (1)

If the lifetime of the temporary returned by bar() were not extended, then any usage of a (exemplified by the line (1)) would lead to undefined behavior. This would make binding non-parameter const references to temporaries completely useless.


EDIT (addressing OP's comment):

Thus the real question should be why a const reference variable (that is not a function parameter) is allowed to bind to a temporary. I don't know the original justification for it (Richard Hodges' answer may be the only true one), but it provides us with one useful feature. Considering the following example:

struct B
{
    virtual void foo() const;
};

B bar();

const B& b = bar();

b.foo();               // (1)

The only difference of this example from the previous one is that B::foo() is virtual. Now, what if we decide to introduce a new class D as a subclass of B and change the return type of bar() from B to D?

struct B
{
    virtual void foo() const;
};

struct D : B
{
    virtual void foo() const;
};

//B bar();
D bar();

const B& b = bar();

b.foo(); // This will call D::foo()

// In the end the temporary bound by b will be correctly destroyed
// using the destructor of D.

Thus, binding const references to temporaries simplifies taking advantage of dynamic polymorphism for objects that are returned by value.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!