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

The advantage of reference linking over reference counting when implementing smart pointer?

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

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

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 将指向的将分配到堆上。假设实现(编译器)使用堆进行自由存储,使用栈进行自动存储。

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

评论可靠性的原因是,当您从免费存储区分配时,在特殊情况下泄漏的可能性更高。然而,自动变量分配要可靠得多,因为释放是由编译器自动处理的。有关详细信息,请参阅 Why should C++ programmers minimize use of 'new'?