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 ??
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.
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. C++ doesn't have required crashes, but crashes can be the result of undefined behaviour.
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. Write:
Cat cat;
cat.meow();
If you cannot do that, use std::unique_ptr
:
auto cat_ptr = std::make_unique<Cat>();
cat_ptr->meow();
If you need a collection, don't use new[]
. Use std::vector
:
std::vector<Cat> cats;
std::vector<std::unique_ptr<Cat>> cat_ptrs;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.