成员变量作为引用
将成员变量声明为引用有什么好处? 我看到人们这样做,但不明白为什么。
What is the advantage of declaring a member variable as a reference?
I saw people doing that, and can't understand why.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种有用的情况是,当您无权访问该对象的构造函数,但又不想通过指针进行间接操作时。例如,如果类
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 anA
instance in its constructor, you would want to store aA&
. This also guarantees that the reference is initialized.当您需要访问另一个对象而不复制它时,成员引用非常有用。
与指针不同,引用不能(意外)更改,因此它始终引用同一个对象。
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.
一般来说,具有不寻常赋值语义的类型(例如
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.