guitarm87
He's talking about making one of the pointers (that is part of several pointers going into the parameter list) "the owner"
The reason for this seems to be to know which one to delete (to do "delete" in code that is)
But...either I've misunderstood this completely or there's something I've missed: Aren't pointers in a parameter list put on the stack since they're part of the function? and if that is the case, don't the get removed automagically when leaving the scope of that function?
I thought you never do a delete on a pointer that has no new?
A pointer and the data it points to are two different things. The pointer itself is just an integer, the address of the memory it points to. However, the data block it is pointing to might be dynamically allocated.
If I write the following:
| Foo * my_foo = new Foo;
delete my_foo;
|
Line 1 is telling the runtime: "Allocate a block of memory large enough to fit a Foo, and place its address in my_foo."
Line 2 : "Deallocate the (previously allocated) block of memory at the address in my_foo."
When you call a function with a pointer argument, you are correct, the pointer itself gets copied onto the stack as a local. However, the data it *points to* is not. So, on function exit, the 4- or 8-byte integer holding the address gets deallocated, but not the Foo being pointed at.
Finally, the real problem arrives in that you can have multiple pointers to the same address:
| Foo * my_foo = new Foo;
Foo * my_foo2 = my_foo;
delete my_foo;
delete my_foo2; // UH OH!
|
This is a "double-free" -- we're deallocating the memory *twice*, through two different pointers.
There are even worse issues:
| Foo * my_foo = new Foo;
Foo * my_foo2 = my_foo;
delete my_foo;
// Insert a few hundred lines here.
my_foo2->bar = 12;
|
This is a "use-after-free" -- among other things, a serious security vulnerability.
This is the problem he's addressing when talking about ownership. If you know that one -- and *only* one -- pointer "owns" the memory, then you don't have to worry about which pointer is used to free.
Does that help?