Guillaume07 Guillaume07 - 1 year ago 85
C++ Question

std::unique_ptr usage

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

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 ?


ok so the correct version is


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 Source

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


p1 = std::move(p2);

Have a look here for more info.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download