铸造智能指针 [英] Casting of smart pointers
问题描述
一段时间以来,我一直在使用Raw指针,现在我正在尝试使用智能指针。
I have been using Raw pointers for a while , now i am trying to use Smart Pointers.
如果ClassB是ClassA的子代。
if ClassB is child of ClassA.
我可以使用原始指针来完成此操作。
I can do this with raw pointers.
ClassA* ptr = new ClassB;
此行将等同于上述行。
std::shared_ptr<ClassA> ptr = std::shared_ptr<ClassB>(new ClassB);
当ptr超出范围时,内存将被清除。
when ptr goes out of scope the memory will be cleared.
推荐答案
Kinda是。
Kinda是因为 std :: shared_ptr
比原始指针慢。如果您在其他地方传递了共享指针的副本,则不会释放对象,但是一旦所有共享指针都消失了,它就会被释放。
Kinda is because std::shared_ptr
is slower than raw pointers. Object won't get deallocated if you passed a copy of the shared pointer somewhere else, but it will get deallocated once all the shared pointers to it are gone.
此外,引用计数器跟踪器是安全线程。
Furthermore, the reference counter tracker is safe-thread.
也 ClassA
不需要虚拟析构函数即可使共享指针正常工作。
Also ClassA
need not have a virtual destructor for the shared pointer to work properly.
您可以想象,这些功能非常昂贵。
As you can imagine, these features are costly.
如果需要与原始指针相同的性能,则可以通过使用 std :: unique_ptr
来实现。但是,它是不可复制的,其用法可能会使C ++ 11中新引入的语言感到困惑。
If you need same performance as raw pointers, you can achieve it by utilizing std::unique_ptr
. Though, it is non-copyable and its usage might confuse newly introduced to C++11.
除此之外,建议使用 std :: make_shared
和 std :: make_unique
用于初始化所述智能指针。
Aside from that, it is recommended to use std::make_shared
and std::make_unique
for initializing said smart pointers.
这篇关于铸造智能指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!