gpt4 book ai didi

c++ - 提前申报有什么危险?

转载 作者:IT老高 更新时间:2023-10-28 13:00:32 25 4
gpt4 key购买 nike

我刚刚接受了采访。有人问我什么是“前向声明”。然后我被问到它们是否是与前向声明相关的危险。

我无法回答第二个问题。在网上搜索并没有显示任何有趣的结果。

那么,有人知道与使用前向声明相关的任何危险吗?

最佳答案

嗯,除了重复的问题...

...标准中至少有一个痛点。

如果你在指向不完整类型的指针上调用 delete,你会得到未定义的行为。实际上,析构函数可能不会被调用。

我们可以在 LiveWorkSpace 上看到使用以下命令和示例:

// -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

你不想感谢你的编译器警告你吗?)?

关于c++ - 提前申报有什么危险?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14381348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com