##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# std::unique_ptr::swap

From cppreference.com
< cpp‎ | memory‎ | unique ptr

void swap(unique_ptr& other); |  | (since C++11)

Swaps the managed objects and associated deleters with another unique_ptr object `other`.

### [edit] Parameters

other | - | another unique_ptr object to swap the managed object and the deleter with

### [edit] Return value

(none)

### [edit] Exceptions

`noexcept` specification:
noexcept

### [edit] Example

Run this code

    #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 << std::endl;
        std::cout << "up2->val:" << up2->val << std::endl;
    }

Output:

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

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/memory/unique_ptr/swap&oldid=63351"