使用std::reference_wrapper
容器的模板参数而不是原始指针有什么好处?这是std::vector<std::reference_wrapper<MyClass> >
对std::vector<MyClass*>
我喜欢忘记空值而不必使用指针语法,但是类型的冗长(即vector<reference_wrapper<MyClass> >
)加上调用站点使用std :: ref来包装实际引用会让我觉得它不值得.
我指的是使用std :: shared_ptr或任何其他智能指针不是一个选项的情况.
使用reference_wrapper或我目前没有考虑的任何其他因素有其他好处吗?(我认为我的问题适用于C++ 11的reference_wrapper和boost)
我在类层次结构中有一堆对象,并希望std::map
使用对这些对象的引用作为映射中的键.它似乎std::reference_wrapper
正是这需要的,但我似乎无法使它工作.到目前为止我尝试过的:
class Object { // base class of my hierarchy
// most details unimportant
public
virtual bool operator< (const Object &) const; // comparison operator
};
std::map<std::reference_wrapper<const Object>, int> table;
auto it = table.find(object);
table[object] = 42;
table[object]++
Run Code Online (Sandbox Code Playgroud)
但是,我总是从编译器中得到一些模糊的错误:
/usr/include/c++/4.5.3/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = std::reference_wrapper<const Object>]’:
/usr/include/c++/4.5.3/bits/stl_tree.h:1522:38: instantiated from ‘std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::find(const _Key&) [with _Key = std::reference_wrapper<const Object>, _Val = std::pair<const …
Run Code Online (Sandbox Code Playgroud)