Pergunta

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

Foi útil?

Solução

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.

Outras dicas

(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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top