【问题标题】:why we cannot use "=" to shared_ptr or unique_ptr? [duplicate]为什么我们不能对 shared_ptr 或 unique_ptr 使用“=”? [复制]
【发布时间】:2018-05-22 10:00:25
【问题描述】:

我发现语法出现编译错误。

std::shared_ptr<int> p = new int(5);

31 41 E:\temprory (delete it if u like)\1208.cpp [Error] conversion from 'int*' to non-scalar type 'std::shared_ptr<int>' requested

不过没关系

std::shared_ptr<int> p(new int(5));

unique_ptr;

但我不知道为什么会被禁止。

【问题讨论】:

  • 构造函数标记为explicit,因此不能复制初始化

标签: c++ c++11 initialization shared-ptr unique-ptr


【解决方案1】:

std::shared_ptrstd::unique_ptr的构造函数采用原始指针是explicitstd::shared_ptr&lt;int&gt; p = new int(5);copy initialization,不考虑 explicit 构造函数。

复制初始化比直接初始化更宽松:显式构造函数不转换构造函数,也不考虑复制初始化。

对于direct initialization,考虑explicit 构造函数,然后std::shared_ptr&lt;int&gt; p(new int(5)); 工作正常。

为什么构造函数是explicit

为了防止无意的隐式转换和所有权转移。例如

void foo(std::unique_ptr<int> p) { ... }

然后

int* pi = new int(5);
foo(pi); // if implicit conversion is allowed, the ownership will be transfered to the parameter p
// then when get out of foo pi is destroyed, and can't be used again

【讨论】:

  • 我相信 OP 是在询问决定明确此构造函数的基本原理。
【解决方案2】:

C++ 不允许从原始指针复制初始化 shared_ptr,因为 shared_ptr 很容易意外地从某个任意原始指针隐式转换为 shared_ptr实际管理它。

【讨论】:

    【解决方案3】:

    想象一下,如果您不小心将一个 int * 指针传递给了一个采用 std::shared_ptr&lt;int&gt; 的函数。当函数完成时,指针将被释放。如果你真的想转让所有权,你应该明确指出。

    【讨论】:

      猜你喜欢
      • 2013-01-30
      • 2013-07-06
      • 2014-01-10
      • 1970-01-01
      • 2020-06-17
      • 2016-12-22
      • 2020-10-24
      • 1970-01-01
      • 2016-02-09
      相关资源
      最近更新 更多