简体   繁体   English

为什么我们需要引用成员的复制构造函数

[英]Why do we need a copy constructor for reference members

I don't understand why we need a copy constructor (to begin with..) especially for the sake of reference members.我不明白为什么我们需要一个复制构造函数(以..开头),尤其是为了参考成员。

Given a class给定一个 class

class Foo {
   Obj &obj;
};

I must now write a copy constructor and = operator (and maybe 5 other secret things), otherwise it won't compile.我现在必须编写一个复制构造函数和=运算符(也许还有其他 5 个秘密的东西),否则它不会编译。 Why?为什么? Why would a compiler be able to figure out that it should copy an int or string but not a reference?为什么编译器能够弄清楚它应该复制一个intstring而不是一个引用? Same for a pointer?指针也一样? What does it think I might want to do instead?它认为我可能想要做什么? I have to write out exactly what the compiler writes out for every other property.我必须准确地写出编译器为每个其他属性写的内容。 What if I add, or worse, someone else adds, a new property to the class and forgets to add that to the copy ctor and operator?如果我向 class 添加了一个新属性,或者更糟的是,其他人添加了一个新属性却忘记将它添加到复制 ctor 和操作符,该怎么办?

The short answer is: because C++ standard says so.简短的回答是:因为 C++ 标准是这样说的。 But this is not a very interesting answer.但这不是一个非常有趣的答案。

To have a more interesting answer, we can ask a different question: what might be the rationale for such behavior?为了得到更有趣的答案,我们可以问一个不同的问题:这种行为的基本原理是什么?

While I do not claim to know the canonical answer to this, I would not be surprised if it is just to reduce confusion.虽然我不声称知道对此的规范答案,但如果只是为了减少混淆,我不会感到惊讶。 References as members could behave unexpectedly, and copying classes with them could yield results you are not expecting.作为成员的引用可能会出现意外行为,并且使用它们复制类可能会产生您意想不到的结果。

Technically speaking, nothing stops compiler from honestly copying the referenced member from source to destination.从技术上讲,没有什么能阻止编译器诚实地将引用的成员从源复制到目标。 But a lot of people would expect the class instead to "repoint" the reference (similar to pointers).但是很多人会期望 class 代替“重新指向”引用(类似于指针)。 But references can not be repointed, and rationale for that is given in "Design and Evolution of C++":但是不能重复引用,其基本原理在“C++ 的设计和演变”中给出:

The reason that C++ does not allow you to rebind references is given in Stroustrup's "Design and Evolution of C++": C++ 不允许您重新绑定引用的原因在 Stroustrup 的“C++ 的设计与演进”中给出:

... I had in the past been bitten by Algol68 references where r1=r2 can either assign through r1 to the object referred to or assign a new reference value to r1 (re-binding r1) depending on the type of r2. ...我过去曾被 Algol68 引用所困扰,其中 r1=r2 可以通过 r1 分配给所引用的 object,或者根据 r2 的类型为 r1 分配一个新的参考值(重新绑定 r1)。 I wanted to avoid such problems in C++.我想在 C++ 中避免此类问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM