当右值声明的变量超出范围而不被从中移出时发出警告 [英] Warning when rvalue-declared variable goes out of scope being not moved from

查看:71
本文介绍了当右值声明的变量超出范围而不被从中移出时发出警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以使编译器( clang ++ g ++ )通知下一种情况:

Is there a way to make a compiler (clang++ or g++) to inform one about next situations:

static_assert(!std::is_lvalue_reference< T >::value);
void g(T);
void f(T x)
{
    T y = x;
#if 0 // turns warning off
    g(std::move(x));
#endif
} // warning here: x goes out of scope, but not moved from

static_assert(!std::is_reference< T >::value);
T f()
{
    T x;
    T y = x;
#if 0 // turns warning off
    return x;
#else
    return {};
#endif
} // warning here: x goes out of scope, but not moved from

再次从变量中移出时,应触发另一类警告:

Another class of warnings should be triggered, when moved from variable used once again:

void f()
{
    T x;
    T y = std::move(x);
    T z = x; // warning here: x is used since it has been moved from
}

诸如std::unique_ptr之类的不可复制类的变量在其内容被窃取后很少再使用.

Variables of such non-copyable classes as std::unique_ptr are rarely reused after their content has been stealed.

如果上述警告可以作为通过#pragma或属性触发的按变量触发,或者对于类型为具有自定义移动分配运算符和构造函数的类的所有变量全局提供,则将是很好的选择.

It would be great, if warnings described above would be available as per-variable triggered via #pragma or attribute or globally for all variables which types are classes with custom move-assignment operator and constructor.

有时候很难追踪变量的寿命.

Sometimes it is hard to follow the lifetime of variable.

现代编译器中使用中间表示形式(如AST)的SSA形式(静态单分配形式).因此,我认为编译器检测上述情况并不难.

There is SSA-form (static single assignment form) of intermediate representation (like AST) used in modern compilers. So I think it is not too hard for compilers to detect above situations.

推荐答案

不,今天无法使用GCC或Clang做到这一点.

No, there is no way to do this with GCC or Clang today.

C ++ 17的新[[nodiscard]]属性含糊不清,但并不相同,因此不能用于您的任何情况.

The new [[nodiscard]] attribute coming to C++17 is vaguely related, but not the same and can't be used for any of your cases.

这篇关于当右值声明的变量超出范围而不被从中移出时发出警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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