Cur*_*ous 12 c++ destructor raii language-lawyer c++11
当我依赖生命周期扩展来分配具有非平凡析构函数的类时,编译器(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;
}
Run Code Online (Sandbox Code Playgroud)
请注意,当我切换到不依赖于生命周期扩展时,事情工作得很好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;
}
Run Code Online (Sandbox Code Playgroud)
让我们说只是语言律师标签的缘故,铸造无效不是一种选择.我可以用构造函数/析构函数做些什么来帮助沉默这个警告吗?
不是您正在寻找的确切答案,但这是一个解决方案建议:
前C++ 17
使用std::ignore这样:
const auto& something = Something{1};
std::ignore = something;
Run Code Online (Sandbox Code Playgroud)
发表C++ 17
使用maybe_unusedattibute,如下所示:
[[maybe_unused]] const auto& something = Something{1};
Run Code Online (Sandbox Code Playgroud)
yus*_*suf -2
I\xc2\xb4d 只是使用匿名 Something 对象,你的警告就消失了......
\n\nint main() \n{\n Something{1};\n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n\nhttps://wandbox.org/permlink/YcuLPFzgOSzltVSq
\n\n编译器警告您 Something 的对象引用变量未使用。无论您对构造函数和析构函数做什么,都是如此。因此,如果您不使用引用变量,就不要创建它。这有效地防止了警告。
\n| 归档时间: |
|
| 查看次数: |
561 次 |
| 最近记录: |