【问题标题】:Any use for dynamically allocating std::unique_ptr?动态分配 std::unique_ptr 有什么用?
【发布时间】:2019-02-16 17:52:23
【问题描述】:

使用new 创建std::unique_ptr 有意义吗?在下面的 sn-p 中,因为我怀疑由 std::unique_ptr 管理的 SimpleClass 对象不会被销毁,除非我自己删除 std::unique_ptr。我想不出这个有用的情况,所以我想知道是否有实际使用它的情况。

  std::unique_ptr<vector_test::SimpleClass>* ptr_to_unique_ptr = new std::unique_ptr<vector_test::SimpleClass>();
  ptr_to_unique_ptr->reset(new vector_test::SimpleClass(555));
  delete ptr_to_unique_ptr;

【问题讨论】:

  • 对于指向对象的唯一指针的原始指针,我想不出一个好的用例。如果我要找到这样一个用例,我想我会尝试使用唯一指针来指向对象的唯一指针。
  • std:unique_ptr&lt;std::unique_ptr&lt;vector_test::SimpleClass&gt;&gt;怎么样?
  • 我只能认为您是否需要共享唯一指针的所有权...stackoverflow.com/questions/50831775/…
  • 我认为这可能只是被命名为滥用。 RAII 给予的每一个职业选手都会被中和。

标签: c++ c++11 smart-pointers


【解决方案1】:

使用new 创建std::unique_ptr 有意义吗?

很可能不会。

在已经使用标准 dynamic memory allocation techniques 的情况下,您会/应该回退到手动内存管理并没有明确的理由。

我想不出这有用的情况,所以我想知道是否有实际使用它的情况。

我也无法想象这种情况。

【讨论】:

  • 您的链接在 URL 的末尾缺少一个字符,但答案很好。
  • 感谢通知,已修复。
【解决方案2】:

很少使用动态分配单数指针。最接近的真实单词用例是一个单链表,我们在其中动态分配一个包含指针的类实例,以及与节点关联的一些数据。虽然,很少需要实现链表,因为它很少是数据结构的最佳选择,而且标准库已经提供了不错的链表设计。

请注意,如果我们要动态分配(智能)指针,则没有充分的理由不使用智能指针来管理该分配。

【讨论】:

  • 这种情况可以用std::weak_ptr 来概括,不是吗?
  • @πάνταῥεῖ 我不确定你在暗示什么情况。我还没有遇到过弱指针的好用处(尽管我不怀疑它们存在)。
【解决方案3】:

使用 new 创建 std::unique_ptr 有意义吗?

我想不出来。在某些情况下,当包含unique_ptr 的范围结束时,您希望防止删除通过unique_ptr 管理的对象。有几种方法可以做到这一点,而不必 new unique_ptr 本身。

一些例子:

  1. 将对象移动到不同范围内的另一个unique_ptr

    std::unique_ptr<int> p1;
    {
        std::unique_ptr<int> p2 = std::make_unique<int>( 42 );
        p1 = std::move( p2 );
        // Destructor of p2 won't delete object, because ownership was transferred.
    }
    // Scope of p2 has ended, but object is still managed by p1.
    std::cout << *p1;
    
  2. 从函数返回一个通过unique_ptr 管理的对象。

    std::unique_ptr<int> MyFun() {
        std::unique_ptr<int> p = std::make_unique<int>( 42 );
        return p;  // No explicit move required, because of RVO
    }
    
  3. Release 所有权并取回原始指针。

    std::unique_ptr<int> p = std::make_unique<int>( 42 );
    some_C_API_that_takes_ownership( p.release() );
    // Destructor of p won't delete object, because ownership was given up.
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    相关资源
    最近更新 更多