のモデルはunique_ptr
所有権の譲渡です。unique_ptr
関数からオブジェクトにを返す場合unique_ptr
、システム内の他のオブジェクトが同じオブジェクトを参照できない可能性があります。
それはあなたが望むものですか?私はそれを非常に疑っています。もちろん、生のポインタを返すだけでもかまいません。
OtherType* get_othertype(const std::string& name)
{
return otMap.find(name)->second.get();
}
したがって、クライアントはオブジェクトにアクセスできますが、マップは引き続きオブジェクトを所有します。
名前の下にエントリが見つからない場合、上記の解決策はかなり脆弱です。より良い解決策は、例外をスローするか、その場合はnullポインタを返すことです。
#include <stdexcept>
OtherType* get_othertype(const std::string& name)
{
auto it = otMap.find(name);
if (it == otMap.end()) throw std::invalid_argument("entry not found");
return it->second.get();
}
OtherType* get_othertype(const std::string& name)
{
auto it = otMap.find(name);
return (it == otMap.end()) ? 0 : it->second.get();
}
完全を期すために、参照を返すというAnthonyの提案を次に示します。
OtherType& get_othertype(const std::string& name)
{
auto it = otMap.find(name);
if (it == otMap.end()) throw std::invalid_argument("entry not found");
return *(it->second);
}
そして、これがマップ内への参照を返す方法ですがunique_ptr
、クライアントが誤って元のファイルを変更しないように、それをconstへの参照にしましょう。
unique_ptr<OtherType> const& get_othertype(const std::string& name)
{
auto it = otMap.find(name);
if (it == otMap.end()) throw std::invalid_argument("entry not found");
return it->second;
}