Return reference to a vector member variable

后端 未结 4 1896
日久生厌
日久生厌 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-30 07:33

    The function getVector can be declared as const. It returns a reference that can be modified, so while the actual function doesn't modify anything in the class, the caller will be able to modify internal data.

    Declare it as:

    std::vector& getVector();
    

    If you want a function to return a vector that can't be modified, the use the const modifier on both the vector and the function:

    const std::vector& getVector() const;
    

提交回复
热议问题