如何在不相关类型的共享指针中共享相同的引用计数器?

时间:2015-04-16 18:36:17

标签: c++ c++11 shared-ptr reference-counting

我有另一个班级成员。我想将共享指针转换为master类的成员。即两个对象都具有共享生命周期,而最后一个超出范围的对象将正确地破坏它们。

#include<memory>
struct Mem
{
};
struct Cont
{
  Mem m;
};

我尝试了以下有效但不完美的方法。特别是mptr.unique()不正确。有没有更好的方法来正确共享引用计数器?

void foo()
{
  std::shared_ptr<Cont> contPtr = std::make_shared<Cont>();  
  std::shared_ptr<Mem> mptr(&contPtr->m, [contPtr](Mem*){});

}

1 个答案:

答案 0 :(得分:4)

std::shared_ptr<Cont> contPtr = std::make_shared<Cont>();  
std::shared_ptr<Mem> mptr(contPtr, &contPtr->m);

this list of std::shared_ptr's constructors

上的(8)