gpt4 book ai didi

c++ - 默认赋值运算符检查自赋值

转载 作者:行者123 更新时间:2023-12-01 18:06:01 27 4
gpt4 key购买 nike

我想知道赋值运算符的默认实现是否检查自赋值,因此这两个实现中哪一个可以被认为最接近默认实现:

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).

关于c++ - 默认赋值运算符检查自赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60289563/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com