김정연
김정연

Reputation: 57

Questions about unique pointers

unique_ptr& operator=(unique_ptr&& _Right) noexcept {
    if (this != _STD addressof(_Right)) {
        reset(_Right.release());
        _Mypair._Get_first() = _STD forward<_Dx>(_Right._Mypair._Get_first());
    }
    return *this;
}

Why does the unique pointer move assignment operator reallocate with reset()?

Is there any reason not to do a shallow copy?

Upvotes: 1

Views: 70

Answers (1)

cdhowie
cdhowie

Reputation: 169018

You cannot copy a std::unique_ptr. That's the whole point -- it's an exclusive-ownership smart pointer. If you make a copy, you no longer have exclusive ownership.

reset() takes ownership of the raw pointer that is released from the move source by _Right.release() while also ensuring that any pointer currently owned by the assignment target is deleted first.

Note that there is no "reallocation." reset() does not perform any allocation -- it assumes ownership of the given raw pointer while potentially deallocating whatever object it owned at the time of the reset() call.

Upvotes: 3

Related Questions