首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

新手问一下容器里为什么不能保存引用?多谢

2013-09-12 
新手问一下容器里为什么不能保存引用?谢谢。vectorA& va新手请教这个为什么会报错?搜了下说是为安全考虑

新手问一下容器里为什么不能保存引用?谢谢。


vector<A&> va;

新手请教这个为什么会报错?搜了下说是为安全考虑,但是说的不是很具体。还请懂的人解答帮忙一下。谢谢。
[解决办法]
因为vector的内部机制里有指针操作,而C++标准规定,不允许使用指向引用的指针。


ISO C++11
8.3.2/5 There shall be no references to references, no arrays of references, and no pointers to references. The declaration of a reference shall contain an initializer (8.5.3) except when the declaration contains an explicit extern specifier (7.1.1), is a class member (9.2) declaration within a class definition, or is the declaration of a parameter or a return type (8.3.5); see 3.1. A reference shall be initialized to refer to a valid object or function. [ Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. —end note ]


至于你要问为什么不允许,最好还是请标准控来解答,我就不多说了...
[解决办法]
算了重发...看得清楚点

ISO C++11
8.3.2/5 There shall be no references to references, no arrays of references, and no pointers to references. The declaration of a reference shall contain an initializer (8.5.3) except when the declaration contains an explicit extern specifier (7.1.1), is a class member (9.2) declaration within a class definition, or is the declaration of a parameter or a return type (8.3.5); see 3.1. A reference shall be initialized to refer to a valid object or function. [ Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As described in 9.6, a reference cannot be bound directly to a bit-field. —end note ]


[解决办法]
也可以这样想,引用必须在声明时初始化,绑定一个对象,不存在指向为NULL的引用,所以你在声明vector<A&>本身就是声明了一个空的引用(当然我觉得我的这个这个解释有点牵强)

就好像没有 int& a[]这种指向引用的数组是一样的...vector只是一个动态的数组,原理上是相似的。标准就是这样规定的,没办法。
[解决办法]
引用是个语法糖
[解决办法]
标准如是说。。

热点排行