c++ - 实现智能指针时引用链接相对于引用计数的优势?

标签 c++ shared-ptr smart-pointers doubly-linked-list reference-counting

The advantage of reference linking over reference counting is that the former does not use extra free store, which makes it more reliable: Creating a reference-linked smart pointer cannot fail. The disadvantage is that reference linking needs more memory for its bookkeeping (three pointers versus only one pointer plus one integer). Also, reference counting should be a bit speedier—when you copy smart pointers, only an indirection and an increment are needed. The list management is slightly more elaborate. In conclusion, you should use reference linking only when the free store is scarce. Otherwise, prefer reference counting.

这是引用自现代 C++ 设计:应用的通用编程和设计模式。我不明白为什么基于引用链接的智能指针不使用额外的免费存储然后变得更可靠,即永不失败?谁能对此提供一些解释?谢谢!

最佳答案

当你将一个引用计数智能指针声明为一个自动变量并从空闲存储中分配存储空间供其管理时,即使指针的成员变量将在自动存储中,为簿记和管理对象创建的控制 block 也会在免费商店。一个简单的例子:

class RefCountIntPtr {
    int *pointee;
    int *count;

public:
    RefCountIntPtr(int *x) {
        if (x) {
            pointee = x;
            // allocate an int from free store and assign 1 to it
            count = new int(1);
        }
    }
};

int main() {
    RefCountIntPtr sp;
}

在这里,sppointeecount 将在 count 进行时在堆栈上分配指向将分配在堆上。假设实现(编译器)使用堆进行自由存储,使用栈进行自动存储。

另一方面,引用链接的智能指针没有来自自由存储的控制 block 分配,它们只有三个指针作为成员变量,它们都分配在自动存储上。创造更多?没问题,它们都将在自动存储中,当您将它们指向同一个指针时充当链表。不同之处在于,链表没有显式计数,而是充当隐式计数,当所有链接都消失时,我们知道计数为 0,需要释放指针。

评论可靠性的原因是,当您从免费存储分配时,在异常情况下发生泄漏的可能性更高。然而,自动变量分配要可靠得多,因为释放是由编译器自动处理的。参见 Why should C++ programmers minimize use of 'new'?了解详情。

关于c++ - 实现智能指针时引用链接相对于引用计数的优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32751155/

相关文章:

c++ - ld : symbol(s) not found for architecture x86_64 (Xcode 4)//opengles. o

c++ - 是否可以在线程运行时从线程获取数据? C++

c++ - 我可以在任何想使用简单指针的地方使用 shared_ptr 吗?

c++ - 获取智能指针的指针指针

c++ - 模板推导/替换在智能指针上失败

c++ - vector 不会推送类函数 c++

c++ - 将 VT 解包与元序列交织在一起

c++ - std::enable_shared_from_this ... 新的 shared_ptr 是否知道获取 shared_from_this()?

c++ - 调用删除器时 shared_ptr 是否仍然拥有它的对象?

c++ - 在 shared_ptr 中使用 deallocator & allocator