且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么复制赋值运算符返回一个引用/ const引用?

更新时间:2023-11-12 14:20:10

严格来说,一个复制赋值运算符不需要返回一个引用,虽然为了模仿C ++编译器使用的默认行为,它应该返回一个非const引用给被赋值的对象(隐式生成的复制赋值操作符将返回一个非 - 参考 - C ++ 03:12.8 / 10)。我看到一个公平的代码,从拷贝分配重载返回 void ,我不记得什么时候导致了严重的问题。返回 void 将阻止用户分配链接( a = b = c; ),例如,在测试表达式中的赋值的结果。虽然这种代码绝不是前所未闻的,我也不认为它是特别常见的 - 特别是对于非原始类型(除非一个类的接口打算用于这些类型的测试,如iostreams)。

我不建议你这样做,只是指出它是允许的,它似乎并不会导致很多问题。



这些其他SO问题与您可能感兴趣的信息/意见相关(可能不是很复杂)。




In C++, the concept of returning reference from the copy assignment operator is unclear to me. Why can't the copy assignment operator return a copy of the new object? In addition, if I have class A, and the following:

A a1(param);
A a2 = a1;
A a3;

a3 = a2; //<--- this is the problematic line

The operator= is defined as follows:

A A::operator =(const A& a)
{
    if (this == &a)
    {
        return *this;
    }
    param = a.param;
    return *this;
}

Strictly speaking, the result of a copy assignment operator doesn't need to return a reference, though to mimic the default behavior the C++ compiler uses, it should return a non-const reference to the object that is assigned to (an implicitly generated copy assignment operator will return a non-const reference - C++03: 12.8/10). I've seen a fair bit of code that returns void from copy assignment overloads, and I can't recall when that caused a serious problem. Returning void will prevent users from 'assignment chaining' (a = b = c;), and will prevent using the result of an assignment in a test expression, for example. While that kind of code is by no means unheard of, I also don't think it's particularly common - especially for non-primitive types (unless the interface for a class intends for these kinds of tests, such as for iostreams).

I'm not recommending that you do this, just pointing out that it's permitted and that it doesn't seem to cause a whole lot of problems.

These other SO questions are related (probably not quite dupes) that have information/opinions that might be of interest to you.