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.
operator T() const volatile noexcept; Atomically loads and returns the current value of the atomic variable. Equivalent to load(). The volatile-qualified version is deprecated if std::atomic<T>::is_always_lock_free is false.
as operator: to explicitly convert an expression to a given type if its run-time type is compatible with that type The is operator checks if the run-time type of an expression result is compatible with a given type. Beginning with C# 7.0, the is operator also tests an expression result against a pattern.
The argument to the typeof operator must be the name of a type or a type parameter, as the following example shows: You can also use the typeof operator with unbound generic types. The name of an unbound generic type must contain the appropriate number of commas, which is one less than the number of type parameters.
The expression with the type-testing is operator has the following form where E is an expression that returns a value and T is the name of a type or a type parameter. E cannot be an anonymous method or a lambda expression. The is operator returns true when an expression result is non-null and any of the following conditions are true:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With