将成员变量引用为类成员 [英] Reference member variables as class members

查看:198
本文介绍了将成员变量引用为类成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的工作地点,我看到这种风格被广泛使用: -

In my place of work I see this style used extensively:-

#include <iostream>

using namespace std;

class A
{
public:
   A(int& thing) : m_thing(thing) {}
   void printit() { cout << m_thing << endl; }

protected:
   const int& m_thing; //usually would be more complex object
};


int main(int argc, char* argv[])
{
   int myint = 5;
   A myA(myint);
   myA.printit();
   return 0;
}

有没有名字来描述这个成语?我假设它是为了防止复制一个大的复杂对象可能很大的开销?

Is there a name to describe this idiom? I am assuming it is to prevent the possibly large overhead of copying a big complex object?

这是一个好的做法吗?

Is this generally good practice? Are there any pitfalls to this approach?

推荐答案


有没有名字来描述这个成语? / p>

Is there a name to describe this idiom?

在UML中,它被称为聚合。它不同于组合,成员对象不是由引用类拥有。在C ++中,可以通过引用或指针以两种不同的方式实现聚合。

In UML it is called aggregation. It differs from composition in that the member object is not owned by the referring class. In C++ you can implement aggregation in two different ways, through references or pointers.


我假设是为了防止复制大型复杂对象的可能大的开销。

I am assuming it is to prevent the possibly large overhead of copying a big complex object?

不,这将是一个很不好的理由使用这个。聚合的主要原因是所包含的对象不是包含对象所拥有的,因此它们的生命周期不受约束。特别地,引用对象的生命周期必须超过引用对象的寿命。它可能早就创建,可能会超出容器寿命的终点。除此之外,引用对象的状态不受类控制,但可以从外部改变。如果引用不是 const ,那么该类可以更改位于其外部的对象的状态。

No, that would be a really bad reason to use this. The main reason for aggregation is that the contained object is not owned by the containing object and thus their lifetimes are not bound. In particular the referenced object lifetime must outlive the referring one. It might have been created much earlier and might live beyond the end of the lifetime of the container. Besides that, the state of the referenced object is not controlled by the class, but can change externally. If the reference is not const, then the class can change the state of an object that lives outside of it.


这通常是好的做法吗?这种方法有什么缺陷吗?

Is this generally good practice? Are there any pitfalls to this approach?

这是一个设计工具。在某些情况下,这将是一个好主意,在一些它不会。最常见的陷阱是持有引用的对象的生命周期永远不能超过引用对象的生命周期。如果封闭对象在引用对象被使用之后使用引用,则您将具有未定义的行为。一般来说,最好是将组合物优先于聚合,但如果你需要它,它就像任何其他工具一样好。

It is a design tool. In some cases it will be a good idea, in some it won't. The most common pitfall is that the lifetime of the object holding the reference must never exceed the lifetime of the referenced object. If the enclosing object uses the reference after the referenced object was destroyed, you will have undefined behavior. In general it is better to prefer composition to aggregation, but if you need it, it is as good a tool as any other.

这篇关于将成员变量引用为类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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