4

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

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
user383352
  • 5,033
  • 4
  • 25
  • 20

3 Answers3

6

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.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
2

(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);
}
Terry Mahaffey
  • 11,775
  • 1
  • 35
  • 44
1

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

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720