C++ 如何为成对元素(向量和int)创建唯一的\u ptr?

C++ 如何为成对元素(向量和int)创建唯一的\u ptr?,c++,c++17,C++,C++17,我已经找过了。但找不到明确的答案。所以我提出了一个新问题。代码如下: using namespace std; using pairfortsp = pair<unique_ptr<vector<int>>, unique_ptr<int>>; int main(int argc, char *argv[]){ unique_ptr<vector<int>> tmpptr1(new vector<int&g

我已经找过了。但找不到明确的答案。所以我提出了一个新问题。代码如下:

using namespace std;

using pairfortsp = pair<unique_ptr<vector<int>>, unique_ptr<int>>;

int main(int argc, char *argv[]){
    unique_ptr<vector<int>> tmpptr1(new vector<int>{1});
    unique_ptr<int> tmpptr2(new int(1));
    unique_ptr<pairfortsp> tmpptr3(new pairfortsp<tmpptr1,tmpptr2>);
}
使用名称空间std;
使用pairfortsp=pair;
int main(int argc,char*argv[]){
唯一的_ptr tmpptr1(新向量{1});
独特的ptr tmpptr2(新的int(1));
独特的ptr tmpptr3(新配对端口SP);
}
当我编译它时,我得到了以下两个错误:

stackover.cpp:25:50: error: invalid operands to binary expression ('pairfortsp *' (aka
      'pair<unique_ptr<vector<int> >, unique_ptr<int> > *') and 'unique_ptr<vector<int> >')
    unique_ptr<pairfortsp> tmpptr3(new pairfortsp<tmpptr1,tmpptr2>);
..................
stackover.cpp:25:67: error: expected expression
    unique_ptr<pairfortsp> tmpptr3(new pairfortsp<tmpptr1,tmpptr2>);
stackover.cpp:25:50:错误:二进制表达式('pairfortsp*'(又名)的操作数无效
“pair*”和“unique_ptr”)
独特的ptr tmpptr3(新配对端口SP);
..................
stackover.cpp:25:67:错误:应为表达式
独特的ptr tmpptr3(新配对端口SP);
那么,为我声明的一对创建唯一的\u ptr的正确步骤是什么呢


谢谢。

看起来您正试图将构造函数参数作为模板参数传递给
std::pair
。也就是说,您使用的是
is而不是
()

另外,由于无法复制
unique\u ptr
,因此必须
std::move
将它们传递给构造函数

以下代码使用
g++-std=c++17 Move.cc
编译

#include <vector>
#include <memory>
#include <utility>

using namespace std;

using pairfortsp = pair<unique_ptr<vector<int>>, unique_ptr<int>>;

int main(int argc, char *argv[]){
    unique_ptr<vector<int>> tmpptr1(new vector<int>{1});
    unique_ptr<int> tmpptr2(new int(1));
    unique_ptr<pairfortsp> tmpptr3(new pairfortsp(std::move(tmpptr1),std::move(tmpptr2)));
}
#包括
#包括
#包括
使用名称空间std;
使用pairfortsp=pair;
int main(int argc,char*argv[]){
唯一的_ptr tmpptr1(新向量{1});
独特的ptr tmpptr2(新的int(1));
独特的_ptr tmpptr3(新的配对端口sp(std::move(tmpptr1),std::move(tmpptr2));
}

仔细查看
新pairfortsp
。这是什么意思?这是什么意思?这意味着我想在堆中为pairfortsp对分配一个空间。我不知道为pairfortsp分配堆空间的正确方法。我的意思是语法上的。@johnweekthird是
pairfortsp
a模板?@eerorika,它是std::pair,有两个唯一的\u ptr元素。谢谢,merlin2011。你的回答解决了我的问题。所以我犯了两个错误。首先,正如您所说,我必须std::move unique\u ptr。其次,我使用令牌来包含两个pair元素。我用了()代币。现在就没有错误了。最好使用
std::make_unique
@Slava创建它们,您是否建议对
std::make_unique
的返回值赋值?请在评论中加入您精确的代码建议。我的意思是
unique\u ptr tmpptr1=std::make_unique(1)或更好的
auto-tmpptr1=std::make_unique(1)等等on@Slava,原则上我同意你的观点,但我觉得这种毫不相关的代码修改会掩盖问题的要点。请随意添加处理这些问题的附加答案。