c++referenceconversion-operator

operator T&() or operator T()?


In defining a conversion operator, is there any advantage of defining

operator T() const;

over

operator T&();
operator const T&() const;

Assuming that I'm not concerned in potential performance gain in returning a value instead of a reference.


Solution

  • The second approach is definitely better.

    With the first approach the calling code is required to make a copy of the returned object, which could be expensive.

    With the second approach the calling code has the option of making or not making a copy.

    When you are responsible for a class/library, you don't want to be responsible for performance bottlenecks for which they are no workarounds.

    One major drawback of the second approach is that the calling code could be be left with a dangling pointer/reference. In order to help your users you'll have to clearly document how long the returned references are valid. Hopefully your users will take heed and do the right thing.