【问题标题】:Unique pointer error while object construction in C++在 C++ 中构造对象时出现唯一指针错误
【发布时间】:2021-07-05 18:47:48
【问题描述】:

使用 unique_ptr 创建对象时出现错误,如下所示 错误:从 Account * 到非标量类型 std::unique_ptr 的错误转换

std::unique_ptr <Account> acc_ptr = new Account(100);

如果我使用如下原始指针,则没有错误

Account *acc_ptr = new Account(100);

为什么会这样?

【问题讨论】:

  • 相关(/重复?):stackoverflow.com/questions/11367933/…。如果第一个可以编译,那么void foo(std::unique_ptr&lt;int&gt;){} int x; foo(&amp;x); 也可以编译,那会很糟糕。

标签: c++ unique-ptr


【解决方案1】:

采用指针的std::unique_ptr 构造函数是explicit

你需要这个:

std::unique_ptr <Account> acc_ptr(new Account(100));

或者,从 C++14 开始,使用更好的std::make_unique 版本:

auto acc_ptr = std::make_unique<Account>(100);

【讨论】:

    猜你喜欢
    • 2015-06-24
    • 2017-07-03
    • 1970-01-01
    • 2013-03-07
    • 2021-04-27
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多