r值在不使用std :: move的情况下引起警告 [英] r-value causes a warning without the use of std::move

查看:104
本文介绍了r值在不使用std :: move的情况下引起警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮助我了解以下代码为何引起警告

Can someone help me to understand why the following code causes a warning

struct A
{
  A() : _a( 0 ) {}

  const int& _a;
};


int main()
{
  A a;
}

有警告

warning: binding reference member '_a' to a temporary value [-Wdangling-field]
      A() : _a( 0 ) {}

,但是此代码(其中std::move用于初始化成员_a的代码)没有:

but this code, where std::move is used to initialize the member _a, does not:

struct A
{
  A() : _a( std::move(0) ) {}

  const int& _a;
};


int main()
{
  A a;
}

0std::move( 0 )都不都是r值吗?

推荐答案

这是一个表达式:

0

这是一个非常小的表达,是的.但这是一种表达方式.

It's a very small expression, true. But it is an expression.

一旦对表达式求值,它就会消失.它消失了.加入看不见的合唱团.去见它的制造商.成为表达式.

Once the expression is evaluated, it goes away. It disappears. Joins the choir invisible. Goes to meet its maker. It becomes an ex-expression.

的确,将const引用绑定到临时项将扩展临时值的范围,直到封闭范围的末尾.

It is true that binding a const reference to a temporary extends the scope of the temporary value until the end of the enclosing scope.

但是在这种情况下,表达式的范围是构造函数.完成构造函数后,临时值将被破坏.

But in this case, the scope of the expression is the constructor. When the constructor is done, the temporary value gets destroyed.

您的编译器注意到以下事实:对表达式的const引用仍然作为类成员继续存在.您的编译器建议您使用类成员现在将导致未定义的行为.您的编译器希望成为您的朋友.您的编译器不希望您编写错误的代码,因此您会从编译器获得一些免费,友好的建议.

Your compiler noticed the fact that a const reference to the expression still continues to exist, though, as a class member. Your compiler is advising you that using the class member will now result in undefined behavior. Your compiler wants to be your friend. Your compiler doesn't want you to write buggy code, so you're getting some free, friendly advice, from your compiler.

在另一种情况下,您添加了一些其他代码,这些代码稍微复杂一些.它仍然是未定义的行为,但是代码现在已经足够复杂,以至于编译器无法看到未定义的行为的结果.但这仍然是相同的错误.

In the other case, you have added some additional code which is slightly more complicated. It is still undefined behavior, but the code is now complex enough that the compiler cannot see that undefined behavior results. But it's still the same bug.

当编译器发现潜在问题时,它将尝试警告您.不幸的是,编译器每次都找不到所有可能的潜在问题.但是,很明显,编译器会告诉您.

A compiler will try to warn you of potential problems, when the compiler sees them. Unfortunately, the compiler cannot find all possible potential problems, every time. But, when it's obvious, the compiler will let you know.

这篇关于r值在不使用std :: move的情况下引起警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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