unique_ptr - 主要改进? [英] unique_ptr - major improvement?

查看:156
本文介绍了unique_ptr - 主要改进?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实际的C ++标准中,创建满足以下规则的集合很困难,如果不是不可能的话:


  1. 异常安全,

  2. 廉价的内部操作(在实际的STL容器中:操作是副本),

  3. 自动内存管理。

为了满足(1),集合不能存储原始指针。要满足(2),集合必须存储原始指针。要满足(3),集合必须按值存储对象。



结论:三个项目彼此冲突。



使用 shared_ptr 时,不满足项目(2),因为当集合需要移动元素时,需要进行两个调用:构造函数和析构函数。没有大量的, memcpy() - 可能的复制/移动操作。



将由 unique_ptr std :: move()解决?使用这些工具的集合将能够满足所有3个条件:


  1. 当集合将作为异常的副作用被删除时,将调用 unique_ptr 的析构函数。没有内存泄漏。



    • unique_ptr 不需要任何额外的空间参考计数器;因此它的主体应该是完全相同的大小,作为包装指针,

    • 我不知道,但它看起来像这样允许移动组 unique_ptrs memmove()类似操作(),

    • 可能, std :: move()操作符将允许移动每个 unique_ptr 对象,而不需要构造函数/析构函数对


  2. unique_ptr 将对给定内存拥有独占所有权。不会发生意外内存泄漏。

这是真的吗?使用 unique_ptr

解决方案的其他优点是什么?最后一种处理堆分配对象的自然方式。



在回答:


我不确定,但它看起来像这样允许使用 memmove()移动 unique_ptr 的组喜欢操作,


有一个提案以允许此操作,但尚未将其纳入C ++ 11标准。


In the actual C++ standard, creating collections satisfying following rules is hard if not impossible:

  1. exception safety,
  2. cheap internal operations (in actual STL containers: the operations are copies),
  3. automatic memory management.

To satisfy (1), a collection can't store raw pointers. To satisfy (2), a collection must store raw pointers. To satisfy (3), a collection must store objects by value.

Conclusion: the three items conflict with each other.

Item (2) will not be satisfied when shared_ptrs are used because when a collection will need to move an element, it will need to make two calls: to a constructor and to a destructor. No massive, memcpy()-like copy/move operations are possible.

Am I correct that the described problem will be solved by unique_ptr and std::move()? Collections utilizing the tools will be able to satisfy all 3 conditions:

  1. When a collection will be deleted as a side effect of an exception, it will call unique_ptr's destructors. No memory leak.
    • unique_ptr does not need any extra space for reference counter; therefore its body should be exact the same size, as wrapped pointer,
    • I am not sure, but it looks like this allows to move groups of unique_ptrs by using memmove() like operations (?),
    • even if it's not possible, the std::move() operator will allow to move each unique_ptr object without making the constructor/destructor pair calls.
  2. unique_ptr will have exclusive ownership of given memory. No accidental memory leaks will be possible.

Is this true? What are other advantages of using unique_ptr?

解决方案

I agree entirely. There's at last a natural way of handling heap allocated objects.

In answer to:

I am not sure, but it looks like this allows to move groups of unique_ptrs by using memmove() like operations,

there was a proposal to allow this, but it hasn't made it into the C++11 Standard.

这篇关于unique_ptr - 主要改进?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆