When you new/delete (or malloc/free --- but you shouldn't be using those in C++)... you
are not doing anything special with the pointer. You are manipulating a separate, unnamed object.
Example:
1 2 3 4 5 6 7 8
|
int* ptr; // 'ptr' is our pointer
ptr = new int; // this creates a new, unnamed int. Let's call this int 'foo'
// we then assign a pointer to foo to our pointer, 'ptr'
*ptr = 5; // this assigns 5 to 'foo'
delete ptr; // this deletes 'foo' (since 'ptr' points to 'foo'). IT DOES NOT
// delete 'ptr'
|
So to answer your 2nd question:
1 2 3 4 5 6 7 8
|
int* a = new int; // create 'foo'. make 'a' point to it
int* b = a; // make 'b' point to the same thing 'a' points to
// here, both a and b point to foo.
delete a; // this deletes foo
delete b; // <- this attempts to delete foo AGAIN which is BAD. foo has already
// been deleted. This will likely cause your program to crash.
|
So the answer to the 2nd question is: You have exactly 1 'delete' for every 'new'. The number of pointers does not matter. in this case, you would delete only one of the pointers because you only allocated one of them.
As for the 1st question...
shared_ptr and unique_ptr automate the cleanup process:
1 2 3 4
|
std::unique_ptr<int> ptr( new int ); // create 'foo', make 'ptr' point to it
// no need to delete it... ever. unique_ptr will delete it
// in the destructor. So cleanup will happen automatically
|
unique_ptr assumes "ownership" of 'foo'. So as soon as the unique_ptr goes out of scope (dtor called), 'foo' will be deleted.
shared_ptr is the same idea... only instead of having 1 owner, you can have multiple pointer sharing ownership... meaning that 'foo' would only be deleted when
all shared_ptrs go out of scope (vs. unique_ptr where there is only 1 pointer)
shared_ptr has pitfalls associated with it, where it's possible to have circular dependencies... leading to leaks because neither pointer ever goes out of scope. So you generally should stick to unique_ptr unless you have a good reason not to.
EDIT: ninja'd by LB