変数=箱のたとえ
本日の西尾家
僕「プログラミングで変数の概念をよく箱に例えるじゃない?」
妻「うん」
僕「でもその例えだと、箱aの中身を箱bに代入したら、その時点で箱aは空っぽになるのが自然なのでは?」
妻「箱ごと入れたんだよ」
僕「なるほど!!」
Facebook
「箱aの中身を箱bに代入したら、その時点で箱aは空っぽになる」という自然な挙動をC++で再現するにはmove semanticsを使う。unique_ptrがまさにその機能を提供している。
https://wandbox.org/permlink/1Uk7XaISQatJniNt
code:cpp
#include <iostream>
struct hoge {
};
int main(){
std::unique_ptr<hoge> a;
std::cout << a << std::endl; // a is empty
a.reset(new hoge());
std::cout << a << std::endl; // a is not empty
std::unique_ptr<hoge> b;
std::cout << b << std::endl; // b is empty
b = std::move(a);
// b = a; won't work.
// error: object of type ... cannot be assigned because its copy assignment operator is implicitly deleted
// note: copy assignment operator is implicitly deleted because ... has a user-declared move constructor
std::cout << a << std::endl; // a is empty
std::cout << b << std::endl; // b is not empty
}
たとえ