10 ms·
In my experience unique pointers are usually a better fit than shared pointers. That is not to say shared pointers do not have their place, but they can definit
by mytherin 7y ago
In my experience unique pointers are usually a better fit than shared pointers. That is not to say shared pointers do not have their place, but they can definitely be abused. Especially for developers that come from garbage collected languages, it might be tempting to replace all pointers with shared pointers and call it a day. Not only can this cause performance issues when these are used in performance critical locations, but you can also lose track of who owns what very easily.
It is also very easy to accidentally create cyclic references with shared pointers. Suppose you have a class like this:
struct Node {
shared_ptr<Node> parent;
shared_ptr<Node> child;
};
This rather innocent looking class creates a cycle when you fill in the values, because the parent and child reference each other. That cycle now means your nodes will not be cleaned up anymore.
Unique pointers do not have any of these problems. They cannot create cycles, are very cheap and they make it very explicit who owns what. They are not suitable for every situation (i.e. when there is actually shared ownership shared pointers should be used) but in most situations I find that they are sufficient and have a lot less pitfalls than shared pointers.
- im3w1l 7y ago> They cannot create cycles, I don't think this is true. Couldn't you accidentally make two objects "own" each other?
- deleted 7y ago[deleted]
- mytherin 7y agoYes, excellent point. It is possible to make cycles, it is just a lot more difficult to do accidentally than with shared pointers.
- saagarjha 7y ago> This rather innocent looking class creates a cycle when you fill in the values, because the parent and child reference each other. That cycle now means your nodes will not be cleaned up anymore. It’s fairly common knowledge, but just to answer the inevitable question: you can avoid the cycle with weak pointers.