Why GCC 5.3.0 gives warning when binding reference to “this” pointer

前端 未结 2 1324
悲&欢浪女
悲&欢浪女 2021-02-19 10:37

Here is the minimal example:

class A
{
    A* const& this_ref;
public:
    A() : this_ref(this) {}
};

GCC 5.3.0 gives warning:

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-19 11:21

    You are creating a dangling reference. Your code is no different from this code:

    struct X
    {
        const int & r;
        X() : r(5) {}
    };     // ^^^^ dangles
    

    There is no "object" called this. this is a keyword, and when used as an expression, it is a prvalue (a temporary) containing the address of the current instance.

    Here's another example of the creation of a similarly dangling reference from something that looks like an object but isn't:

    struct Y
    {
        int a[10];
        int* const & r;
    
        Y() : r(a) {}
    };
    

    Here, a is a named entity (an lvalue), but in the initializer of r, the expression a is a prvalue (namely the result of the decay of the array).

    The overall message is that you should be careful with the language feature that allows const lvalue references to bind to rvalues. Its main purpose is to make function calls easy, but its other uses are much hairier.

提交回复
热议问题