简体   繁体   中英

Is there a difference between these two conversion methods?

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.

Version 1 and 2 are called copy initialization (form 1) and direct initialization (form 3), respectively. The difference depends on the relationship between T and S .

The effects on the return statement, which performs copy initialization (form 4), depend on the nature of S . The difference is that s is an l-value while S(t) is an r-value. Copy elision may also apply here. For class types, this may make a difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM