【问题标题】:Why std::unique_ptr is not compatible with assignement operator?为什么 std::unique_ptr 与赋值运算符不兼容?
【发布时间】:2021-10-28 01:05:54
【问题描述】:

例如:

std::unique_ptr<int> int_ptr = new int(10); // error: conversion from ‘int*’ to non-scalar type ‘std::unique_ptr’ requested

std::unique_ptr<int> pointer(new int(10));  // this work fine

【问题讨论】:

  • @armagedescu for shared_ptr 也会产生同样的错误。
  • @armagedescu unique_ptr 不是单身人士。您可以拥有 N 个具有 N 个唯一值的单独实例。这与单例允许的相反。
  • @armagedescu Singleton 表示全球唯一,不适用于unique_ptr。您正在考虑适用于 unique_ptr 的“唯一所有权”。
  • @armagedescu - 该链接中的问题顺便说一句,unique_ptr 是一个单身人士,但这不是问题的重点,并且没有任何 cmets 或答案解决了该断言.充其量是弱权威。习惯上,“singleton”表示全局共享的单个对象。

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


【解决方案1】:

它们都是初始化,而不是赋值。第一个是复制初始化,第二个是直接初始化。 constructor of std::unique_ptr采用原始指针标记为explicit,可以在direct initialization中使用,但不能在copy initialization中使用。

explicit unique_ptr( pointer p ) noexcept;

直接初始化比复制初始化更宽松:复制初始化只考虑非显式构造函数和非显式用户定义转换函数,而直接初始化考虑所有构造函数和所有用户定义转换函数。

【讨论】:

    猜你喜欢
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多