shared_ptr 和切片 [英] shared_ptr and slicing
问题描述
与我共事的人曾经说过 shared_ptr 是不安全的,并且会在从派生类转换到基类(即向上转换)时进行切片.例如,如果有 2 个类 A 和 B,其中 B 派生自 A,则
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)
会切片.我向他指出 http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/shared_ptr.htm它说的地方
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
可以隐式转换为 shared_ptr
只要 T*
可以隐式转换为 U*代码>.
shared_ptr<T>
can be implicitly converted toshared_ptr<U>
wheneverT*
can be implicitly converted toU*
.
暗示在这些情况下使用是安全的,但他似乎并不这么认为.
implied that it's safe to use in those contexts but he didn't seem to think so.
推荐答案
有人错了,对象切片 不适用于指针.指针用法被包裹在 shared_ptr
中并没有改变这一点 - 它在这里没有做任何特殊的魔法,它使用传递给其构造函数的值初始化一个内部指针.
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) {}
// ...
};
您丢失了 B
的静态类型信息,是的,但是指向的对象没有任何变化.
You lose the static type-information of B
, yes, but nothing changes regarding the object pointed to.
这篇关于shared_ptr 和切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!