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

标签 c++ c++11 language-lawyer destructor raii

当我依靠生命周期扩展来分配给具有非平凡析构函数的类时,编译器(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;
}

为了语言律师标签,我们假设强制转换为 void 不是一个选项。我可以对构造函数/析构函数做些什么来帮助消除此警告吗?

最佳答案

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

C++17 前

使用 std::ignore像这样:

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

后 C++17

使用 maybe_unused attibute ,像这样:

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

关于c++ - 如何使用非平凡的析构函数防止未使用的变量警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47257978/

相关文章:

c++ - C++的子集和递归

c++ - VC++编译器升级2010->2015重新定义; 'constexpr' 说明符不匹配

c++ - 使用 using 指令进行不明确的名称查找

c++ - 为什么禁止一次打开多个命名空间?

c++ - 字节顺序标记真的是一个有效的标识符吗?

c++ - 未实现的拷贝构造函数的拷贝赋值

c++ - C++模板中的运算符重载

python - 在 Python 2.7 中编织内联 C++ 代码

c++ - 如何使用自定义结构初始化 boost::array?

c++ - std::string,string val 和 string val 之间的区别 = ""