gpt4 book ai didi

删除后的C++

转载 作者:太空宇宙 更新时间:2023-11-04 14:40:59 25 4
gpt4 key购买 nike

我是 C++ 的新手,我想知道为什么...

#include <iostream>
using namespace std;
class myClass{
public:
void myMethod(){
cout << "It works!" << endl;
}
myClass(){
cout << "myClass is constructed!" << endl;
}
~myClass(){
cout << "This class is destructed!" << endl;
}
};
int main()
{
myClass c;
c.myMethod();
myClass *e = &c;
delete e;
cout << "This is from main" << endl;
return 0;
}

上面是代码。输出是

myClass is constructed!
It works!
This class is destructed!

我想知道“This is from main”输出从哪里消失了。C++ 是否在 delete 关键字后不执行代码?

最佳答案

您只能删除 使用new 创建的对象。

你做的是UB,通过双删。

顺便说一下,虽然在这种情况下您的程序在具有 UB 的语句之后立即停止执行,但不一定非要以这种方式发生,因为

However, if any such execution contains an undefined operation, this International Standard places no requirement on the implementation executing that program with that input (not even with regard to operations preceding the first undefined operation).

关于删除后的C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39882302/

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