简体   繁体   English

智能指针是否可以进行切片?

[英]Is it possible for slicing to occur with Smart Pointers?

If I understand slicing correctly I don't think this could happen with pointers or smart pointers. 如果我理解切片正确,我不认为这可能发生指针或智能指针。 For example, if you had: 例如,如果你有:

class A
{
int something;
};

class B : public A
{
int stuff;
int morestuff;
};

int main()
{
    std::shared_ptr<B> b(new B());
    std::shared_ptr<A> a;
    a = b;
}

My understanding is that the block of memory allocated to the object pointed to by "b" is still the same and doesn't change when assigned to the smart pointer "a". 我的理解是,分配给“b”所指向的对象的内存块仍然相同,并且在分配给智能指针“a”时不会改变。

Please confirm or reject my understanding, or let me know of any pitfalls associated with this. 请确认或拒绝我的理解,或让我知道与此相关的任何陷阱。

A smart pointer is still a pointer, so such an assignment won't cause slicing. 智能指针仍然是指针,因此这样的赋值不会导致切片。 Slicing happens only when dealing with values, not pointers. 切片仅在处理值时发生,而不是指针。 Note, however, templates don't know about the relationships between the items the point at, so even though B derives from A, shared_pointer<B> doesn't derived from shared_pointer<A> , so an assignment doesn't (automatically) get an automatic up-cast like it would with native pointers. 但是请注意,模板不知道点之间的项之间的关系,因此即使B派生自A, shared_pointer<B>也不是从shared_pointer<A>派生的,因此赋值不会(自动)像使用原生指针一样获得自动上传。

Edit: elaborating on final point. 编辑:详细阐述最后一点。

Slicing happens with values, not pointers, so (given your definitions of A and B), something like: 切片发生在值而不是指针上,所以(给定A和B的定义),类似于:

A ax = b; A ax = b;

would work, but would "slice" the B object to become an A object. 会工作,但会“切片”B对象成为A对象。 If, however, you have some sort of template that holds an instance of the item: 但是,如果您拥有某种包含该项目实例的模板:

template <class T>
class holder { 
   T t_;
public:
   holder &operator=(T const &t) { 
       t_ = t;
       return *this;
   }
   holder &operator=(holder const &t) { t_ = t; return *this; }
};

Now, if we try to assign one value to another, like would cause slicing: 现在,如果我们尝试将一个值分配给另一个,就像会导致切片一样:

holder<A> ha;
holder<B> hb;

A a;
B b;

ha = a;
hb = b;
ha = hb;

we will NOT get slicing. 我们不会切片。 Instead, the compiler will simply give us an error, telling us that holder<A> and holder<B> are not related types, so the assignment can't happen -- without adding an explicit cast, it simply won't compile. 相反,编译器只会给我们一个错误,告诉我们holder<A>holder<B>不是相关类型,因此分配不会发生 - 如果不添加显式强制转换,它就不会编译。

你是对的,但它们不一样:你无法评估a->stuff

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM