Thursday, 28 September 2017

c++ - Which smart pointer type?




I'm fairly new to smart pointer usage, and want to make sure I'm not introducing bad habits. I have an object A that is being created from a factory, and added to a queue. This queue is then read from another thread, and at this point I think it's perfectly valid to use a unique_ptr.




struct IInterface
{

}

class A : public IInterface
{

}


std::queue> queue;


However, while constructing A I realize I need a Class C. C takes a List of B's that it owns.



class A : public IInterface
{
C c;
}


class B
{
}

class C
{
List> b;
}



To me this still looks okay because we have ownership defined. However, I'm unsure of what pointer needs to be used when Class B now needs a pointer to IInterface, which A happens to implement. Do I make it a shared_ptr?



struct IInterface
{

}

class A : public IInterface
{
C c;

}

std::queue> queue;



class B
{
shared_ptr a;
}


class C
{
List> b;
}


Did I choose the correct smart pointer, and did I analyze this correctly? I know this is super simple for you guys, but figured I would ask before I start doing things incorrectly.


Answer



Leaving aside why C owns its B objects via a pointer, the question is not whether A is used via some base class. Indeed, a shared_ptr can be used to own an object of a derived class even if Base has a non-virtual destructor!




The real question is whether the lifetime of the B objects owned by a C (which is probably the same as the lifetime of the C) is (known to be) shorter than that of the A objects to which they refer. If it is, you can stick to unique_ptr for owning the As and A* (or IInterface*) for using them. If not, you should consider using shared_ptr for both, although you should also consider other possibilities like destroying individual B objects sooner or transferring the ownership of the A to a place where it can outlive the observing references to it.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...