为什么拷贝构造函数的参数是引用而不是指针? [英] Why is the argument of the copy constructor a reference rather than a pointer?

查看:168
本文介绍了为什么拷贝构造函数的参数是引用而不是指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么复制构造函数的参数是引用而不是指针?

Why is the argument of the copy constructor a reference rather than a pointer?

为什么我们不能使用指针?

Why can't we use the pointer instead?

推荐答案

有很多原因:


  1. 为NULL。 OK,可以创建一个NULL引用,但也可以将 std :: vector< int> * 转换为 std :: vector< ; SomeType> * 。这并不意味着这样的演员已经定义了行为。也不创建NULL引用。指针在设置为NULL时已定义行为;引用不。因此,引用总是期望引用实际对象。

  1. References cannot be NULL. OK, it's possible to create a NULL reference, but it's also possible to cast a std::vector<int>* into a std::vector<SomeType>*. That doesn't mean such a cast has defined behavior. And neither does creating a NULL reference. Pointers have defined behavior when set to NULL; references do not. References are therefore always expected to refer to actual objects.

变量和临时表不能隐式转换为其类型的指针。原因很明显。我们不希望指针临时运行,这就是为什么标准明确禁止这样做(至少当编译器可以告诉你在做它)。但我们可以向他们提供参考;

Variables and temporaries cannot be implicitly converted into pointers to their types. For obvious reasons. We don't want pointers to temporaries running around, which is why the standard expressly forbids doing it (at least when the compiler can tell you are doing it). But we are allowed to have references to them; these are implicitly created.

由于第2点,使用指针而不是引用将要求每个复制操作使用运算符的地址&)。哦,等等,C ++委员会愚蠢地允许这是重载。因此,任何复制操作都需要实际使用 std :: addressof ,一个C ++ 11功能,获取地址。所以每个副本需要看起来像 Type t {std :: addressof(v)}; 或者你可以使用引用

Because of point number 2, using pointers rather than references would require every copy operation to use the address-of operator (&). Oh wait, the C++ committee foolishly allowed that to be overloaded. So any copy operation would need to actually use std::addressof, a C++11 feature, to get the address. So every copy would need to look like Type t{std::addressof(v)}; Or you could just use references.

这篇关于为什么拷贝构造函数的参数是引用而不是指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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