考虑下面的类:投STL ::包含指向STL ::含载体常指针
class SomeInfo
{
private:
std::vector<someObj *> _myVector;
public:
const std::vector<const someObj*>& getInfoVector() const
{
return _myVector;
}
};
当我尝试用gcc 4.1.2编译,它给了我下面的错误:
error: invalid initialization of reference of type
‘const std::vector<const someObj*, std::allocator<const someObj*> >&’
from expression of type
‘const std::vector<someObj*, std::allocator<someObj*> >
如果我删除'someObj *'前的'const',然后编译,但我不想用非常量指针返回向量,因为我不想让它们引用的对象从我的SomeInfo类外部改变。在这个情况下,你会怎么做?
为什么不首先使_myVector成为常量指针的向量? – Ferruccio
因为在后面阶段,会有一个析构函数,它必须'删除'常量指针,我知道这是允许的语言,但我认为它很丑陋!从我的观点来看,const是const的,不应该被触及......这个向量成员不是这种情况,它不是const,我只是想让const访问它的值。 – pinpinokio