在 Visual Studio 中,我经常将对象仅用于 RAII 目的。例如:
ScopeGuard close_guard = MakeGuard( &close_file, file );
close_guard 的全部目的是确保文件将在函数退出时关闭,它不会在其他任何地方使用。但是,Visual Studio 给我一个警告,提示“局部变量已初始化但未引用”。我想针对这种特定情况关闭此警告。
你如何处理这种情况? Visual Studio 认为这个对象没有用,但这是错误的,因为它有一个非平凡的析构函数。
我不想为此使用 #pragma 警告 指令,因为即使出于正当理由它也会关闭此警告。
最佳答案
如果你的对象有一个重要的析构函数,Visual Studio 不应该给你那个警告。以下代码在 VS2005 中不会生成任何警告,并且警告一直向上 (/W4):
class Test
{
public:
~Test(void) { printf("destructor\n"); }
};
Test foo(void) { return Test(); }
int main(void)
{
Test t = foo();
printf("moo\n");
return 0;
}
注释掉析构函数会给出警告;代码原样没有。
关于c++ - 处理 C++ "initialized but not referenced"警告以销毁作用域助手?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/219770/