Search code examples
c++initializationcopy-initializationdirect-initialization

In C++, under the case `T object(other);`, is it direct initialization or copy initialization?


Assume I have this code

T object(other);

It is direct initialization or copy initialization? Based on the rule of direct initialization :

T object ( arg ); initialization with a nonempty parenthesized list of expressions

It is direct initialization.

But I saw someone said:

  • It is copy initialization when object and other is same type.
  • It is direct initialization when object and other is different type.

I don't know which is correct.


Solution

  • All forms of T object(other); are direct initialization. Direct initialization is defined in [dcl.init.general]/15 as:

    The initialization that occurs

    • for an initializer that is a parenthesized expression-list or a braced-init-list,
    • for a new-initializer ([expr.new]),
    • in a static_­cast expression ([expr.static.cast]),
    • in a functional notation type conversion ([expr.type.conv]), and
    • in the braced-init-list form of a condition

    is called direct-initialization.

    emphasis mine

    Which covers T object(other);

    Copy intialization is define in [dcl.init.general]/14 as:

    The initialization that occurs in the = form of a brace-or-equal-initializer or condition ([stmt.select]), as well as in argument passing, function return, throwing an exception ([except.throw]), handling an exception ([except.handle]), and aggregate member initialization other than by a designated-initializer-clause ([dcl.init.aggr]), is called copy-initialization.

    T object(other); is not covered so it is not copy initialization.