复制构造函数的参数选择

发布于 2024-08-05 08:47:57 字数 226 浏览 7 评论 0原文

最近,我在一次采访中被问到有关复制构造函数的参数的问题。
[编辑] 作为实现复制构造函数功能的 C++ 语言设计者,为什么要选择常量引用参数而不是指向 const 对象的 const 指针。

我有一些想法,比如因为指针可以分配给 NULL,这在复制构造函数中可能没有意义(语义上),并且指针变量是一个独立的对象(这在效率方面可能不好)而引用只是实际对象的别名(因此是传递对象的更好方法)。
还有其他想法吗?

I was recently asked in an interview about the parameter for a copy constructor.
[Edited]
As a designer of C++ language implementing copy constructor feature, why would you choose constant reference parameter over a const pointer to a const object.

I had a few ideas like since a pointer can be assigned to NULL which probably doesn't make sense (semantically) in a copy constructor and the fact that pointer variable is an independent object (which would probably not be good in terms of efficiency) whereas a reference is just an alias to the actual object (therefore a better way to pass the object).
Any other ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

深海不蓝 2024-08-12 08:47:57

因为 Stroustrup 希望类像原始类型一样。当初始化 int 变量时:

int x = 5;
int y = x; // Why would you write int y = &x; ?

将常量指针传递给常量对象,与 C++ 为 C 带来的不一致。C++ 中的类只是用户定义类型,如果它们不像原始类型那样工作,那么这些是什么?

另一个例子是运算符重载,如果没有引用,C++ 编程将会很痛苦。想象一下你必须写:

myclass myobj1, myobj2, myobj3;
&myobj3 = &myobj1 + &myobj2;

Because Stroustrup wanted classes to be like primitive-types. When you initialize an int variable:

int x = 5;
int y = x; // Why would you write int y = &x; ?

Passing constant pointer to constant object, is inconsistent with what C++ brought to C. classes in C++ are just User-Defined Types, if they don't work like primitive types then what are they?

Another example where programming in C++ would be miserable without references is operators overloading. Imagine you have to write:

myclass myobj1, myobj2, myobj3;
&myobj3 = &myobj1 + &myobj2;
你げ笑在眉眼 2024-08-12 08:47:57

这是语法上的便利。

调用复制构造函数时最常见的用例是按值传递参数或按值返回某些内容。

如果复制构造函数的参数是指针而不是引用,则需要应用取址运算符才能调用复制构造函数,这会很尴尬。

It's a syntactic convenience.

The most common use cases for when a copy constructor gets called is when a parameter is passed by value, or something is returned by value.

If the copy constructor had a parameter that was a pointer rather than a reference, you would need to apply the address-of operator in order to invoke the copy constructor, which would be awkward.

梦旅人picnic 2024-08-12 08:47:57

我认为不在复制构造函数中使用指针的重要原因是临时变量如何绑定到右值。对于指针,可以将指针保存到临时值,并在以后使用未定义的行为,而对于引用,存储和使用引用会更困难,而使用实际值更容易。

I believe that important reason not to use pointers in copy constructors is how temporaries binded to rvalues. For pointers it will be possible to save pointer to temporary and use it later with undefined behavior, with references it is harder to store and use references, easier to use actual values.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文