I have a quick question regarding const-correctness for getters of vector of non-pointers.
Basically, I have this class with a non-const getter and a const getter for m_Vertices:
class Mesh
{
public:
std::vector<Vertex>& GetVertices() { return m_Vertices; }
const std::vector<Vertex>& GetVertices() const { return m_Vertices; }
private:
std::vector<Vertex> m_Vertices;
}
The non-const getter makes sense; the getter is non-const, we return a non-const reference to a vector of non-const Vertex instances.
The const getter in the other hand doesn't makes sense to me. I'm questioning the const-correctness and whether I should just return a copy of the vector. The problem I see is that we return a const reference to a vector of non-const Vertex instances. So, the callee will have a const reference to m_Vertices, but will still be able to modify the Vertex instances, which feels wrong to me in terms of const-correctness.
In that case, should I simply return a copy of m_Vertices?
Vertexinstances" Will it?std::vectordoesn't work the way you thinkconst std::vectordoes not allow to modify its elements so your assumption is incorrect.m_Vertices, those invariants would be at the mercy of whatever manipulations the users of theGetVerticesdo to the member variable... why even bother to make itprivate:in the first place? Perhaps it has no preconditions/postconditions, and the class has no invariants...?GetVerticesis called would create a big overhead in big scenes. Also, I haven't identified pre-conditions/post-conditions nor invariants for the class. Truth be told, I'm not doing contract programming anyway.