为什么GCC 5.3.0在绑定引用“this”时会给出警告。指针 [英] Why GCC 5.3.0 gives warning when binding reference to "this" pointer

查看:161
本文介绍了为什么GCC 5.3.0在绑定引用“this”时会给出警告。指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是最小的例子:

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

GCC 5.3.0发出警告:



< >

警告:临时绑定到'A :: this_ref'只会持续到
构造函数退出[-Wextra]
A():this_ref(this){} p>

这个什么是... MSVC 2015是沉默这个,并指向成员 this_ref->成员在我的情况下的构造函数中给出了预期的行为(但可能只是UB,不确定)。






编辑:



注意这个问题扩展一个链接作为可能的重复,因为它不是关于如何创建这样的引用的一般问题,但关于警告GCC(和MSVC以外的其他可能的编译器)在创建一个。

解决方案

您正在创建悬挂引用。您的代码与此代码没有什么不同:

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

没有名为 这个是一个关键字,当用作表达式时,它是一个包含当前实例地址的prvalue(临时) p>

这里是另一个例子,从一个类似的悬挂引用创建类似对象,但不是:

  struct Y 
{
int a [10];
int * const& r;

Y():r(a){}
};

这里, a 一个左值),但在 r 的初始化器中, a (即数组衰减的结果)。



总的消息是,你应该小心语言特性,允许const值引用绑定到右值。它的主要目的是使函数调用变得容易,但是其他用途却很多。


Here is the minimal example:

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

GCC 5.3.0 gives warning:

warning: a temporary bound to 'A::this_ref' only persists until the constructor exits [-Wextra] A() : this_ref(this) {}

Is this a temporary then? What the... MSVC 2015 is silent about this, and referring to class members by this_ref->member outside the constructor in my case gives expected behaviour (but might be just a case of UB, not sure).


EDIT:

Note this question extends one linked as possible duplicate, because it's not generic question about way to create such reference, but about warning GCC (and possible other compilers other than MSVC) produces when creating one.

解决方案

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.

这篇关于为什么GCC 5.3.0在绑定引用“this”时会给出警告。指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆