std::unique ptr::swap

提供: C++入門
移動: 案内検索
スポンサーリンク


概要

std::unique_ptrstd::unique_ptr のポインタを std::unique_ptr::swap で入れ替えることができます。 release/reset/get_deleterを利用して、マニュアルで記述するよりもはるかにシンプルに記述できます。

std::unique_ptr::swap の例

ソースコード unique_ptr_swap.cpp

#include <iostream>
#include <exception>
#include <memory>
 
int
main(int argc, char const* argv[])
{
        std::unique_ptr<int> foo(new int(123));
        std::unique_ptr<int> bar(new int(456));
 
        foo.swap(bar);
 
        std::cout << "foo: " << *foo << std::endl;      // 456
        std::cout << "bar: " << *bar << std::endl;      // 123
 
        return 0;
}

コンパイル

g++48 -std=c++11  unique_ptr_swap.cpp -o unique_ptr_swap

実行例

% ./unique_ptr_swap
foo: 456
bar: 123


関連項目




スポンサーリンク