Is there a difference between copy initialization and direct initialization?

前端 未结 9 2438
眼角桃花
眼角桃花 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条回答
  •  猫巷女王i
    2020-11-21 04:55

    Answering with respect to this part:

    A c2 = A(); A c3(A());

    Since most of the answers are pre-c++11 I am adding what c++11 has to say about this:

    A simple-type-specifier (7.1.6.2) or typename-specifier (14.6) followed by a parenthesized expression-list constructs a value of the specified type given the expression list. If the expression list is a single expression, the type conversion expression is equivalent (in definedness, and if defined in meaning) to the corresponding cast expression (5.4). If the type specified is a class type, the class type shall be complete. If the expression list specifies more than a single value, the type shall be a class with a suitably declared constructor (8.5, 12.1), and the expression T(x1, x2, ...) is equivalent in effect to the declaration T t(x1, x2, ...); for some invented temporary variable t, with the result being the value of t as a prvalue.

    So optimization or not they are equivalent as per the standard. Note that this is in accordance with what other answers have mentioned. Just quoting what the standard has to say for sake of correctness.

提交回复
热议问题