Consider the following class:
class SomeInfo
{
private:
std::vector<someObj *> _myVector;
public:
const std::vector<const someObj*>& getInfoVector() const
{
return _myVector;
}
};
When I try to compile with gcc 4.1.2, it gives me the following error:
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*> >
If I remove the ‘const’ in front of ‘someObj *’, then it compiles, but I don’t want to return vector with non-constant pointers, because I don’t want the objects referenced by them to be changed from outside my SomeInfo class. What would you do in this situation?
What I would do in this situation is forget about returning a
vector(or reference thereto). The caller can’t make any changes, so doesn’t need to see any particular container. Other answers explain why you can’t refer to your vector as if it were a vector ofconst someObj*. For that matter, if in future you change your class to use adequeinstead of avectoryou can’t return a reference to that as if it were a vector either. Since callers just need access to the elements, let’s give them that:const_info_iteratoris a typedef to a class that’s slightly annoying to write. It has to wrap astd::vector<someObj *>::const_iteratorand const-ify the type ofoperator*.boost::transform_iteratormight be useful, or it’s not all that bad to write from scratch. Bidirectional iterators do require the most operator overloads, though.Now, if the caller really wants a vector of
const someObj*, then using my interface they can easily get a snapshot at any particular moment:What they can’t have is a
vectorthat continually reflects changes made to some othervectorof a different type somewhere else —std::vectorjust doesn’t do that.