成员变量作为引用

发布于 2024-10-20 02:04:06 字数 41 浏览 1 评论 0原文

将成员变量声明为引用有什么好处? 我看到人们这样做,但不明白为什么。

What is the advantage of declaring a member variable as a reference?
I saw people doing that, and can't understand why.

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

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

发布评论

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

评论(3

深爱不及久伴 2024-10-27 02:04:06

一种有用的情况是,当您无权访问该对象的构造函数,但又不想通过指针进行间接操作时。例如,如果类 A 没有公共构造函数,并且您的类希望在其构造函数中接受 A 实例,则您需要存储 A& ;。这也保证了引用被初始化。

One useful case is when you don't have access to the constructor of that object, yet don't want to work with indirection through a pointer. For example, if a class A does not have a public constructor and your class wants to accept an A instance in its constructor, you would want to store a A&. This also guarantees that the reference is initialized.

悲喜皆因你 2024-10-27 02:04:06

当您需要访问另一个对象而不复制它时,成员引用非常有用。

与指针不同,引用不能(意外)更改,因此它始终引用同一个对象。

A member reference is useful when you need to have access to another object, without copying it.

Unlike a pointer, a reference cannot be changed (accidentally) so it always refers to the same object.

暗藏城府 2024-10-27 02:04:06

一般来说,具有不寻常赋值语义的类型(例如 std::auto_ptr<>)和 C++ 引用更容易搬起石头砸自己的脚(或者打断整条腿)。

当引用用作成员时,这意味着编译器生成的operator=通过分配给引用的对象而不是重新分配引用来完成一件非常令人惊讶的事情,因为不能重新分配引用来引用另一个对象。换句话说,大多数时候拥有引用成员会使该类不可分配。

通过使用普通指针可以避免这种令人惊讶的行为。

Generally speaking, types with unusual assignment semantics like std::auto_ptr<> and C++ references make it easier to shoot yourself in the foot (or to shoot off the whole leg).

When a reference is used as a member that means that the compiler generated operator= does a very surprising thing by assigning to the object referenced instead of reassigning the reference because references can not be reassigned to refer to another object. In other words, having a reference member most of the time makes the class non-assignable.

One can avoid this surprising behaviour by using plain pointers.

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