开发者

why isn't assignment operator called here?

开发者 https://www.devze.com 2023-03-31 21:38 出处:网络
Edit: sorry I used \"assignment constructor\" instead of \"assignment operator\" in my original post. Fixed now.

Edit: sorry I used "assignment constructor" instead of "assignment operator" in my original post. Fixed now.

It turns out that the copy constructor is called instead of the assignment operator in the following code. Anyone can tell me the reason behind this? Thank you.

class A

{
int i;
public:
A(int ii) { i = ii; }
A(const A&a开发者_运维问答mp; a) { i = a.i; i++; }
A& operator=(const A& a) { i = a.i; i--; }
};
int main(void)
{
A a(4);
A b = a;
return 0;
}


A a(4);
A b = a;

None of them is assignment1. Both are initialization.

First one is called direct-initialization, and second one is called copy-initialization.

The difference between them is that first one would work even if the copy-constructor is inaccessible (i.e its either private or protected), and second one would NOT work if the copy-constructor is inaccessible.

Even though the second one requires the copy-constructor to be accessible, that doesn't mean that the copy-constructor will necessarily be called. The compiler is allowed to optimize this, and so can elide the call to copy-constructor altogether. An accessible copy-constructor is needed for semantic validation.

See these topics :

  • Is there a difference in C++ between copy initialization and direct initialization?
  • When should you use direct initialization and when copy initialization?
  • c++ copy initialization & direct initialization, the weird case

1. And there is nothing such a thing called "assignment constructor".


operator= is not an "assignment constructor", it is an "assignment operator".

When you initialize a variable in its definition (as in A b = a), it is by definition equivalent to calling the copy constructor. ie, A b(a); and A b = a; are exactly equivalent.

0

精彩评论

暂无评论...
验证码 换一张
取 消