在容器中使用reference

编程入门 行业动态 更新时间:2024-10-25 23:32:44
本文介绍了在容器中使用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

本文发布于:2023-08-04 17:29:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298234.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:容器   reference

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!