gpt4 book ai didi

c++ - 在 C++ 中构造对象时出现唯一指针错误

转载 作者:行者123 更新时间:2023-12-04 00:48:58 25 4
gpt4 key购买 nike

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

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

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

Account *acc_ptr = new Account(100);

为什么会这样?

最佳答案

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

你需要这个:

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

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

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

关于c++ - 在 C++ 中构造对象时出现唯一指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68260852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com