为什么复制赋值运算符返回一个引用/ const引用? [英] Why must the copy assignment operator return a reference/const reference?

查看:141
本文介绍了为什么复制赋值运算符返回一个引用/ const引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,从拷贝赋值运算符返回引用的概念对我来说不清楚。为什么复制赋值运算符不能返回新对象的副本?此外,如果我有A类和以下:

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

a3 = a2; // < - 这是有问题的行

operator =定义如下: / p>

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


解决方案

严格来说,一个复制赋值运算符不需要返回一个引用,虽然为了模仿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.

这篇关于为什么复制赋值运算符返回一个引用/ const引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆