包含引用的 STL 映射无法编译
以下内容:
std::map<int, ClassA &> test;
给出:
error C2101: '&' on constant
虽然下面
std::map<ClassA &, int> test;
给予
error C2528: '_First' : pointer to reference is illegal
后者似乎 map 不能包含键值的引用,因为它有时需要实例化类,并且没有对象就无法实例化引用.但是为什么第一种情况不起作用?
The latter seems like map cannot contain a reference for the key value, since it needs to instantiate the class sometimes and a reference cannot be instantiated without an object. But why does the first case not work?
推荐答案
在 stl 容器中存储引用是非法的,因为类型必须是可复制构造和可分配的.无法分配引用.
It is illegal to store references in an stl container, because types must be copy constructible and assignable. References can not be assigned.
究竟是什么操作导致第一个错误取决于实现,但我认为它与创建引用有关,而不是立即分配它.第二条错误消息看起来实际上与构建地图索引有关.
Exactly what operation causes the first error is implementation dependent, but I image that it is related to creating a reference and not assigning it immediately. The second error message looks like its actually related to building the map index.
如果您的类型很小,您可以将其复制到映射中,或者如果它很大,请考虑使用指针,但请记住,容器不会为您释放对象,您必须自己明确地执行此操作.
If your type is small, you can copy it into the map, or if it is large consider using pointers instead, but remember that the container will not deallocate the objects for you, you'll have to do that explicitly yourself.
这个 SO 问题您可能会感兴趣.
This SO question might be of interest to you.
相关文章