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

前端 未结 2 1313
悲&欢浪女
悲&欢浪女 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

    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:

    • the this pointer;

    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:

    • binding a reference to a prvalue

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

提交回复
热议问题