在下面的代码示例中,只要 B
的任何对象存在,就应该在 struct B
中存在一个 struct A
的实例.示例按预期工作。
#include <memory>
#include <iostream>
#include <mutex>
struct A
{
A() { std::cout << "A() called" << std::endl; }
~A() { std::cout << "~A() called" << std::endl; }
};
struct B
{
B()
{
std::cout << "B() called" << std::endl;
std::lock_guard<std::mutex> guard(mtx);
if( !refCount )
{
a.reset( new A );
}
++refCount;
}
~B()
{
std::cout << "~B() called" << std::endl;
std::lock_guard<std::mutex> guard(mtx);
--refCount;
if( !refCount )
{
a.reset( );
}
}
static std::unique_ptr<A> a;
static std::mutex mtx;
static int refCount;
};
std::unique_ptr<A> B::a;
int B::refCount(0);
std::mutex B::mtx;
int main()
{
{
B b1; //B::a should be created here
B b2;
} //B::a should be destroyed here
B b3; // B::a should be recreated here
} //B::a should be destroyed again here
另见 http://coliru.stacked-crooked.com/a/fea428254933ee5c
我的问题:是否有没有引用计数的替代(线程安全!)实现?这是否可以通过 std::shared_ptr
和 std::weak_ptr
的构造来解决?
最佳答案
确保对象“只要 B
的任何对象都存在”就存在的唯一方法是保持 B
对象的引用计数。这是判断是否存在任何事件的 B
对象、它们是否会在程序运行时被任意创建和销毁的唯一现实方法。
std::shared_ptr
在内部保留引用计数,以原子方式跟踪。使用它们可能是一个更好的主意,而不是自己手动管理引用计数;这样您就不必精心实现所有 RAII 构造函数,也不必重新发明轮子。
关于c++ - unique_ptr refcount 的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38069598/