Safe to use the compiler generated assignment operator?

I'm using the CPoint class from MFC. There is no explicitly defined assignment operator or copy constructor (AFAIK). Yet, this works:

CPoint p1(1, 2), p2;
p2 = p1; // p2 now is equal to p1

I'm assuming this is working automagically because of a compiler generated assignment operator. Correct?

If so, can I be confident that this isn't doing anything unexpected? In this case CPoint is so simple I think all is well, but in general this is something that worries me a bit. Is it better form to do:

p2.SetPoint(p1.x, p2.x);

-cr


This is safe - if an assignment operator wasn't meant to be supplied then the MFC designers could have made sure it wasn't available (by making it private for example).

IIRC the compiler will perform a member-by-member copy, so for a class containing POD like this, you won't have a problem. It can get messy if you have a class that allocates memory and neglects to override operator= and perform a deep-copy.

FWIW I asked a question about what the compiler can and cannot do a while back:

Why don't C++ compilers define operator== and operator!=?

Some of the answers make for interesting reading.


Look up default copy constructor:

http://www.fredosaurus.com/notes-cpp/oop-condestructors/copyconstructors.html

This isn't a special thing about CPoint.


If a class is "simple", then the compiler-generated assignment operator will work (memberwise copy). If there are some members that would require more advanced logic (let's say the object maintains an internal pointer to what it expects is a private buffer), then the compiler-generated assignment operator will have issues. CPoint just stores an x and y coordinate of a point, so you should not run into issues.

链接地址: http://www.djcxy.com/p/73770.html

上一篇: 如何避免C ++中operator ==实现中的错误?

下一篇: 安全使用编译器生成的赋值运算符?