如何使用非平凡析构函数防止未使用的变量警告
How to prevent unused variable warning with non trivial destructor
当我依靠生命周期延长来分配给具有非平凡析构函数的类时,编译器(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 的对象引用变量未使用。这是真的,无论你对构造函数和析构函数做什么。因此,如果不使用引用变量,请不要创建它。这有效地防止了警告。
相关文章:
- 使用typeid警告未使用的变量
- 未使用的C++未优化的静态成员函数/变量
- C++未使用的变量警告,即使我在函数结束时返回它
- 如何使 Visual Studio 2010 警告未使用的变量
- C 20合同和未使用的变量
- 提升::序列化警告未使用的变量file_version
- 未使用的变量禁止打印?
- GCC和Clang不警告未使用的异常变量
- 避免在 openmp 并行块中使用预编译器语句出现未使用的变量警告
- 抑制警告:未使用的变量
- 错误:非静态数据成员的使用无效,在此范围内未声明变量
- 如何使用非平凡析构函数防止未使用的变量警告
- 为什么这个未使用的变量没有优化掉?
- 为什么msvc编译器在显式调用析构函数时会发出未使用的变量
- 警告:变量已设置,但未使用
- 检测函数范围之外的未使用变量
- 如何禁止显示有关C++中未使用变量的警告
- C++未使用变量的异常
- 为什么在c++函数中使用void(未使用)(和类似的)而不是没有名称的参数来消除未使用变量的警告
- 如何在Eclipse中禁用未使用变量警告?