Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::unique_ptr with derived class

I have a question about the c++11 pointers. Specifically, how do you turn a unique pointer for the base class into the derived class?

class Base { public:    int foo; }  class Derived : public Base { public:    int bar; }  ...  std::unique_ptr<Base> basePointer(new Derived); // now, how do I access the bar member? 

it should be possible, but I can't figure out how. Every time I try using the

basePointer.get() 

I end up with the executable crashing.

Thanks in advance, any advice would be appreciated.

like image 885
Lukas Schmit Avatar asked Jul 02 '13 05:07

Lukas Schmit


People also ask

What is the use of std :: unique_ptr?

std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.

Can unique_ptr be assigned?

It can be assigned: class owner { std::unique_ptr<someObject> owned; public: owner() { owned=std::unique_ptr<someObject>(new someObject()); } };

Can unique_ptr be copied?

A unique_ptr does not share its pointer. It cannot be copied to another unique_ptr , passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. A unique_ptr can only be moved.

How do you remove a unique pointer in C++?

An explicit delete for a unique_ptr would be reset() . But do remember that unique_ptr are there so that you don't have to manage directly the memory they hold. That is, you should know that a unique_ptr will safely delete its underlying raw pointer once it goes out of scope.


1 Answers

If they are polymorphic types and you only need a pointer to the derived type use dynamic_cast:

Derived *derivedPointer = dynamic_cast<Derived*>(basePointer.get()); 

If they are not polymorphic types only need a pointer to the derived type use static_cast and hope for the best:

Derived *derivedPointer = static_cast<Derived*>(basePointer.get()); 

If you need to convert a unique_ptr containing a polymorphic type:

Derived *tmp = dynamic_cast<Derived*>(basePointer.get()); std::unique_ptr<Derived> derivedPointer; if(tmp != nullptr) {     basePointer.release();     derivedPointer.reset(tmp); } 

If you need to convert unique_ptr containing a non-polymorphic type:

std::unique_ptr<Derived>     derivedPointer(static_cast<Derived*>(basePointer.release())); 
like image 127
Captain Obvlious Avatar answered Sep 24 '22 23:09

Captain Obvlious