【发布时间】:2013-03-02 19:29:12
【问题描述】:
为什么我不能引用包含对象引用的 std::vector?以下代码在 Visual C++ 2010 中生成编译错误:
void Map::Filter( Object::Type type, std::vector<Object&>& list )
{
for ( register int y = 0; y < MAP_H; y++ )
for ( register int x = 0; x < MAP_W; x++ ) {
if ( under[y][x].GetType() == type )
list.push_back(under[y][x]);
if ( above[y][x].GetType() == type )
list.push_back(above[y][x]);
}
}
汇总编译错误:
c:\program files\microsoft visual studio 10.0\vc\include\xmemory(137): error C2528: 'pointer' : pointer to reference is illegal
c:\program files\microsoft visual studio 10.0\vc\include\vector(421) : see reference to class template instantiation 'std::allocator<_Ty>' being compiled
我通过从“对象引用向量”切换到“对象指针向量”解决了这个问题。我只是不明白为什么我不能引用引用向量。
【问题讨论】:
-
引用必须在声明时初始化;指针没有。
-
为什么是
std::vector<Object&>而不是简单的std::vector<Object>? -
简短的回答是“因为标准是这样说的”。如果你真的想要,你可以创建一个
reference_wrapper的向量 -
是的,vector
-
如果您对标准中涉及参考规则的部分感兴趣,请参阅 C++11 § 8.3.2,特别是第 5 段:"没有对引用的引用,没有引用数组,也没有指向引用的指针。引用的声明应包含一个初始化程序(8.5.3),除非声明包含显式的外部说明符(7.1.1),是类成员( 9.2) 类定义中的声明,或者是参数或返回类型的声明 (8.3.5);参见 3.1。应初始化引用以引用有效的对象或函数。"
标签: c++ visual-studio-2010 vector stl reference