ma740988 wrote:
Experimenting with smart pointers here but need a refresher here.
Consider the snippet:
# include <iostream>
# include <string>
using namespace std;
class ying {
public:
};
class yang
{
public:
};
class bar {
yang *ptr_ya;
ying *ptr_yi;
public:
bar ( yang* ptr1, ying* ptr2 )
: ptr_ya(ptr1)
, ptr_yi(ptr2)
{}
void test_yang() { ptr_ya->run_it(); }
void test_ying() { ptr_yi->run_it(); }
~bar() { delete ptr_ya; delete ptr_yi; }
};
int main()
{
yang *ptr_ya = new yang();
ying *ptr_yi = new ying();
bar b(ptr_ya, ptr_yi);
b.test_yang();
b.test_ying();
// no longer necessary. this is why we're better off with
// auto_ptrs (the smart 'pointer' stuff)
//delete ptr_ya;
//delete ptr_yi;
}
I've haven't retrofitted the source yet to use smart pointers,
nonetheless, simple question. The ying and yang objects are passed
(pass by pointer) to bar constructors. That said, it's bars
responsibility to delete ying and yang. Correct?
Without some policy in place that we could apply to this situation that
wold tell us that bar now "owns" the pointers passed in its
constructor, then I would say the answer is "no": bar should not free
the pointers since it did not allocate them. Whichever class or
function allocated the memory has the responsibility for ensuring that
the memory is freed after it's no longer needed. The allocating code
"owns" the allocated memory, and that would be the function main in
this case.
Now, ownership of allocated memory can be transferred - but there has
to be a well-documented, consistently-followed convention to perform
such a transfer. It's not enough just to decide that bar owns the
pointers because we wrote the code that way. Memory management becomes
unmaintainable unless the API alone can tell us when a class or
function assumes ownership of passed in, allocated memory.
A smart pointer lets a block of allocated memory have multiple,
concurrent owners - and a smart pointer frees the allocated memory only
after it has no more owners left. Since ownership of a smart pointer
does not need to be transferred, any code can decide to "own" a smart
pointer, without having to coordinate the transfer from anywhere else.
So by simplifying the rules of memory ownership, smart pointers are not
only easier to use, they also reduce the likelihood of
memory-management related errors.
Greg