I have created one Node
object and the pointer named head
is pointing to it. Then another pointer named newHead
is created which points to the same object. Then I delete the memory by doing delete head
and reassign head
to a nullptr
. However, this change is not reflected by the newHead
pointer. From the attached code it is evident that newHead
is not a nullptr
and accessing the member value
returns garbage value.
To understand this problem, I have already gone through this post which states that
Also note that you can delete the memory from any pointer that points to it
which is evidently not the case for the attached code below. Further I know that using smart pointers
will definitely one way to resolve the issue, but in my application, I do need to use a raw pointer.
Any help in giving me an understanding of why is this happening and how to resolve it will be appreciated. Thank you.
#include <iostream>
using namespace std;
class Node {
public:
Node(int value) {this->value = value;}
int value;
Node* next = nullptr;
};
int main(int argc, char** argv) {
// create a node object
Node* head = new Node(5);
// another pointer pointing to head
Node* newHead = head;
// delete the object pointed to by head
delete head;
head = nullptr;
// check if newHead is nullptr
if (newHead == nullptr) {
std::cout << "newHead is a nullptr" << std::endl;
}
else {
std::cout << "Head is not a nullptr" << std::endl;
std::cout << "Node value is: " << newHead->value << std::endl;
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire