如何使用非平凡析构函数防止未使用的变量警告

How to prevent unused variable warning with non trivial destructor

本文关键字:未使用 变量 警告 析构函数 何使用      更新时间:2023-10-16

当我依靠生命周期延长来分配给具有非平凡析构函数的类时,编译器(gcc 和 clang (会发出未使用的变量警告。 有没有办法解决这个问题?https://wandbox.org/permlink/qURr4oliu90xJpqr

#include <iostream>
using std::cout;
using std::endl;
class Something {
public:
    explicit Something(int a_in) : a{a_in} {}
    Something() = delete;
    Something(Something&&) = delete;
    Something(const Something&) = delete;
    Something& operator=(Something&&) = delete;
    Something& operator=(const Something&) = delete;
    ~Something() {
        cout << this->a << endl;
    }
private:
    int a;
};
int main() {
    const auto& something = Something{1};
    return 0;
}

请注意,当我切换到不依赖寿命延长时,一切正常 https://wandbox.org/permlink/cJFwUDdi1YUEWllq

我什至尝试手动定义所有构造函数,然后使用模板化static_assert删除它们,以便仅在调用这些构造函数时触发 https://wandbox.org/permlink/fjHJRKG9YW6VGOFb

#include <iostream>
using std::cout;
using std::endl;
template <typename Type>
constexpr auto definitely_false = false;
template <typename T = void>
class Something {
public:
    explicit Something(int a_in) : a{a_in} {}
    Something() { static_assert(definitely_false<T>, ""); }
    Something(Something&&) { static_assert(definitely_false<T>, ""); }
    Something(const Something&) { static_assert(definitely_false<T>, ""); }
    Something& operator=(Something&&) { static_assert(definitely_false<T>, ""); }
    Something& operator=(const Something&) { static_assert(definitely_false<T>, ""); }
    ~Something() {
        cout << this->a << endl;
    }
private:
    int a;
};
int main() {
    const auto& something = Something<>{1};
    return 0;
}

让我们说,只是为了语言律师标签的缘故,投掷无效不是一种选择。 我可以对构造函数/析构函数做一些有助于消除此警告的操作吗?

不是您要查找的确切答案,但这里有一个解决方法建议:

C++17 之前

使用如下std::ignore

const auto& something = Something{1};
std::ignore = something;

C++17 后

使用maybe_unused属性,如下所示:

[[maybe_unused]] const auto& something = Something{1};

> C++17 引入了 maybe_unused 属性,这对您的情况可能会有所帮助。它可以应用于变量以指示它可能未使用:

[[maybe_unused]] const auto & something = Something<>{1};

我只会使用匿名的 Something 对象,而您的警告就消失了......

int main() 
{
    Something{1};
    return 0;
}

https://wandbox.org/permlink/YcuLPFzgOSzltVSq

编译器会警告您 Something 的对象引用变量未使用。这是真的,无论你对构造函数和析构函数做什么。因此,如果不使用引用变量,请不要创建它。这有效地防止了警告。