What is boost's shared_ptr(shared_ptr const & r, T * p) used for?

后端 未结 6 1225
孤街浪徒
孤街浪徒 2021-02-01 04:28

boost::shared_ptr has an unusual constructor

template shared_ptr(shared_ptr const & r, T * p);

and I a

6条回答
  •  被撕碎了的回忆
    2021-02-01 04:57

    For "shared_ptr b(a, dynamic_cast(a.get()));"

    I think it is not the recommended way using smart pointer.

    The recommended way of doing this type conversion should be:

    shared_ptr b(a);
    

    Since in Boost document it is mentioned that:

    shared_ptr can be implicitly converted to shared_ptr whenever T* can be implicitly converted to U*. In particular, shared_ptr is implicitly convertible to shared_ptr const, to shared_ptr where U is an accessible base of T, and to shared_ptr.

    In addition to that, we also have dynamic_pointer_cast which could directly do conversion on Smart Pointer object and both of these two methods would be much safer than the manually casting raw pointer way.

提交回复
热议问题