Guillaume07 Guillaume07 - 25 days ago 7
C++ Question

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

Answer

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.