std :: shared_ptr向上转换为基类-最佳方法? [英] std::shared_ptr upcasting to base class - best method?
问题描述
哪种转换效果更好,有什么区别?
Which conversion is better, and what is the difference?
class Base
{};
class Derived : public Base, public std::enable_shared_from_this<Derived>
{};
int main(int argc, const char * argv[])
{
std::shared_ptr<Base> ptr1 = std::dynamic_pointer_cast<Base>(std::shared_ptr<Derived>(new Derived())); // version 1
std::shared_ptr<Base> ptr2 = std::shared_ptr<Derived>(new Derived()); // version 2
return 0;
}
推荐答案
与在 shared_ptr
的其他用例中一样,您应该更喜欢使用 make_shared
而不是构造 shared_ptr
:
As in other use cases of shared_ptr
, you should prefer using make_shared
instead of constructing the shared_ptr
manually:
std::shared_ptr<Base> ptr2 = std::make_shared<Derived>();
这实际上是您的版本2,再加上 make_shared的各种好处
.
This is essentially your version 2, plus the various benefits of make_shared
.
版本1做了很多不必要的工作:首先,您构造一个临时的 shared_ptr< Derived>
,然后您将 dynamic_cast
的内容指向基类指针(而 static_cast
就足够了),然后将该指针存储在另一个 shared_ptr< Base>
中.因此,您有许多不必要的运行时操作,但与版本2相比,类型安全性没有任何好处.
Version 1 does a bunch of unnecessary stuff: First you construct a temporary shared_ptr<Derived>
, then you dynamic_cast
its contents to a base class pointer (while a static_cast
would be sufficient here) and then you store that pointer in a different shared_ptr<Base>
. So you have a lot of unnecessary runtime operations, but no benefits regarding type safety over Version 2.
这篇关于std :: shared_ptr向上转换为基类-最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!