Return reference to a vector member variable

后端 未结 4 1895
日久生厌
日久生厌 2021-01-30 07:05

I have a vector as member in a class and I want to return a reference to it through a getVector() function, so as to be able to modify it later. Isn’t it better practice the fun

4条回答
  •  情话喂你
    2021-01-30 07:29

    it's not unusual to declare both const and mutable variants, like so:

    std::vector& VectorHolder::getVector() {
      return myVector;
    }
    const std::vector& VectorHolder::getVector() const {
      return myVector;
    }
    

    the underlying problem with your program is that you return a non-const reference from a const method.

    std::vector& VectorHolder::getVector() const {
      return myVector; // << error: return mutable reference from const method
    }
    

    so you make it const using this form:

    const std::vector& VectorHolder::getVector() const {
      return myVector; // << ok
    }
    

    and when this is in a non const method or the client holds a non-const reference, then you can legally use a non-const method:

    std::vector& VectorHolder::getVector() {
      return myVector; // << ok
    }
    

    finally, you could return a value (in some cases):

    std::vector VectorHolder::getVector() const {
      return myVector; // << ok
    }
    

    because the copy requires no mutation and provides no exposure to the internal data.

    so you will end up declaring both variants quite often.

    the results of declaring both are:

    VectorHolder m;
    const VectorHolder c;
    
    m.getVector().size(); // << ok
    c.getVector().size(); // << ok - no mutation
    
    m.getVector().push_back(a); // << ok
    c.getVector().push_back(a); // << error: attempt to mutate const reference because the const vector is returned
    

    so it all works out nicely (apart from the redundancy of the methods).

提交回复
热议问题