lyt*_*nyn 12 c++ boost smart-pointers shared-ptr
关于boost::shared_ptrs的陷阱有几个有趣的问题.在其中一个中,有一个有用的提示,以避免指向boost::shared_ptr<Base>和boost::shared_ptr<Derived>相同的类型对象,Derived因为它们使用不同的引用计数,并可能过早地破坏对象.
我的问题:是否安全兼得boost::shared_ptr<T>并boost::shared_ptr<const T>点型的同一个对象T,还是将导致同样的问题?
ere*_*eOn 19
这是非常安全的.
以下代码示例:
#include <iostream>
#include <boost/shared_ptr.hpp>
int main(int, char**)
{
boost::shared_ptr<int> a(new int(5));
boost::shared_ptr<const int> b = a;
std::cout << "a: " << a.use_count() << std::endl;
std::cout << "b: " << b.use_count() << std::endl;
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
编译并运行良好,完全正确.它输出:
a: 2
b: 2
Run Code Online (Sandbox Code Playgroud)
两者shared_ptr共用同一个参考计数器.
也:
#include <iostream>
#include <boost/shared_ptr.hpp>
class A {};
class B : public A {};
int main(int, char**)
{
boost::shared_ptr<A> a(new B());
boost::shared_ptr<B> b = boost::static_pointer_cast<B>(a);
std::cout << "a: " << a.use_count() << std::endl;
std::cout << "b: " << b.use_count() << std::endl;
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
表现方式相同.但您必须永不您建立shared_ptr使用这样的结构:
boost::shared_ptr<A> a(new B());
boost::shared_ptr<B> b(static_cast<B*>(a.get()));
Run Code Online (Sandbox Code Playgroud)
a.get()给出原始指针并丢失有关引用计数的所有信息.这样做,你最终会得到两个不同的(没有链接的)shared_ptr使用相同的指针但不同的引用计数器.