Does a const reference class member prolong the life of a temporary?

前端 未结 5 1091
独厮守ぢ
独厮守ぢ 2020-11-21 08:04

Why does this:

#include 
#include 
using namespace std;

class Sandbox
{
public:
    Sandbox(const string& n) : member(n) {         


        
5条回答
  •  悲哀的现实
    2020-11-21 08:56

    Only local const references prolong the lifespan.

    The standard specifies such behavior in §8.5.3/5, [dcl.init.ref], the section on initializers of reference declarations. The reference in your example is bound to the constructor's argument n, and becomes invalid when the object n is bound to goes out of scope.

    The lifetime extension is not transitive through a function argument. §12.2/5 [class.temporary]:

    The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below. A temporary bound to a reference member in a constructor’s ctor-initializer (§12.6.2 [class.base.init]) persists until the constructor exits. A temporary bound to a reference parameter in a function call (§5.2.2 [expr.call]) persists until the completion of the full expression containing the call.

提交回复
热议问题