我刚刚接受采访。有人问我什么是“前瞻性声明”。然后有人问我是否存在与前瞻性声明相关的危险。
我无法回答第二个问题。在网上搜索并没有出现任何有趣的结果。
那么,有人知道使用前向声明有什么危险吗?
好吧,除了重复的问题之外......
...标准中至少有一个痛处。
如果你打电话delete
在指向不完整类型的指针上,您会得到未定义的行为。实际上,析构函数可能不会被调用。
我们可以看到生活工作空间 http://liveworkspace.org/code/fiKs6%242使用以下命令和示例:
// -std=c++11 -Wall -W -pedantic -O2
#include <iostream>
struct ForwardDeclared;
void throw_away(ForwardDeclared* fd) {
delete fd;
}
struct ForwardDeclared {
~ForwardDeclared() {
std::cout << "Hello, World!\n";
}
};
int main() {
ForwardDeclared* fd = new ForwardDeclared();
throw_away(fd);
}
诊断:
Compilation finished with warnings:
source.cpp: In function 'void throw_away(ForwardDeclared*)':
source.cpp:6:11: warning: possible problem detected in invocation of delete operator: [enabled by default]
source.cpp:5:6: warning: 'fd' has incomplete type [enabled by default]
source.cpp:3:8: warning: forward declaration of 'struct ForwardDeclared' [enabled by default]
source.cpp:6:11: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined
您不想感谢您的编译器向您发出警告吗;)?
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)