1
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?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
김정연
  • 47
  • 2

1 Answers1

3

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.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • Thank you for answering first. Does the reset () function not reallocate? The unique pointer address before and after the reset () call is different. Doesn't this mean that it has been reallocated? – 김정연 May 11 '20 at 18:41
  • @김정연 No. All this does is transfer ownership of the allocation that was _already_ managed by another `std::unique_ptr` object. Assigning one pointer to another pointer does not mean any allocation happens. – cdhowie May 12 '20 at 06:05