operator T&() or operator T()?

Lingxi picture Lingxi · Jan 29, 2016 · Viewed 7k times · Source

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.

Answer

Georg picture Georg · Jan 29, 2016

I think it depends on the situation. The first approach returns a new object that can be modified w/o altering the original object. The second approach returns a reference to an existing object. If you change this object, you will also change the original object.

Which one is the right for you you have to decide; there is no general advantage.