سؤال

For example, in

unique_ptr<Derived> = new deriv;
std::vector<unique_ptr<Base>>.push_back(std::move(deriv));

will deriv be sliced to type unique_ptr<Base>?

هل كانت مفيدة؟

المحلول

No slicing will occur; the unique_ptr<Base> will own the pointer to the Derived object.

A unique_ptr to a derived class can be implicitly converted to a unique_ptr to a base class.

نصائح أخرى

(your example doesn't compile in the current edit, I'm just going to assume what your intent was)

No, it doesn't. Slicing refers to copying Derived objects into a Base object, not a Derived pointer into a Base pointer (here, the unique_ptr is a red herring).

This results in slicing:

class a { };

class b : public a { };

void foo(a myvar) { };

int main()
{
    b myb;
    foo(myb);
}

This does not:

class a { };

class b : public a { };

void foo(a* myvar) { };

int main()
{
    b myb;
    foo(&myb);
}

Any slicing that could occur, would occur on the element type of the container. Objects contained indirectly are not affected.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top