Why is the copy-constructor not called when returning by-value a list-initialized object?

后端 未结 1 674
伪装坚强ぢ
伪装坚强ぢ 2021-02-09 05:04

I understand that when objects are returned by-value from a function, their copy-constructors are called. If a class has a deleted copy-constructor, returning by value will fail

1条回答
  •  误落风尘
    2021-02-09 06:03

    And I read somewhere on a SO post that this [...] is the same as [...]

    They were wrong. They're similar, but not the same.

    By using the braced-init-list, you are able to initialize the return value in-place. If you create a temporary, then what you're doing is creating the temporary and then copying it into the return value. Any compiler worth its salt will elide it, but the copy constructor still must be accessible.

    But since the braced-init-list initializes the return value in-place, you don't need access to the copy constructor.

    From the standard, section 6.6.3, p2:

    A return statement with a braced-init-list initializes the object or reference to be returned from the function by copy-list-initialization (8.5.4) from the specified initializer list.

    Note that "copy-list-initialization" is not similar to "copy-initialization"; it doesn't do any copying and therefore it doesn't require an accessible copy constructor. The only difference between "copy-list-initialization" and "direct-list-initialization" is that the former will choke on explicit constructors.

    0 讨论(0)
提交回复
热议问题