Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 553
Lingxi Avatar asked Jan 29 '16 05:01

Lingxi


People also ask

What is the use of operator T in C++?

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.

What is the difference between is and as operator in C?

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.

What is the argument to the typeof operator?

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.

What is type-testing is operator in JavaScript?

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:


2 Answers

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.

like image 105
R Sahu Avatar answered Sep 18 '22 23:09

R Sahu


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.

like image 35
Georg Avatar answered Sep 17 '22 23:09

Georg