gpt4 book ai didi

c++ - 编译时出现 make_unique 错误

转载 作者:太空狗 更新时间:2023-10-29 20:34:57 32 4
gpt4 key购买 nike

<分区>

刚开始学习智能指针 stl::make_unique

必须将旧代码更改为现代 c++

当我编译下面的代码行时出现以下错误(原始代码示例)

#include <memory>
#include <iostream>

using namespace std;
struct Student
{
int id;
float Score;
};
auto main()->int
{
auto Student1 = make_unique<Student>(1, 5.5);
//auto Student1 = make_unique<int>(1); //Works perfectly
//auto Student2 = unique_ptr<Student>{ new Student{1,22.5} }; //Works
cout << "working";
return 0;
}

1>------ Build started: Project: ConsoleApplication4, Configuration: Debug Win32 ------
1>Source.cpp
1>c:\program files (x86)\microsoft visual studio\2017\enterprise\vc\tools\msvc\14.10.25017\include\memory(2054): error C2661: 'Student::Student': no overloaded function takes 2 arguments
1>c:\users\hsingh\documents\visual studio 2017\projects\consoleapplication4\consoleapplication4\source.cpp(12): note: see reference to function template instantiation 'std::unique_ptr<Student,std::default_delete<_Ty>> std::make_unique<Student,int,double>(int &&,double &&)' being compiled
1> with
1> [
1> _Ty=Student
1> ]
1>Done building project "ConsoleApplication4.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

我试图查看 make_unique 实现,看起来它应该有效。查看上面的站点,可能的实现是

// note: this implementation does not disable this overload for array types
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

所以我的问题是(现在我所拥有的是直接使用 unique_ptr)

  1. 如何使用 make_unique 使其工作

  2. 我可以对 STL 中的 make_unique 实现做哪些更改以使其正常工作

经过几个回答添加问题3

3.什么是最好使用带构造函数的 make_unique 或直接使用 unique_ptr

unique_ptr<Student>{ new Student{1,22.5} }

我更喜欢后者,因为不需要定义构造函数。请提出建议

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