Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 当rvalue声明的变量超出了不从中移动的范围时发出警告_C++_C++11_Warnings_Move Semantics - Fatal编程技术网

C++ 当rvalue声明的变量超出了不从中移动的范围时发出警告

C++ 当rvalue声明的变量超出了不从中移动的范围时发出警告,c++,c++11,warnings,move-semantics,C++,C++11,Warnings,Move Semantics,有没有一种方法可以让编译器(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 诸如

有没有一种方法可以让编译器(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
诸如
std::unique_ptr
等不可复制类的变量在其内容被窃取后很少被重用

如果通过
#pragma
或属性触发的变量或全局变量(类型为具有自定义移动赋值运算符和构造函数的类)可以提供上述警告,那就太好了

有时很难跟踪变量的生存期


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

不,现在使用GCC或Clang无法做到这一点


C++17新增的
[[nodiscard]]
属性关系模糊,但不相同,不能用于任何情况。

“当从再次使用的变量移动时”,当然如果移动内容,应该假设变量处于未定义状态-即使它只是一个整数,也不应该再次使用它。如果你需要使用它,为什么要先移动它?@JohnBargman,不,移动不是这样做的。对于整数,它将保持不变;对于唯一的,它有一个完全定义的状态(它是空的);对于大多数其他类型,它是“有效但未指定的”。@Orient,“T是prvalue”是什么意思?T是一个类型,不是一个表达式,所以这没有意义。您希望触发警告的条件是什么?@JonathanWakely对于未指定状态为。。。糟糕的代码味道,对于简单类型,我不确定有效性是实现定义的还是标准的一部分,您知道吗?无论如何,这肯定是一种不好的做法吗?您可以将其实现为静态工具(使用libclang可能会有所帮助)
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
}