【发布时间】:2012-05-30 14:39:43
【问题描述】:
我正在开发一个使用 VC9 构建的应用程序,但我遇到了一个我不完全理解的警告:为什么在构造函数的右大括号上有一个“无法访问代码”警告?强>
重现问题的最小测试用例是:
__declspec(noreturn) void foo() {
// Do something, then terminate the program
}
struct A {
A() {
foo();
} // d:\foo.cpp(7) : warning C4702: unreachable code
};
int main() {
A a;
}
这必须用 /W4 编译才能触发警告。或者,您可以使用 /we4702 进行编译,以在检测到此警告时强制出错。
d:\>cl /c /W4 foo.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 15.00.21022.08 for x64
Copyright (C) Microsoft Corporation. All rights reserved.
foo.cpp
d:\foo.cpp(7) : warning C4702: unreachable code
有人能准确地解释一下这里无法到达的地方吗?我最好的理论是它是析构函数,但我想要一个明确的答案。
如果我想让这段代码警告干净,我该如何实现?我能想到的最好的办法就是将它转换为编译时错误。
struct A {
private:
A(); // No, you can't construct this!
};
int main() {
A a;
}
编辑:为澄清起见,使用 noreturn 函数终止程序通常不会在包含该函数调用的右大括号上引起无法访问的代码警告。
__declspec(noreturn) void foo() {
// Do something, then terminate the program
}
struct A {
A() {
}
~A() {
foo();
}
};
int main() {
A a;
}
结果:
d:\>cl /c /W4 foo3.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 15.00.21022.08 for x64
Copyright (C) Microsoft Corporation. All rights reserved.
foo3.cpp
【问题讨论】:
-
因为你终止了
foo()中的程序? -
制作
private而不实现它是通常的方式,C++11 有= delete来实现它。 -
必须
foo()是__declspec(noreturn)吗? -
@ixe013:是的,
foo()在其他地方使用,重要的是我们在使用后标记无法访问的代码。我想我们可以有两个版本的foo(),但这感觉有点傻(一个特殊的版本只用于构造函数?)。 -
这在我看来像是一个编译器错误。因此,您有理由在构造函数期间禁用此警告,并用一个大注释解释原因。
标签: c++ visual-c++ constructor visual-c++-2008 unreachable-code