Class example { }; int main() { Example* pointer1 = new example(); Example* pointer2; pointer2 = pointer1; delete pointer1; } Should I delete pointer2? I think it's in the stack and I don't need to delete.
Short answer: No.
pointer1 and pointer2 are both pointers which exist on the stack. new Example allocates on the heap a new object of type Example, and its memory address is stored in pointer1. When you do delete pointer1, you are freeing the memory allocated on the heap. Since both pointer1 and pointer2 are both referencing the same memory location at the point of the delete call, it does not need to also be deleted, in fact, this would be Undefined Behaviour, and could cause heap corruption or simply your program to crash.
At the end of this, both pointer1 and pointer2 are still pointing to the same block of memory, neither are actually nullptr.
new must be matched by exactly one call to delete. Also careful on the terms heap and stack those terms, these are not strictly part of C++; you should use the terms automatic storage duration and dynamic storage duration. The reason I bring it up as you get into the more complex details heap and stack become confusing while storage duration continues to work. I suppose in this situation it works but be careful.Deleting a pointer is telling the operating system that the memory at the location of that pointer is not needed anymore by the program. Remember that a pointer is just an integer that points to place in your RAM. By doing pointer2 = pointer1, you're only copying the integer and you're not moving any memory around. Therefore, by deleting the first pointer, because the second pointer points to the same location, you don't need to delete it.
newit, you shoulddeleteit. Once. If you pass along ownership, you are passing along the responsibility to delete it, and the passer is relinquishing that responsibility. (But it is better to express that ownership more explicitly in the code by usingstd::unique_ptrorstd::shared_ptr.)pointer2will be a dangling pointer. You need to set it tonullptryourself (if that is important to your code).