本文介绍了共享指针如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

共享指针如何知道有多少个指针指向该对象? (shared_ptr,在这种情况下)

解决方案

基本上, shared_ptr 指针:指向共享对象的指针和指向包含两个引用计数的结构的指针:一个用于强引用,一个用于具有所有权的引用,另一个用于弱引用或不具有所有权的引用。 / p>

复制 shared_ptr 时,复制构造函数会增加强引用计数。当销毁一个 shared_ptr 时,析构函数减少强引用计数,并测试引用计数是否为零;如果是,析构函数删除共享对象,因为没有 shared_ptr 指向它。



弱引用count用于支持 weak_ptr ;基本上,任何时候从 shared_ptr 创建 weak_ptr ,弱引用计数增加,并且任何时候被销毁的弱引用计数递减。只要强引用计数或弱引用计数大于零,引用计数struct就不会被销毁。



有效地,只要强引用count大于零,共享对象不会被删除。只要强引用计数或弱引用计数不为零,引用计数struct就不会被删除。


How do shared pointers know how many pointers point to that object? (shared_ptr, in this case)

解决方案

Basically, shared_ptr has two pointers: a pointer to the shared object and a pointer to a struct containing two reference counts: one for "strong references," or references that have ownership, and one for "weak references," or references that don't have ownership.

When you copy a shared_ptr, the copy constructor increments the strong reference count. When you destroy a shared_ptr, the destructor decrements the strong reference count and tests whether the reference count is zero; if it is, the destructor deletes the shared object because no shared_ptrs point to it anymore.

The weak reference count is used to support weak_ptr; basically, any time a weak_ptr is created from the shared_ptr, the weak reference count is incremented, and any time one is destroyed the weak reference count is decremented. As long as either the strong reference count or the weak reference count is greater than zero, the reference count struct will not be destroyed.

Effectively, as long as the strong reference count is greater than zero, the shared object will not be deleted. As long as the strong reference count or the weak reference count is not zero, the reference count struct will not be deleted.

这篇关于共享指针如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 23:18