std::unique_ptr<T,Deleter>::operator=

  1. Move assignment operator. Transfers ownership from r to *this as if by calling reset(r.release()) followed by assigning get_deleter() from std::forward(r.get_deleter()).

# Declarations

unique_ptr& operator=( unique_ptr&& r ) noexcept;

(constexpr since C++23)

template< class U, class E >
unique_ptr& operator=( unique_ptr<U, E>&& r ) noexcept;

(constexpr since C++23)

unique_ptr& operator=( std::nullptr_t ) noexcept;

(constexpr since C++23)

unique_ptr& operator=( const unique_ptr& ) = delete;

# Parameters

# Return value

*this

# Notes

As a move-only type, unique_ptr’s assignment operator only accepts rvalues arguments (e.g. the result of std::make_unique or a std::move’d unique_ptr variable).

# Example

#include <iostream>
#include <memory>
 
struct Foo
{
    int id;
    Foo(int id) : id(id) { std::cout << "Foo " << id << '\n'; }
    ~Foo() { std::cout << "~Foo " << id << '\n'; }
};
 
int main() 
{
    std::unique_ptr<Foo> p1(std::make_unique<Foo>(1));
 
    {
        std::cout << "Creating new Foo...\n";
        std::unique_ptr<Foo> p2(std::make_unique<Foo>(2));
        // p1 = p2; // Error ! can't copy unique_ptr
        p1 = std::move(p2);
        std::cout << "About to leave inner block...\n";
 
        // Foo instance will continue to live, 
        // despite p2 going out of scope
    }
 
    std::cout << "About to leave program...\n";
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 2047C++11for overload (2), get_deleter() was assigned fromstd::forward(r.get_deleter())corrected tostd::forward(r.get_deleter())
LWG 2118C++11unique_ptr<T[]>::operator=rejected qualification conversionsaccepts
LWG 2228(N4366)C++11the converting assignment operatorwas missing the assignability constraintadded the constraint
LWG 2246C++11the assignment target of the converteddeleter of r was not specifiedspecified as get_deleter()
LWG 2899C++11the move assignment operator was not constrainedconstrained