Har*_*ngh 4 c++ stl smart-pointers
我刚开始学习智能指针 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 ==========
Run Code Online (Sandbox Code Playgroud)
我试图查看 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)...));
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是(解决现在我所拥有的是直接使用unique_ptr)
如何使用 make_unique 使其工作
我可以对 STL 中的 make_unique 实现做哪些更改以使其正常工作
几个答案后 添加问题 3
3.什么是最好使用make_unique和构造函数或直接使用unique_ptr
unique_ptr<Student>{ new Student{1,22.5} }
Run Code Online (Sandbox Code Playgroud)
我更喜欢后者,因为不需要定义构造函数。请建议
不幸的是,make_unique不执行直接列表初始化。如果您在此处查看它的描述,您将看到以下语句:
构造非数组类型 T。参数 args 传递给 T 的构造函数。如果 T 不是数组类型,则此重载仅参与重载决议。该函数等效于: unique_ptr( new T(std::forward(args)...) )
您的类没有接受两个参数的构造函数。不过,它是一个聚合,可以使用聚合初始化来构造,如第二个示例所示:
auto* p = new Student{2, 3};
Run Code Online (Sandbox Code Playgroud)
但是 make_unique 没有调用这个表单,所以这就是它失败的原因。有一个建议让它像这样工作:http : //www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4462.html