Namespaces
Variants

std::unique_ptr<T,Deleter>:: swap

From cppreference.net
Memory management library
( exposition only* )
Allocators
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Memory resources
Uninitialized storage (until C++20)
( until C++20* )
( until C++20* )
( until C++20* )

Garbage collector support (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
(C++11) (until C++23)
void swap ( unique_ptr & other ) noexcept ;
(C++11 이후)

* this 와 다른 unique_ptr 객체 other 의 관리 대상 객체와 관련된 삭제자를 교환합니다.

매개변수

other - 다른 unique_ptr 객체와 관리되는 객체 및 삭제자를 교환하기 위한 객체

반환값

(없음)

예제

#include <iostream>
#include <memory>
struct Foo
{
    Foo(int _val) : val(_val) { std::cout << "Foo...\n"; }
    ~Foo() { std::cout << "~Foo...\n"; }
    int val;
};
int main()
{
    std::unique_ptr<Foo> up1(new Foo(1));
    std::unique_ptr<Foo> up2(new Foo(2));
    up1.swap(up2);
    std::cout << "up1->val:" << up1->val << '\n';
    std::cout << "up2->val:" << up2->val << '\n';
}

출력:

Foo...
Foo...
up1->val:2
up2->val:1
~Foo...
~Foo...