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

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

问题描述

在 C++ 中,我不清楚从复制赋值运算符返回引用的概念.为什么复制赋值运算符不能返回新对象的副本?另外,如果我有 A 类,以及以下内容:

A a1(param);A a2 = a1;A a3;a3 = a2;//<--- 这是有问题的行

operator= 定义如下:

A A::operator=(const A& a){如果(这个 == &a){返回 *this;}参数 = a.param;返回 *this;}

解决方案

严格来说,复制赋值运算符的结果不需要返回引用,尽管为了模仿 C++ 编译器使用的默认行为,它应该返回对分配给的对象的非常量引用(隐式生成的复制赋值运算符将返回非常量引用 - C++03:12.8/10).我见过相当多的代码从复制赋值重载返回 void ,我不记得这何时导致严重问题.例如,返回 void 将阻止用户进行赋值链接"(a = b = c;),并阻止在测试表达式中使用赋值的结果.虽然这种代码绝非闻所未闻,但我也不认为它特别常见 - 特别是对于非原始类型(除非类的接口用于此类测试,例如用于 iostream).

我不建议您这样做,只是指出这是允许的,而且似乎不会造成很多问题.

这些其他 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.

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

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