Why does storing references (not pointers) in containers in C++ not work?(为什么在 C++ 中的容器中存储引用(而不是指针)不起作用?)
问题描述
在我的程序中,我有一个 STL 集.
In my program I have a STL set.
set<string> myStrings;
为了提高我的代码的效率,我将它改为持有,只有指针.(我不需要存储实际的字符串副本.)
To improve the efficiency of my code I changed it to hold, only pointers. (I don't need actual string copies to be stored.)
set<string*> myStrings;
我已经读到,在可能的情况下用引用替换指针是一个很好的做法.(当然,仅当不需要指针的实际功能时.)
I have read that it is a good practice to substitute pointers with references when possible. (Of course, only if the actual functionality of a pointer is not needed.)
set<string&> myStrings;
不过,后者给了我很多编译器错误.为什么不能使用引用作为容器元素?
The latter one gives me a lot of compiler errors, though. Why is it not possible to use references as container elements?
推荐答案
容器存储对象.引用不是对象.
Containers store objects. References are not objects.
C++11 规范明确规定 (§23.2.1[container.requirements.general]/1):
The C++11 specification clearly states (§23.2.1[container.requirements.general]/1):
容器是存储其他对象的对象.
Containers are objects that store other objects.
这篇关于为什么在 C++ 中的容器中存储引用(而不是指针)不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在 C++ 中的容器中存储引用(而不是指针)不起作用?
基础教程推荐
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- c++ STL设置差异 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
