使用 std :: reference_wrapper 作为容器的模板参数而不是原始指针有什么好处?这是 std :: vector< std :: reference_wrapper< MyClass> > 与 std :: vector< MyClass *>
What benefits has using std::reference_wrapper as template parameter of containers instead of raw pointers? That is std::vector<std::reference_wrapper<MyClass> > vs. std::vector<MyClass*>
忽略了null并且不必使用指针语法,而是类型的冗余(即 vector< reference_wrapper< MyClass>> )加上调用站点使用std ::
I like forgetting about nulls and not having to use pointer syntax, but the verbosity of the types (i.e. vector<reference_wrapper<MyClass> >) plus having the call site use std::ref to wrap the actual reference makes me think it is not worth it.
我指的是使用std :: shared_ptr或任何其他智能指针的情况下不是一个选项。
I am referring to cases in which using std::shared_ptr or any other smart pointer is not an option.
使用reference_wrapper还是其他因素,我目前没有考虑到吗? (我想我的问题适用于C ++ 11的reference_wrapper和boost的)
Are there other benefits of using reference_wrapper or any other factors I am currently not taking into account? (I think my question applies to both C++11's reference_wrapper and boost's)
推荐答案我不认为有任何技术差异。参考包装器提供了基本的指针功能,包括动态改变目标的能力。
I don't think there is any technical difference. Reference wrapper provides basic pointer functionality, including the ability to change the target dynamically.
一个好处是它演示了intent。它告诉读取代码的人是谁谁有变量,实际上并不控制其寿命。用户没有忘记删除或新的东西,有些人可能开始寻找,当他们看到指针语义。
One benefit is that it demonstrates intent. It tells people who read the code that "whoever" has the variable, isn't actually controlling its lifespan. The user hasn't forgotten to delete or new anything, which some people may start to look for when they see pointer semantics.
更多推荐
在容器中使用reference
发布评论