Why is the assignment operator not called in this case in favor of the copy constructor?

前端 未结 2 762
名媛妹妹
名媛妹妹 2020-12-20 03:09

From the wikipedia page for copy constructors:

X a = X();     

// valid given X(const X& copy_from_me) but not valid given X(X& copy_from_me)
// bec         


        
相关标签:
2条回答
  • 2020-12-20 03:34

    It's simply a matter of understanding the grammar of C++. The statement X a = X(); is a declaration statement with initializer, and not an assignment expression. The grammatical meaning of this statement is to declare a variable a of type X and copy-initialize it from the expression X(). There is no assign­ment involved here in any way.

    0 讨论(0)
  • 2020-12-20 03:56

    Because the code is constructing an object. The = sign here is initializing, not assigning. You can only assign to an existing object, not to one that's under construction.

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