c++ - operator T&() or operator T()? -


in defining conversion operator, there advantage of defining

operator t() const; 

over

operator t&(); operator const t&() const; 

assuming i'm not concerned in potential performance gain in returning value instead of reference.

the second approach better.

with first approach calling code required make copy of returned object, expensive.

with second approach calling code has option of making or not making copy.

when responsible class/library, don't want responsible performance bottlenecks no workarounds.

one major drawback of second approach calling code be left dangling pointer/reference. in order users you'll have document how long returned references valid. users take heed , right thing.


Comments