c++ - unique_ptr refcount 的替代方案

标签 c++ c++11 smart-pointers

在下面的代码示例中,只要 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_ptrstd::weak_ptr 的构造来解决?

最佳答案

确保对象“只要 B 的任何对象都存在”就存在的唯一方法是保持 B 对象的引用计数。这是判断是否存在任何事件的 B 对象、它们是否会在程序运行时被任意创建和销毁的唯一现实方法。

std::shared_ptr 在内部保留引用计数,以原子方式跟踪。使用它们可能是一个更好的主意,而不是自己手动管理引用计数;这样您就不必精心实现所有 RAII 构造函数,也不必重新发明轮子。

关于c++ - unique_ptr refcount 的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38069598/

相关文章:

c++ - 混合可变参数模板值和可变参数推导类型

c++ - 如何处理未能释放包含在智能指针中的资源?

rust - 如何使用 Arc<Mutex<...>> 转换特征对象?

c++ - 我应该在我的类中的 std::vector 成员变量中使用 std::unique_ptr<T> 吗?

c++ 类分配的动态数组失败(内存泄漏)

c++ - 如何使用 Boost Graph Library 创建 named_graph?

c++ - boost::container::vector 无法使用 C++03 编译器进行编译

c++ - 使用具有自定义标量类型的 Eigen::Geometry 模块

c++ - 使用 std::find 根据字符串 vector 检查字符串的问题

C++20 #import ""- 语句 : Will it be possible to use multiple preprocessed header files