NISHIO Hirokazu[Translate]
変数=箱のたとえ
>本日の西尾家
> 僕「プログラミングで変数の概念をよく箱に例えるじゃない?」
> 妻「うん」
> 僕「でもその例えだと、箱aの中身を箱bに代入したら、その時点で箱aは空っぽになるのが自然なのでは?」
> 妻「箱ごと入れたんだよ」
> 僕「なるほど!!」

「箱aの中身を箱bに代入したら、その時点で箱aは空っぽになる」という自然な挙動をC++で再現するにはmove semanticsを使う。unique_ptrがまさにその機能を提供している。
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 }


"Engineer's way of creating knowledge" the English version of my book is now available on [Engineer's way of creating knowledge]

(C)NISHIO Hirokazu / Converted from [Scrapbox] at [Edit]