包含引用的STL映射不编译 [英] STL map containing references does not compile

查看:124
本文介绍了包含引用的STL映射不编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下:

std::map<int, ClassA &> test;

给出:

error C2101: '&' on constant



While the following

std::map<ClassA &, int> test;

提供

error C2528: '_First' : pointer to reference is illegal

不能包含键值的引用,因为它需要有时实例化类,并且不能在没有对象的情况下实例化引用。

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容器中存储引用是非法的,因为类型必须是copy可构建和可转让。不能分配参考。

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.

个问题可能是您感兴趣的。

This SO question might be of interest to you.

这篇关于包含引用的STL映射不编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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