本文介绍了单个vs共享所有权意义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚看到单一时读取的维基百科共享所有权。



Google搜索,找不到任何有用的答案!

$ b $

解决方案

这本质上是 unique_ptr vs shared_ptr 。



单一拥有权, ,表示该资源由一个类实例所拥有。一旦该实例停止存在,资源被释放(通过析构函数)。您发现的大多数RAII类都有独特的所有权,例如 std :: vector 。



资源在多个类实例之间共享。资源仅在每个实例停止存在时释放,因此需要某种形式的引用计数或垃圾回收。您希望共享所有权的示例是复制不可变资源的非常昂贵的处理。我已经看到它也用于图形。



这可能有助于思考指针。单个所有权将只有1个拥有指针,共享将有多个。当然,RAII可能不涉及指针。

  + --------------- + 
|共享实例|
+ -------- + + ------------ + - + + --------------- +
| Resource | | + ---------- +共享实例|
+ -------- + vv + --------------- +
^ + -------- +
| | Resource |< ----------- +
| + -------- + + --- + ----------- +
| ^ |共享实例|
+ ------ + -------- + | + --------------- +
| Unique Instance | |
+ --------------- + |
+ ------ + -------- +
|共享实例|
+ --------------- +


Was reading Wikipedia for RAII when just saw Single and Shared ownership.

Googled for it and couldn't find any useful answer!

Could some one possibly explain this concept for a schoolboy?

解决方案

It is essentially unique_ptr vs shared_ptr.

Single ownership, otherwise known as unique ownership, means that the resource is owned by a single class instance. Once that instance ceases to exist the resource is released (via the destructor). The majority of RAII classes you find have unique ownership, such as std::vector.

Shared ownership means the resource is shared between multiple class instances. The resource is only released once every instance ceases to exist and thus requires some form of reference counting or garbage collection. An example of where you would want shared ownership is a handle to a very expensive to copy immutable resource. I've seen it used in graphs too.

It might help to think in terms of pointers. Single ownership will only have 1 owning pointer, shared will have multiple. Of course, RAII might not involve pointers.

                    +---------------+
                    |Shared instance|
    +--------+      +------------+--+           +---------------+
    |Resource|                   |   +----------+Shared instance|
    +--------+                   v   v          +---------------+
        ^                    +--------+
        |                    |Resource|<-----------+
        |                    +--------+        +---+-----------+
        |                         ^            |Shared instance|
 +------+--------+                |            +---------------+
 |Unique Instance|                |
 +---------------+                |
                           +------+--------+
                           |Shared instance|
                           +---------------+

这篇关于单个vs共享所有权意义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 05:47