为什么某些 class 方法 return “*this”(自身的对象引用)?
Why do some class methods return "*this" (object reference of self)?
互联网上(也特别是这里,在 Whosebug 上)有很多代码可以解释 return *this
。
例如来自 post Copy constructor and = operator overload in C++: is a common function possible? :
MyClass& MyClass::operator=(const MyClass& other)
{
MyClass tmp(other);
swap(tmp);
return *this;
}
当我把 swap 写成:
void MyClass::swap( MyClass &tmp )
{
// some code modifying *this i.e. copying some array of tmp into array of *this
}
将 operator =
的 return 值设置为 void
并避免 returning *this
还不够吗?
这个习惯用法的存在是为了实现函数调用的链接:
int a, b, c;
a = b = c = 0;
这适用于 int
s,因此没有必要让它不适用于用户定义的类型:)
流运算符类似:
std::cout << "Hello, " << name << std::endl;
与
工作方式相同
std::cout << "Hello, ";
std::cout << name;
std::cout << std::endl;
由于 return *this
习惯用法,可以像第一个示例一样链接。
返回 *this
的原因之一是允许像 a = b = c;
这样的赋值链,它等同于 b = c; a = b;
。一般来说,赋值结果可以在任何地方使用,例如在调用函数 (f(a = b)
) 或表达式 (a = (b = c * 5) * 10
) 时。虽然,在大多数情况下,它只会让代码变得更复杂。
你 return *this
当有强烈的感觉你将对对象调用相同的操作时。
例如,std::basic_string::append
return 本身,因为有一种强烈的感觉,你会想要附加另一个字符串
str.append("I have ").append(std::to_string(myMoney)).append(" dollars");
operator =
也是如此
myObj1 = myObj2 = myObj3
swap
没有这么强烈的感觉。表达式 obj.swap(other).swap(rhs)
看起来很常见吗?
互联网上(也特别是这里,在 Whosebug 上)有很多代码可以解释 return *this
。
例如来自 post Copy constructor and = operator overload in C++: is a common function possible? :
MyClass& MyClass::operator=(const MyClass& other)
{
MyClass tmp(other);
swap(tmp);
return *this;
}
当我把 swap 写成:
void MyClass::swap( MyClass &tmp )
{
// some code modifying *this i.e. copying some array of tmp into array of *this
}
将 operator =
的 return 值设置为 void
并避免 returning *this
还不够吗?
这个习惯用法的存在是为了实现函数调用的链接:
int a, b, c;
a = b = c = 0;
这适用于 int
s,因此没有必要让它不适用于用户定义的类型:)
流运算符类似:
std::cout << "Hello, " << name << std::endl;
与
工作方式相同std::cout << "Hello, ";
std::cout << name;
std::cout << std::endl;
由于 return *this
习惯用法,可以像第一个示例一样链接。
返回 *this
的原因之一是允许像 a = b = c;
这样的赋值链,它等同于 b = c; a = b;
。一般来说,赋值结果可以在任何地方使用,例如在调用函数 (f(a = b)
) 或表达式 (a = (b = c * 5) * 10
) 时。虽然,在大多数情况下,它只会让代码变得更复杂。
你 return *this
当有强烈的感觉你将对对象调用相同的操作时。
例如,std::basic_string::append
return 本身,因为有一种强烈的感觉,你会想要附加另一个字符串
str.append("I have ").append(std::to_string(myMoney)).append(" dollars");
operator =
myObj1 = myObj2 = myObj3
swap
没有这么强烈的感觉。表达式 obj.swap(other).swap(rhs)
看起来很常见吗?