Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

c++ - std::unique_ptr usage

std::unique_ptr<int> p1(new int);
std::unique_ptr<int> p2(new int);
p2=p1;

It seems here that p1 is no longer "unique" since p2 refer to it also

It is legal c++ ? Does unique_ptr have copy_semantics ? If no, and if it has only move semantics, is p1 set to NULL after assign it to p2 ?

EDIT:

ok so the correct version is

 p2=std::move(p1)

According to that, after this assign, p1 is not valid ? And the difference with auto_ptr is here? it is more safe to explictly specfiy transfer of ownership than implicitly as it is the case with auto_ptr I guess

question from:https://stackoverflow.com/questions/5622764/stdunique-ptr-usage

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

std::unique_ptr is non-assignable and non-copyable. You need to use std::move();

so

p1 = std::move(p2);

Have a look here for more info.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...