std::unique_ptr<int> ptr;
ptr = new int[3]; // error
error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int *' (or there is no acceptable conversion)
Why this is not compiled? How can I attach native pointer to existing unique_ptr instance?
Firstly, if you need an unique array, make it
This allows the smart pointer to correctly use
delete[]to deallocate the pointer, and defines theoperator[]to mimic a normal array.Then, the
operator=is only defined for rvalue references of unique pointers and not raw pointers, and a raw pointer cannot be implicitly converted to a smart pointer, to avoid accidental assignment that breaks uniqueness. Therefore a raw pointer cannot be directly assigned to it. The correct approach is put it to the constructor:or use the
.resetfunction:or explicitly convert the raw pointer to a unique pointer:
If you can use C++14, prefer the
make_uniquefunction over usingnewat all: