有没有一种方法可以让编译器(clang++ 或 g++)告知接下来的情况:
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
当再次使用变量时,应触发另一类警告:
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
之类的不可复制类的变量其内容被盗后很少被重复使用。
如果上述警告可以通过 #pragma
触发每个变量,那就太好了或属性或全局变量,其类型是具有自定义 move 赋值运算符和构造函数的类。
有时很难跟踪变量的生命周期。
现代编译器使用中间表示形式(如 AST)的 SSA 形式(静态单赋值形式)。所以我认为编译器检测上述情况并不难。
最佳答案
不,目前无法使用 GCC 或 Clang 来执行此操作。
C++17 中的新 [[nodiscard]]
属性隐约相关,但并不相同,并且不能用于您的任何情况。
关于c++ - 当右值声明的变量超出范围且未被 move 时发出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36152183/