其他分享
首页 > 其他分享> > c – 编译时make_unique错误

c – 编译时make_unique错误

作者:互联网

参见英文答案 > using c++ aggregate initialization in std::make_shared                                    1个
我刚刚开始学习智能指针
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)

>如何使用make_unique使其工作
>我可以对STL中的make_unique实现进行哪些更改以使其正常工作

经过几个答案
补充问题3

3.使用make_unique和构造函数或者直接使用unique_ptr最好

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

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

解决方法:

不幸的是,make_unique不执行直接列表初始化.如果您查看它的描述here,您将看到以下声明:

Constructs a non-array type T. The arguments args are passed to the
constructor of T. This overload only participates in overload
resolution if T is not an array type. The function is equivalent to:
unique_ptr(new T(std::forward(args)…))

您的类没有接受两个参数的构造函数.但它是一个聚合,可以使用聚合初始化来构造,如第二个示例所示:

auto* p = new Student{2, 3};

但是make_unique并没有调用这种形式,所以这就是它失败的原因.有人建议让它像这样工作:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4462.html

标签:c,smart-pointers,stl
来源: https://codeday.me/bug/20190828/1751069.html