std::move

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

C++std::move とは、引数で与えられたオブジェクトの持つリソースを左辺へオブジェクトに移動する機能を提供します。所有権を移動します。std::moveは、C++11で追加されました。std::moveは、キャストの1つです。

読み方

std::move
えすてぃーでぃー むーぶ

概要

std::moveは、二種類の使い方があります。

#include <utility> // std::move(object)
static_cast<typename std::remove_reference<T>::type&&>(t)
 
#include <algorithm> // std::move(range)
template <class InputIterator, class OutputIterator>
  OutputIterator move (InputIterator first, InputIterator last,
  	OutputIterator result);

1つのオブジェクトを他方にmoveします。

std::string s1("hoge"), s2;
s2 = std::move(s1);

レンジを指定して、std::moveできます。

std::vector<string> v1 {"1","2","3","4","5"}, v2;
std::move(v1.begin(), v1.end(), back_inserter(v2) );

所有権を移す例

ソースコード unique_ptr_operator_equal.cpp

#include <iostream>
#include <exception>
#include <memory>
#include <utility>
 
class C {
        public:
                C() { }
                ~C() {
                        std::cout << __PRETTY_FUNCTION__ << std::endl;
                }
                void doit (){
                        std::cout << __PRETTY_FUNCTION__ << std::endl;
                }
};
 
int
main(int argc, char const* argv[])
{
        std::unique_ptr<int> foo(new int(123));
        std::unique_ptr<int> bar;
        bar     = std::move(foo);
 
        std::cout << "foo: " << foo.get() << std::endl;
        std::cout << "bar: " << bar.get() << std::endl;
        return 0;
}

コンパイル

g++49 -std=c++11 -I/usr/local/lib/gcc49/include/c++/ \
-Wl,-rpath=/usr/local/lib/gcc49  unique_ptr_operator_equal.cpp -o unique_ptr_operator_equal

実行例

% ./unique_ptr_operator_equal
foo: 0
bar: 0x28404088

レンジで移動する例

ソースコード std_move_range1.cpp

std::vector v1 から v2 に std::moveを使用して要素を移動します。 std::moveを実行した後にv1の各要素は、残っていますが、それぞれのオブジェクトは、すでに値を持っていません。

#include <iostream>
#include <vector>
#include <iterator>     // std::back_inserter
#include <algorithm>    // std::move(range)
#include <string>
using namespace std;
int main(int argc, char const* argv[])
{
        std::vector<string> v1 {"1","2","3","4","5"}, v2;
        std::move(v1.begin(), v1.end(), back_inserter(v2) );
        cout << v1.size() << endl;
        for(auto i: v1) {
                cout << "[ " << i << "] ";
        }
        cout << endl;
        cout << v2.size() << endl;
        for(auto i: v2) {
                cout << "[ " << i << "] ";
        }
        cout << endl;
        return 0;
}

コンパイル

g++49 -std=c++11 -I/usr/local/lib/gcc49/include/c++/ \
-Wl,-rpath=/usr/local/lib/gcc49  std_move_range1.cpp -o std_move_range1

実行例

% ./std_move_range1
5
[ ] [ ] [ ] [ ] [ ]
5
[ 1] [ 2] [ 3] [ 4] [ 5]

関連項目





スポンサーリンク