赋值运算符 - 自赋值 [英] Assignment operator - Self-assignment

查看:61
本文介绍了赋值运算符 - 自赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译器生成的赋值运算符是否会防止自赋值?

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?

不,如果您的类的所有属性(以及它们的属性)都是 POD 类型.

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.

这篇关于赋值运算符 - 自赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆