my_*_*ion 2 c++ unique-ptr c++11
这是我的代码:
typedef map<string, unique_ptr<MyClass> > DB;
const unique_ptr<MyClass>>& find_it(const string &key, const DB &db)
{
auto itr = db.find(key);
if (itr == db.end()) {
return nullptr;
}
return itr->second;
}
Run Code Online (Sandbox Code Playgroud)
返回语句会导致编译器警告: returning reference to local temporary object [-Wreturn-stack-address].
是的,我可以理解返回对本地临时变量的引用是不好的,但我想知道这里最简单的修复是什么,给出以下内容:
1. Do not expose the map to the callers of find_it (I use typedef here is just for asking this question, in real code it is wrapped inside an interface).
2. Using an iterator kind of thing to indicate the position of the searched item is a hassle to me, I like to avoid it.
Run Code Online (Sandbox Code Playgroud)
鉴于这些,我能提出的最好的方法是将find_it()分解为2个函数:
bool exists(const string &key, const DB &db)
{
auto itr = db.find(key);
return itr != db.end();
}
const unique_ptr<MyClass>>& find_it(const string &key, const DB &db)
{
auto itr = db.find(key);
assert(itr != db.end());
return itr->second;
}
Run Code Online (Sandbox Code Playgroud)
有什么建议?
该return nullptr语句隐式构造一个unique_ptr<MyClass>实例,然后您返回对它的引用,因此警告.一个简单的解决方法是定义一个static unique_ptr<MyClass>保存nullptr并返回对它的引用.
const unique_ptr<MyClass>& find_it(const string &key, const DB &db)
{
static unique_ptr<MyClass> not_found;
auto itr = db.find(key);
if (itr == db.end()) {
return not_found;
}
return itr->second;
}
Run Code Online (Sandbox Code Playgroud)
一个更好的解决方案可能是使用boost::optional.将返回类型更改为boost::optional<std::unique_ptr<MyClass>> const&,然后boost::none在未找到对象时返回.