shared_ptr and slicing

后端 未结 2 682
后悔当初
后悔当初 2021-01-11 22:01

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 cl

2条回答
  •  渐次进展
    2021-01-11 22:27

    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 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.

提交回复
热议问题