提高::shared_ptr和boost::shared_ptr共享引用计数?

[英]Do boost::shared_ptr and boost::shared_ptr share the reference count?


There are several interesting questions on pitfalls with boost::shared_ptrs. In one of them, there is the useful tip to avoid pointing boost::shared_ptr<Base> and boost::shared_ptr<Derived> to the same object of type Derived since they use different reference counts and might destroy the object prematurely.

关于boost的缺陷有几个有趣的问题:shared_ptrs。其中有一个有用的技巧可以避免指向boost::shared_ptr和boost::shared_ptr <派生的> 到派生的类型相同的对象,因为它们使用不同的引用计数,可能会过早地破坏对象。

My question: Is it safe to have both boost::shared_ptr<T> and boost::shared_ptr<const T> point to the same object of type T, or will this cause the same problem?

我的问题是:拥有boost: shared_ptr 和boost::shared_ptr 指向同一个类型T的对象,安全吗?

1 个解决方案

#1


18  

It is perfectly safe.

它是完全安全的。

The following code sample:

以下代码示例:

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

Compiles and run fine, and is perfectly correct. It outputs:

编译和运行良好,并且完全正确。输出:

a: 2
b: 2

The two shared_ptr share the same reference counter.

两个shared_ptr共享同一个引用计数器。


Also:

另外:

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

Behave the same way. You must, however never build your shared_ptr using a construct like this:

相同的行为。但是,千万不要使用这样的结构来构建shared_ptr:

boost::shared_ptr<A> a(new B());
boost::shared_ptr<B> b(static_cast<B*>(a.get()));

a.get() gives the raw pointer and loses all information about reference counting. Doing this, you'll end up with two distinct (not linked) shared_ptr that use the same pointer but different reference counters.

get()提供原始指针并丢失有关引用计数的所有信息。这样,您将得到两个不同的shared_ptr(没有链接),它们使用相同的指针,但使用不同的引用计数器。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2010/09/30/53d375aae25b21824fbc91c1a5eaf6a7.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号