In the following code, I have an execution error, which I expect since I initialized ptr1 with NEW and after deleting it, I try to access the deleted object with another pointer.
#include <iostream>
#include <string>
class MyClass
{
public:
std::string name{ "Unknown" };
MyClass(){ std::cout << "Constructor" << std::endl; }
~MyClass(){ std::cout << "Destructor" << std::endl; }
void printName() { std::cout << this->name << std::endl; }
};
int main()
{
MyClass* ptr1 = new MyClass();
MyClass* ptr2 = ptr1;
delete ptr2;
ptr1->printName();
delete ptr1;
return 0;
}
In the next code, after the first delete I don't expect to be able to call the second one because I'm trying to delete an already deleted object...Could someone help me understand what's going on?
My understanding is that with NEW I have created an object in memory and that I have 2 pointers 'ptr1' and 'ptr2' that point to the same memory space.
I don't understand why the following code doesn't crash? And why the destructor can be called twice?
#include <iostream>
#include <string>
class MyClass
{
public:
std::string name{ "Unknown" };
MyClass(){ std::cout << "Constructor" << std::endl; }
~MyClass(){ std::cout << "Destructor" << std::endl; }
void printName() { std::cout << this->name << std::endl; }
};
int main()
{
MyClass* ptr1 = new MyClass();
MyClass* ptr2 = ptr1;
delete ptr1;
delete ptr2;
return 0;
}
Output
Constructor
Destructor
Destructor
Aucun commentaire:
Enregistrer un commentaire