简体   繁体   English

分配操作员 - 自我分配

[英]Assignment operator - Self-assignment

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? 即使班级成员不是指针类型,我是否总是需要防止自我分配?

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 . 不,如果您的所有类属性(以及它们的属性)都是POD类型 ,则不会。

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 . 还要考虑复制和交换习语

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;
}
class T {
    int x;
public:
    T(int X = 0): x(X) {}
// prevent copying
private:
    T& operator=(const T&);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM