I have to work with some heavily templated code which I am trying to decipher.
I see two different constructs and I am not sure if I am missing something. Here is a simplified example of these type conversions which are used at some places, is there a difference between the following statements?
template<typename T, typename S> S my_function(T t)
{
// version 1:
S s = t
return s;
// version 2:
return S(t);
}
I am thinking to changing everything to one style, are the two statements 100% equivalent and if not, what are the differences?
No, they are not 100% equivalent!
For the simple case (c++11 and beyond), considering the return statement with type class S then the difference are:
If S has move operators then they are used when returning the value, otherwise the copy operators are used. Also note that if those operators are private or deleted then version 1 will not compile.
For version 2 s is created (with a constructor, or user defined operator) and returned directly because of RVO
Now for the complicated case, there are other things to consider; First version uses copy initialization and second is direct initialization. There are also user defined operators and explicit keyword that can alter the behavior.
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