Search code examples
c++shared-ptr

shared_ptr and slicing


Someone I worked with once said that shared_ptr was unsafe and would slice when casting from a derived class to a base class (i.e. upcasting). For example if there were 2 classes A and B where B derived from A, then

shared_ptr<A> a(new B)

would slice. I pointed him to http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/shared_ptr.htm where it says

shared_ptr<T> can be implicitly converted to shared_ptr<U> whenever T* can be implicitly converted to U*.

implied that it's safe to use in those contexts but he didn't seem to think so.


Solution

  • That someone is wrong, object slicing doesn't apply to pointers. That the pointer usage is wrapped away in a shared_ptr doesn't change that - it doesn't do any particular magic here, it initializes an internal pointer with the value passed to its constructor.

    Simplified it could look e.g. like this for the purpose of this question:

    template<class T> struct ptr {
        T* t;
        ptr(T* t) : t(t) {}
        // ...
    };
    

    You lose the static type-information of B, yes, but nothing changes regarding the object pointed to.