operator T&() or operator T()?

10.6k Views Asked by At

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.

2

There are 2 best solutions below

2
On BEST ANSWER

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.

3
On

I think it depends on the situation. The first approach returns a new object that can be modified without 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 to decide; there is no general advantage.