c++ - 当右值声明的变量超出范围且未被 move 时发出警告

标签 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

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/

相关文章:

c++ - 自定义 std::shared_ptr 或 boost::shared_ptr 以在 NULL 取消引用时抛出异常

javascript - 所有 Sequelize 验证都收到非错误警告?

php - 警告: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\m2\my booking.php on line 158

c++ - 在以下情况下纹理是如何被破坏的?

c++ - 我无法访问我的变量的值,即使我通过作用域传递了它

c++ - 整数数组的位封装

c - 非可移植指针转换

c++ - 通过检查其返回值作为 -32767 和 0x8000 来使用 GetAsyncKeyState() 有什么区别?

c++ - 通过属性值从 vector 中删除对象的 unique_ptr

c++ - 嵌套 c++11 范围循环以查找组合