分配操作符 - 自我分配 [英] 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?
推荐答案
编译器是否生成了对自我赋值的赋值操作符? / p>
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屋!