2

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));
    }
user788171
  • 16,753
  • 40
  • 98
  • 125
  • 7
    You are returning by reference a temporary value. In this case your bottleneck is in atof, not in returning a copy. – Alessandro Pezzato Jan 18 '12 at 14:27
  • I agree with the note above as well but you also need to look into http://en.wikipedia.org/wiki/Copy_elision as the compiler can sometimes make better decisions then you can. – rerun Jan 18 '12 at 14:32
  • You don't need to return built-in types per reference as an optimization, they should be passed just as efficiently per copy. – sbi Jan 18 '12 at 14:55

2 Answers2

3

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];
}
Alessandro Pezzato
  • 8,603
  • 5
  • 45
  • 63
3

Here's a good article: Want Speed? Pass by Value.

Also you really need to be careful with returning by reference. References are like pointers in that you can get dangling references which aren't legally usable. The following has undefined behavior:

int const &foo() {
    return 1;
}

Also, when passing primitive types like float it's usually better to just copy them, because passing a pointer means you'll be copying a pointer instead, which is unlikely to be faster than copying the value itself. This answer has a good rule of thumb for taking parameters by reference vs. value: https://stackoverflow.com/a/1567186/365496

Another reason to pass by const & instead of by value is if making a copy could require heap memory allocations. Such copies could fail and so it's better to pass by reference to avoid that error possibility.

Community
  • 1
  • 1
bames53
  • 86,085
  • 15
  • 179
  • 244