There are two concepts (ownership, lifetime) that are important when using C++ smart pointers (unique, shared, weak). I try to understand those concepts and how they influence smart pointer (or raw pointer) usage.
I read two rules:
- Always use smart pointers to manage ownership/lifetime of dynamic objects.
- Don't use smart pointers when not managing ownership/lifetime.
An example:
class Object
{
public:
Object* child(int i) { return mChildren[i]; }
// More search and access functions returning pointers here
private:
vector<Object*> mChildren;
};
I want to rewrite this using smart pointers. Lets ignore child() first. Easy game. A parent owns its children. So make mChildren a vector of unique_ptr.
According to the above rules, some people argue child(i) should continue returning a raw pointer.
But isn't this risky? Someone could do stupid things like deleting the returned object getting a hard to debug crash... which could be avoided using a weak_ptr or a shared_ptr as a return value.
Can't one say that copying a pointer always means to temporarily share the ownership and/or to assert the lifetime of the object?
Is it worth using smart pointers for children only if I do not get a safer API as well?