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

跟風遠走 提交于 2019-12-03 23:46:40

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.

Is this a temporary then?

To be precise, this is not temporary, but a temporary is created here.

Firstly, this is prvalue,

The following expressions are prvalue expressions:

Secondly, temporary object will be created when binding reference to a prvalue,

Temporary objects are created when a prvalue is materialized so that it can be used as a glvalue, which occurs (since C++17) in the following situations:

That's why GCC gives warning, because this_ref is bound to a temporary created. (And then become dangled later, which leads to UB.)

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