C++ catching dangling reference

前端 未结 7 841
温柔的废话
温柔的废话 2020-12-14 22:02

Suppose the following piece of code

struct S {
    S(int & value): value_(value) {}
    int & value_;
};

S function() {
    int value = 0;
    retur         


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 22:22

    This is perfectly valid code.

    If you call your function and bind the temporary to a const reference the scope gets prolonged.

    const S& s1 = function(); // valid
    
    S& s2 = function(); // invalid
    

    This is explicitly allowed in the C++ standard.

    See 12.2.4:

    There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression.

    and 12.2.5:

    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 of a subobject to which the reference is bound persists for the lifetime of the reference except: [...]

提交回复
热议问题