views:

72

answers:

3

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

+3  A: 

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
+1  A: 

(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
+1  A: 

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

Ben Voigt