在容器中使用reference_wrapper而不是原始指针的好处? [英] Benefits of using reference_wrapper instead of raw pointer in containers?

查看:265
本文介绍了在容器中使用reference_wrapper而不是原始指针的好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 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_wrapper而不是原始指针的好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆