[英]C++: object deleted (created with new) but member function still working (?)
Just for curiosity and experimenting I wrote following code and now am trying to understand whats happening after delete... why is the cat object still meowing ?? 出于好奇和实验目的,我编写了以下代码,现在试图了解删除后发生的事情...为什么cat对象仍然发出声音?
the compiler version I use: 我使用的编译器版本:
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609
and compile the code: 并编译代码:
g++ cat.cpp -pedantic -Wall -o cat
With other compilers may crash when calling meou() after delete. 与其他编译器一起删除后调用meou()可能会崩溃。
I would like to know 我想知道
the code: 编码:
#include <iostream>
using namespace std;
class Cat
{
public:
Cat() { cout << "Cat construct" << endl; }
~Cat() { cout << "Cat destruct" << endl; }
void meow();
};
void Cat::meow(void)
{
cout << "meow..." << endl;
}
int main()
{
Cat * pCat = new Cat;
pCat->meow();
cout << "pCat = " << pCat << endl;
delete pCat;
pCat = NULL;
cout << "pCat = " << pCat << endl;
pCat->meow();
cout << "why still meowing?!" << endl;
return 0;
}
the output: 输出:
Cat construct
meow...
pCat = 0x2147030
Cat destruct
pCat = 0
meow...
why still meowing?!
why is not crashing
为什么不崩溃
Because dereferencing nullptr
or accessing a deleted object is undefined behaviour. 因为取消引用
nullptr
或访问已删除的对象是未定义的行为。 C++ doesn't have required crashes, but crashes can be the result of undefined behaviour. C ++不需要崩溃,但是崩溃可能是未定义行为的结果。
which precautions should I take
我应该采取哪些预防措施
That's a rather broad topic. 那是一个相当广泛的话题。 The most important thing in C++ is not to use dynamic allocation if you don't need to.
在C ++中,最重要的是不需要使用动态分配。 Write:
写:
Cat cat;
cat.meow();
If you cannot do that, use std::unique_ptr
: 如果您不能这样做,请使用
std::unique_ptr
:
auto cat_ptr = std::make_unique<Cat>();
cat_ptr->meow();
If you need a collection, don't use new[]
. 如果您需要集合,请不要使用
new[]
。 Use std::vector
: 使用
std::vector
:
std::vector<Cat> cats;
std::vector<std::unique_ptr<Cat>> cat_ptrs;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.