C++ 中的重载赋值运算符 [英] Overloading assignment operator in C++
问题描述
据我所知,当重载 operator= 时,返回值应该是非常量引用.
As I've understand, when overloading operator=, the return value should should be a non-const reference.
A& A::operator=( const A& )
{
// check for self-assignment, do assignment
return *this;
}
在以下情况下允许调用非常量成员函数是非常量的:
It is non-const to allow non-const member functions to be called in cases like:
( a = b ).f();
但是为什么要返回一个引用呢?如果返回值没有声明为引用,在什么情况下会出现问题,比如说按值返回?
But why should it return a reference? In what instance will it give a problem if the return value is not declared a reference, let's say return by value?
假设复制构造函数已正确实现.
It's assumed that copy constructor is implemented correctly.
推荐答案
不返回引用是一种资源浪费,并且会产生奇怪的设计.为什么您要为您的运营商的所有用户制作一份副本,即使几乎所有用户都会丢弃该值?
Not returning a reference is a waste of resources and a yields a weird design. Why do you want to do a copy for all users of your operator even if almost all of them will discard that value?
a = b; // huh, why does this create an unnecessary copy?
此外,您的类的用户会感到惊讶,因为内置的赋值运算符不会同样复制
In addition, it would be surprising to users of your class, since the built-in assignment operator doesn't copy likewise
int &a = (some_int = 0); // works
这篇关于C++ 中的重载赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!