map から map へ要素を移動するのに、unique_ptr を使いたかったが、当時使っていた VC++ 2010 か 20151 では、コンパイルエラーになってしまった。 その時は結局、shared_ptr を使って回避した。
今、gcc 11.2.0 で試してみると問題は再現しない。コンパイラの不具合でよかったのだろうか (もう手元には VC++ がないので、検証できない)
#include <iostream> #include <map> #include <memory> #include <string> struct Hoge { std::string value; Hoge(); ~Hoge(); }; Hoge::Hoge(){ std::cout << "ctor called." << std::endl; } Hoge::~Hoge(){ std::cout << "dtor called." << std::endl; } int main(){ std::map<int,std::unique_ptr<Hoge>> src; std::map<int,std::unique_ptr<Hoge>> dst; std::unique_ptr<Hoge> p(new Hoge); p->value = "ahaha"; src[1] = std::move(p); dst[2] = std::move(src[1]); src.erase(1); for(auto p=dst.begin() ; p != dst.end() ; p++){ std::cout << "dst[" << p->first << "]= " << p->second->value << std::endl; } return 0; }
$ g++ unique.cpp $ a ctor called. dst[2]= ahaha dtor called.
- どっちだったか、ちょっと覚えていない↩