简体   繁体   English

如何为一对中的哪些元素(向量和整数)也是unique_ptr创建unique_ptr?

[英]How to create unique_ptr for pair which elements(vector and int) are also unique_ptr?

I have searched. 我已经搜寻了。 but can't find a clear answer. 但找不到明确的答案。 So I created a new question. 因此,我提出了一个新问题。 The codes are as below: 代码如下:

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>);
}

When i compiled it, I got following two errors: 当我编译它时,出现以下两个错误:

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>);

So what is the correct steps to create unique_ptr for the pair like the one I declared? 那么,为像我声明的那对创建unique_ptr的正确步骤是什么?

Thanks. 谢谢。

It looks like you are trying to pass constructor arguments to std::pair as template parameters. 似乎您正在尝试将构造函数参数传递给std::pair作为模板参数。 That is, you were using < > is instead of ( ) . 也就是说,您使用的是< >而不是( )

Also, since unique_ptr cannot be copied, you must std::move them to pass them to the constructor. 另外,由于unique_ptr无法复制,因此必须std::move它们传递给构造函数。

The following code compiles with g++ -std=c++17 Move.cc . 以下代码使用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)));
}

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

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