默认赋值运算符检查自赋值
Default assignment operator checks for self assignment
我想知道赋值运算符的默认实现是否检查自赋值,所以这两个实现中的哪一个可以被认为最接近默认实现:
class A{
int x;
public :
...
// first one
A& operator=(const A& a){
if(this != &a) x = a.x;
return *this;
}
// second one
A& operator=(const A& a){
x = a.x;
return *this;
}
}
我搜索了 C++ 标准,但我能找到的唯一一个是 this,但没有关于此的任何内容
不,实现不检查 "self":
https://en.wikipedia.org/wiki/Assignment_operator_(C%2B%2B)
The copy assignment operator, often just called the "assignment
operator", is a special case of assignment operator where the source
(right-hand side) and destination (left-hand side) are of the same
class type.
It is one of the special member functions, which means
that a default version of it is generated automatically by the
compiler if the programmer does not declare one.
The default version
performs a memberwise copy, where each member is copied by its own
copy assignment operator (which may also be programmer-declared or
compiler-generated).
赋值运算符不检查自赋值。因此,您的第二个实现最接近默认实现。
我在标准中看不到关于任何此类优化的任何文字,如果我的 class 的属性在某些情况下不会由编译器生成的运算符分配,那将很奇怪。想象一些属性分配是用户定义的并且执行一些不常见的任务。编译器不知道这一点,即使我为自己分配了一个对象,IMO 也应该调用它们。
我想知道赋值运算符的默认实现是否检查自赋值,所以这两个实现中的哪一个可以被认为最接近默认实现:
class A{
int x;
public :
...
// first one
A& operator=(const A& a){
if(this != &a) x = a.x;
return *this;
}
// second one
A& operator=(const A& a){
x = a.x;
return *this;
}
}
我搜索了 C++ 标准,但我能找到的唯一一个是 this,但没有关于此的任何内容
不,实现不检查 "self":
https://en.wikipedia.org/wiki/Assignment_operator_(C%2B%2B)
The copy assignment operator, often just called the "assignment operator", is a special case of assignment operator where the source (right-hand side) and destination (left-hand side) are of the same class type.
It is one of the special member functions, which means that a default version of it is generated automatically by the compiler if the programmer does not declare one.
The default version performs a memberwise copy, where each member is copied by its own copy assignment operator (which may also be programmer-declared or compiler-generated).
赋值运算符不检查自赋值。因此,您的第二个实现最接近默认实现。
我在标准中看不到关于任何此类优化的任何文字,如果我的 class 的属性在某些情况下不会由编译器生成的运算符分配,那将很奇怪。想象一些属性分配是用户定义的并且执行一些不常见的任务。编译器不知道这一点,即使我为自己分配了一个对象,IMO 也应该调用它们。