Is there a difference between copy initialization and direct initialization?

前端 未结 9 2669
眼角桃花
眼角桃花 2020-11-21 04:44

Suppose I have this function:

void my_test()
{
    A a1 = A_factory_func();
    A a2(A_factory_func());

    double b1 = 0.5;
    double b2(0.5);

    A c1;
         


        
9条回答
  •  甜味超标
    2020-11-21 05:15

    Of note:

    [12.2/1] Temporaries of class type are created in various contexts: ... and in some initializations (8.5).

    I.e., for copy-initialization.

    [12.8/15] When certain criteria are met, an implementation is allowed to omit the copy construction of a class object ...

    In other words, a good compiler will not create a copy for copy-initialization when it can be avoided; instead it will just call the constructor directly -- ie, just like for direct-initialization.

    In other words, copy-initialization is just like direct-initialization in most cases where understandable code has been written. Since direct-initialization potentially causes arbitrary (and therefore probably unknown) conversions, I prefer to always use copy-initialization when possible. (With the bonus that it actually looks like initialization.)

    Technical goriness: [12.2/1 cont from above] Even when the creation of the temporary object is avoided (12.8), all the semantic restrictions must be respected as if the temporary object was created.

    Glad I'm not writing a C++ compiler.

提交回复
热议问题