为什么我们必须在复制构造函数的参数中使用引用而不是指针?这个问题在接受采访时被问到了。我回答了以下几点:
但面试官不满意。他说它“与继承和虚拟功能有关”。我需要帮助或一些相关的观点,我可以在这个方向上思考答案。
答案 0 :(得分:2)
你的面试官错了,你是对的。
你的答案最重要的方面是2.和3(基本上是相同的点,但措辞不同):因为标准如此(see 12.8.2):
如果第一个参数的类型为
X
,X&
,const X&
或volatile X&
,则类const volatile X&
的非模板构造函数是一个复制构造函数,并且没有其他参数,或者所有其他参数都有默认参数(...)。
我们使用引用而不是指针,因为标准是这样的。否则,它不是复制构造函数。
当涉及到继承和虚函数时,引用可以执行指针所能做的所有事情。
您可以提供的另一个原因是Gautam Jha points out in the comments,即引用允许您从临时副本中复制。
答案 1 :(得分:2)
你指出看起来很明智,我无法弄清楚你的采访者想要听到的消息。
但是,据我所知,为复制构造函数和赋值运算符启用统一语法是Stroustrup引入引用的一个重要原因。例如,假设我们在C ++中没有引用,我们想要做一些复制构造,通过指针传递参数:
class MyClass {
// Copy ctor and assignment operator are declared
// like this in our referenceless "C with classes" language:
MyClass(const MyClass* const);
MyClass* operator=(const MyClass* const);
};
MyClass a, b, c;
//Let's copy-construct:
MyClass d = &a; // Dereferencing looks ugly.
//Let's assign:
a = &b; // Dereferencing again.
// Even worse example:
a = b = c = &d; // Only the last variable should be dereferenced.
a = b = &c; // Awfully inhomogeneous code.
/*
The above line is equivalent to a = (b = &c),
where (b = &c) returns a pointer, so we don't need to
dereference the value passed to assignment operator of a.
*/
这显然不是内置类型的工作方式:
int a, b, c;
int d = a;
a = b = c = d;
因此引入了参考来解决这些不均匀性。
<强> UPD 强>
有关这一点的权威性证明,请参阅Stroustrup的C ++设计和演变的第3.7节。不幸的是,我没有这本书的英文文本,但本章的第一句是(后译成英文):
基本上为操作符重载支持引入了引用。
在接下来的几页中,Stroustrup深入探讨了这个话题。