Search code examples
c++performancereferencecopydeep-copy

C++ return by reference multiple times


I have been using return by reference to try to speed up my code and avoid multiple expensive copy operations.

I have an access member function that looks like this:

    std::string const& access_element(int index) const;

If I have another member function that calls access_element(), do I need to also return that by reference?

For instance.

    float const& access_element2(int index) const {
       return atof(access_element(index));
    }

versus

    float access_element2(int index) {
       return atof(access_element(index));
    }

Solution

  • You are returning by reference a temporary value. In this case your bottleneck is in atof, not in returning a copy. atof return a temporary value. If your intention is to speed up with a return by reference, you should return a member object, or a member object of a member object (like a vector item) that is returned by reference.

    float const& access_element2(int index) const {
       return elements[index];
    }