Yokohama6 epi
- 2. わんくま同盟 横浜勉強会 #06
C++ は むずかしいややこしい
class Foo;
void f(Foo x); ← 値 (C)
void f(Foo* x); ← ポインタ (C)
void f(Foo& x); ← 参照 (C++)
...こんだけでも十分ややこしいのに
void f(Foo&& x); ← 右辺値参照(C++11 NEW)
- 4. わんくま同盟 横浜勉強会 #06
move semantics
y = x; は、
フツーなら “x を y に copy” だけど
x が右辺値なら
右辺を copy の後 廃棄するんだから
意味的には move だよね。
copy+廃棄 コスト > move コスト なら
move の方がお得よね♪
- 5. わんくま同盟 横浜勉強会 #06
copy より move がお得な典型例
template<typename T>
class novice_vector {
private:
T* data_; // Tの列
size_t size_; // 要素数
size_t capacity_; // 容量
…
};
あいうえお
よくある
コンテナ/コレクション
- 6. わんくま同盟 横浜勉強会 #06
copy ctor
novice_vector(const novice_vector& other)
: size_(other.size_), capacity_(other.capacity_) {
// 領域を確保して
data_ = new T[capacity_];
// 引数からcopyする
for ( size_t i = 0; i < size_; ++i ) {
data_[i] = other.data_[i];
}
}
- 7. わんくま同盟 横浜勉強会 #06
copy operator ‘=‘
novice_vector& operator=(const novice_vector& other) {
// 現data_を廃棄し
delete[] data_;
// 新たに領域を確保して
data_ = new T[other.cpacity_];
// 右辺からcopyする
for ( size_t i = 0; i < other.size_; ++i ) {
data_[i] = other.data_[i];
}
size_ = other.size_;
capacity_ = other_.capacity_;
return *this;
}
- 10. わんくま同盟 横浜勉強会 #06
move ctor
novice_vector(novice_vector&& other)
// 右辺のナカミをもらって
: size_(other.size_), capacity_(other.capacity_) {
data_ = other.data_;
// 右辺側は空にする
other.data_ = nullptr;
other.size_ = 0;
other.capacity_ = 0;
}
- 11. わんくま同盟 横浜勉強会 #06
move operator ‘=‘
novice_vector& operator=(novice_vector&& other) {
// 右辺のナカミをもらって
size_ = other.size_;
capacity_ = other.capacity_;
data_ = other.data_;
// 右辺側は空にする
other.data_ = nullptr;
other.size_ = 0;
other.capacity_ = 0;
return *this;
}