gpt4 book ai didi

c++ - 如果类具有引用数据成员,为什么编译器不合成默认赋值运算符

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:08:15 24 4
gpt4 key购买 nike

在 C++ 中,如果类具有引用数据成员,则默认赋值运算符不会由编译器合成。为什么?

最佳答案

In C++, if a class has a reference data member the default assignment operator is not synthesized by compiler. Why?

复制分配应该做什么定义在:

C++03 标准 12.8/13:

Each subobject is assigned in the manner appropriate to its type:

  • if the subobject is of class type, the copy assignment operator for the class is used (as if by explicit qualification; that is, ignoring any possible virtual overriding functions in more derived classes);

  • if the subobject is an array, each element is assigned, in the manner appropriate to the element type;

  • if the subobject is of scalar type, the built-in assignment operator is used.

简而言之,这意味着每个成员都应该以适当的方式分配
这就提出了一个问题,
在类中分配引用成员的行为应该是什么?
考虑以下有关引用的内容:

  1. 引用本质上是不可分配的,它们一直引用它们被初始化的相同引用[Ref 1]
  2. 由于 #1 分配给引用不会重新分配引用,它会更改引用者的值,这是一种非直观行为。

这里没有要强制执行的默认正确行为,而是一种相当情况下的行为。因此,C++ 标准要求类的设计者处于确定此行为的最佳位置,因此决定默认赋值运算符不应由如果类具有引用数据成员,则编译器。

这个决定在:
C++03 标准 12.8/12:

An implicitly-declared copy assignment operator is implicitly defined when an object of its class type is assigned a value of its class type or a value of a class type derived from its class type. A program is ill formed if the class for which a copy assignment operator is implicitly defined has:
.......
— a nonstatic data member of reference type, or
.......


[引用 1]
C++03 标准 8.5.3/2:

A reference cannot be changed to refer to another object after initialization. Note that initialization of a reference is treated very differently from assignment to it. Argument passing (5.2.2) and function value return (6.6.3) are initializations.

关于c++ - 如果类具有引用数据成员,为什么编译器不合成默认赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10781130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com