关于boost::shared_ptr的陷阱,有几个有趣的问题。在其中之一中,有一个有用的技巧,可以避免将boost::shared_ptr<Base>boost::shared_ptr<Derived>指向Derived类型的同一对象,因为它们使用不同的引用计数,并且可能会过早地破坏该对象。

我的问题:将boost::shared_ptr<T>boost::shared_ptr<const T>都指向T类型的同一对象是否安全,否则会导致相同的问题吗?

最佳答案

这是绝对安全的。

以下代码示例:

#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;
}

编译并运行正常,并且完全正确。它输出:
a: 2
b: 2

这两个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;
}

行为方式相同。但是,您必须绝对不要使用类似以下的构造来构建shared_ptr:
boost::shared_ptr<A> a(new B());
boost::shared_ptr<B> b(static_cast<B*>(a.get()));
a.get()提供了原始指针,并丢失了有关引用计数的所有信息。这样做,您将得到两个不同的(未链接的)shared_ptr,它们使用相同的指针但使用不同的引用计数器。

关于c++ - boost::shared_ptr <T>和boost::shared_ptr <const T>是否共享引用计数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3828497/

10-10 21:26
查看更多