gpt4 book ai didi

c++11 - shared_ptr 引用计数器是如何布局的?

转载 作者:行者123 更新时间:2023-12-04 02:51:12 27 4
gpt4 key购买 nike

我是 C++ 的新手。我一直认为 shared_ptr 将单独的指针保存到单独的引用计数器变量。但是今天突然发现其实我不知道它是怎么布局的,引用值不需要在C++中有单独的指针。

如果布局由标准定义,std::shared_ptr 的正确预期布局是什么?

最佳答案

C++ 标准没有为任何非标准布局类定义它应该如何在内存中布局,例如[class.mem]/13

Nonstatic data members of a (non-union) class with the same access control (Clause 11) are allocated so that later members have higher addresses within a class object. The order of allocation of non-static data members with different access control is unspecified (Clause 11). Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions (10.3) and virtual base classes (10.1).

标准布局类型有一些异常(exception)/简化,但类的内存布局没有通用规范。

这也适用于标准库中的类。除此之外,标准只定义了对这些类的要求,其中一些是成员函数签名意义上的“接口(interface)”。在 [objects.within.classes] 中非常明确:

1) Clauses 18 through 30 and Annex D [i.e. the Standard Library] do not specify the representation of classes, and intentionally omit specification of class members (9.2). An implementation may define static or non-static class members, or both, as needed to implement the semantics of the member functions specified in Clauses 18 through 30 and Annex D.

2) Objects of certain classes are sometimes required by the external specifications of their classes to store data, apparently in member objects. For the sake of exposition, some subclauses provide representative declarations, and semantic requirements, for private member objects of classes that meet the external specifications of the classes. The declarations for such member objects and the definitions of related member types are followed by a comment that ends with exposition only, as in:

streambuf* sb; // exposition only

也就是说,对 std::shared_ptr 所需功能的一些评论:

  • 您需要将拥有对象的引用计数存储在一个动态分配的对象中,该对象包含此所有权信息(dyn.alloc。因为不清楚哪个 shared_ptr 是最后一个活着的,并且最后一个必须取消分配它)
  • 您还需要存储此所有权信息对象的引用计数以供weak_ptr 使用,如weak_ptr::expiredweak_ptr::lock 等可能不会失败(例如,通过访问冲突)

迂腐的旁注:标准不要求 shared_ptr not 泄漏内存,但 PC 类型架构的典型实现可能会使用动态内存分配。

std::make_shared btw 被认为比使用 std::shared_ptr 的构造函数更快,因为它可以为拥有的对象和所有权分配内存一次分配中的信息对象(标准说“实现不应执行超过一次内存分配。”,尽管这只是一个备注)。

关于c++11 - shared_ptr 引用计数器是如何布局的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17627302/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com