简体   繁体   English

构造一对unique_ptr <int> 和诠释

[英]Construct pair of unique_ptr<int> and int

I'm trying to create a pair of int and a unique_ptr. 我正在尝试创建一对int和unique_ptr。 How should I use make_pair to create this ? 我应该如何使用make_pair创建它?

#include <string>
#include <memory>
#include <algorithm>

int main()
{
    std::unique_ptr<int> p = std::make_unique<int>(0);
    std::pair<int, std::unique_ptr<int>> pr = std::make_pair((int)0, p);
}

I run into the following issue, 我遇到了以下问题,

Error   C2440   '<function-style-cast>': cannot convert from 'initializer list' to '_Mypair'    templpairuniqueptr  c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.15.26726\include\utility 405 

I could not understand why this happens. 我不明白为什么会这样。 I'm on MSVC. 我正在使用MSVC。

You cannot copy unique pointers. 您不能复制唯一的指针。 After all, the copy would not be unique. 毕竟,副本不是唯一的。 Move instead: 改为移动:

auto pr = std::make_pair(
    0, std::make_unique<int>(0)
);

You can move from lvalues as well, if you need to, by converting the lvalue to an rvalue with std::move : 如果需要,您也可以从左值std::move ,方法是使用std::move将左值转换为右值:

auto pr = std::make_pair(
    0, std::move(p)
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM