johnweekthird
johnweekthird

Reputation: 3

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?

Thanks.

Upvotes: 0

Views: 145

Answers (1)

merlin2011
merlin2011

Reputation: 75555

It looks like you are trying to pass constructor arguments to std::pair as template parameters. 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.

The following code compiles with 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)));
}

Upvotes: 1

Related Questions