다음 클래스를 고려하십시오.cast stl :: stl에 대한 포인터를 포함하는 벡터 :: constant 포인터가 들어있는 벡터
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