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