为什么shared_ptr实现中的ref_count是int*

hav*_*vij 8 c++ shared-ptr

我已经看到了几个shared_ptr的实现,例如这里.所有人都宣称ref_countint*.我不明白,如果只是一个,我们会失去什么int.谢谢!

template <class T>
class shared_ptr {
    T* ptr;
    int* ref_count;

    /**
     * Initializes the ref count used for tracking the usage.
     */
    void initialize_ref_count() {
        if (ref_count != nullptr)
            return;
        try {
            ref_count = new int;
            *ref_count = 1;
        }
        catch (std::bad_alloc& e) {
            std::cerr << "Memory allocation error: " << e.what();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

who*_*oan 8

正如您在(在链接中)提供的实现中所看到的,当共享指针被复制构造复制分配时,指向引用计数器(ref_count)的指针在管理同一指针的所有实例之间共享:

    // Copy constructor
    shared_ptr(const shared_ptr& copy) {
        ptr = copy.ptr;
        ref_count = copy.ref_count; // see here
        if (ref_count != nullptr) {
            ++(*ref_count);
        }
    }

    // Assignment operator
    shared_ptr& operator=(const shared_ptr& copy) {
        ptr = copy.ptr;
        ref_count = copy.ref_count; // see here
        if (ref_count != nullptr) {
            ++(*ref_count);
        }
        return *this;
}
Run Code Online (Sandbox Code Playgroud)

这样,该共享指针的所有实例都引用相同的内存位置来跟踪ref计数器,最后一个shared_ptr将能够知道它是否需要进行清理(delete分配的内存):

   ~shared_ptr() {
        --(*ref_count);
        if (*ref_count == 0) {
            delete ref_count;
            ref_count = nullptr;
            delete ptr;
            ptr = nullptr;
        }
    }
Run Code Online (Sandbox Code Playgroud)

放弃

这个答案基于OP为简单起见提供的示例.一个shared_ptr实现更为复杂的是,一个在本例中(想想原子,比赛条件等).

  • FWIW,`operator =`函数有问题.在向它分配`copy.ref_count`之前,它应该首先递减`this`的`ref_count`. (4认同)