前瞻性声明的危险是什么? [英] What are the dangers of forward declarations?
问题描述
我刚刚接受采访。我被问什么是前进声明。然后我问他们是否是与远期申报相关的危险。
I just had an interview. I was asked what is a "forward declaration". I was then asked if they were dangers associated with forward declarations.
我无法回答第二个问题。在网上搜索没有显示任何有趣的结果。
I could not answer to the second question. A search on the net didn't show up any interesting result.
那么,有人知道与使用前瞻性声明相关的任何危险吗?
So, do someone know any dangers associated with the use of forward declarations ?
推荐答案
很好,除了有关重复的问题...
Well, apart from the issues about duplication...
...
如果在指向不完整类型的指针上调用 delete
得到未定义的行为。在实践中,析构函数可能不会被调用。
If you call delete
on a pointer to an incomplete type, you get undefined behavior. In practice, the destructor may not get called.
我们可以看到,在 LiveWorkSpace 使用以下命令和示例:
We can see that on LiveWorkSpace using the following command and sample:
// -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
不要感谢你的编译器警告你;)
Don't you want to thank your compiler for warning you ;) ?
这篇关于前瞻性声明的危险是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!