C++ 带有派生类的 std::unique_ptr
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17417848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
std::unique_ptr with derived class
提问by Lukas Schmit
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?
我有一个关于 c++11 指针的问题。具体来说,如何将基类的唯一指针转换为派生类?
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.
提前致谢,任何建议将不胜感激。
回答by Captain Obvlious
If they are polymorphic types and you only need a pointer to the derived type use dynamic_cast
:
如果它们是多态类型并且您只需要一个指向派生类型的指针,请使用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:
如果它们不是多态类型,则只需要一个指向派生类型的指针,static_cast
并希望最好:
Derived *derivedPointer = static_cast<Derived*>(basePointer.get());
If you need to convert a unique_ptr
containing a polymorphic type:
如果需要转换unique_ptr
包含多态类型的 a:
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:
如果需要转换unique_ptr
包含非多态类型:
std::unique_ptr<Derived>
derivedPointer(static_cast<Derived*>(basePointer.release()));