Thanks all for the references. I am beginning to be able to wrap my head around it. My next question is when passing as parameters. For instance:
1 2 3 4 5 6 7 8 9 10 11
|
void baz(unique_ptr<A> temp)
{
temp->bar();
}
// .....
unique_ptr<A> b = make_unique<B>();
unique_ptr<A> c = make_unique<C>();
baz(b);
baz(c);
|
It is at this point I am getting errors (it looks like the default constructor is deleted). When moving, it works fine:
1 2 3
|
baz(move(b));
baz(move(c));
c->bar();
|
But there is a seg fault when c->bar() is called. Assuming my understanding of move semantics is correct (c would be destroyed), this is to be expected. How would I be able to pass a unique ptr over and keep its value after?
I noticed that there are no issues with using shared_ptr. Perhaps this gets back to a poor understanding of smart pointers.
unique_ptr only allows it to have one owner. In this instance, the function from which it is created is the owner and it simply cannot be passed. However, when moved, ownership goes to baz. When baz ends, the memory gets cleaned up and you get the seg fault.
shared_ptr allows for more than one owner, hence why you are able to initialize another shared_ptr with a shared_ptr and pass it in the standard fasion.
Does this sound about right?