Assignment operator - Self-assignment

China☆狼群 提交于 2019-12-30 08:00:19

问题


Does the compiler generated assignment operator guard against self assignment?

class T {

   int x;
public:
   T(int X = 0): x(X) {}
};

int main()
{
   T a(1);
   a = a;
}

Do I always need to protect against self-assignment even when the class members aren't of pointer type?


回答1:


Does the compiler generated assignment operator guard against self assignment?

No, it does not. It merely performs a member-wise copy, where each member is copied by its own assignment operator (which may also be programmer-declared or compiler-generated).

Do I always need to protect against self-assignment even when the class members aren't of pointer type?

No, you do not if all of your class's attributes (and therefore theirs) are POD-types.

When writing your own assignment operators you may wish to check for self-assignment if you want to future-proof your class, even if they don't contain any pointers, et cetera. Also consider the copy-and-swap idiom.




回答2:


This is an easy one to check empirically:

#include <iostream>
struct A {
  void operator=(const A& rhs) {
    if(this==&rhs) std::cout << "Self-assigned\n";
  }
};

struct B {
  A a;
};

int main()
{
  B b;
  b = b;
}



回答3:


class T {
    int x;
public:
    T(int X = 0): x(X) {}
// prevent copying
private:
    T& operator=(const T&);
};


来源:https://stackoverflow.com/questions/5608556/assignment-operator-self-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!