像Java一样管理对象:T&形式仅仅用在参数传递
类的对象为了关联/包含一个T类型的instance,若成员变量包括T*/ T&, 这种设计叫做“aggregation”(聚合);而若采用T 形式,则称为"composition"(组合)
//组合Composition
class Man {
Eye eye;
Nose nose;
} //聚合Aggregation
class Man {
Dog* dog;
House& house;
}
这个回答不错,百度知道:☛ 组合和聚合的区别?
怎样看待“引用类型作为类的成员变量”?
参考StackOverflow上此问题的回答:☛ Reference member variables as class members
尤其是其中 manlio的回答:
It's called dependency injection via constructor injection: (通过构造函数进行依赖注入)
class A
gets the dependency as an argument to its constructor and saves the reference to dependent class as a private variable.
For const-correctness I'd write:
using T = int;
class A
{
public:
A(const T &thing) : m_thing(thing) {}
// ...
private:
const T & m_thing;
};
but a problem with this class is that it accepts references to temporary objects:
T t;
A a1{t}; // this is ok, but...
A a2{T()}; // ... this is BAD. //临时的匿名对象 属于 rvalue
It's better to add (requires C++11 at least):
class A
{
public:
A(const T &thing) : m_thing(thing) {}
A(const T &&) = delete; // prevents rvalue binding
// ...
private:
const T &m_thing;
};
Anyway if you change the constructor:
class A
{
public:
A(const T *thing) : m_thing(*thing) { assert(thing); }
// ...
private:
const T &m_thing;
};
it's pretty much guaranteed that you won't have a pointer to a temporary.
Also, since the constructor takes a pointer, it's clearer to users of A
that they need to pay attention to the lifetime of the object they pass.
使用T&作为成员变量后:
①各个Contructor里必须对此T& t进行赋值。
②对象生成后就不能再对它进行赋值(=),因为引用不能二次赋值。
在此提问 ☛Should I prefer pointers or references in member data? 下, anon的回答:
As everyone seems to be handing out general rules, I'll offer two:
Never, ever use references as class members. I have never done so in my own code (except to prove to myself that I was right in this rule) and cannot imagine a case where I would do so. The semantics are too confusing, and it's really not what references were designed for. (引用& 最初就是为了 运算符重载时好看 而设计出来的)
Always, always, use references when passing parameters to functions, except for the basic types, or when the algorithm requires a copy.
These rules are simple, and have stood me in good stead. I leave making rules on using smart pointers (but please, not auto_ptr) as class members to others.
即:▶T& 形式仅仅用在 参数传递 ▶作为成员变量都用T* 形式 (绝不要用T&)。
最新文章
- redis的主从复制配置
- 用jxl解析excel内容
- 利用JS实现的根据经纬度计算地球上两点之间的距离
- 【英语】Bingo口语笔记(20) - i长短音
- Android的selector,背景选择器
- 【andorid】Attribute is missing the Android namespac
- C# XML 根级别上的数据无效
- C#正则提取HTML中img的url值
- unity节目素材ProceduralMaterial采用
- 3450: Tyvj1952 Easy
- CentOS安装配置MySql数据库
- [机器学习] Apriori算法
- .NET Core阿里大于短信发送SDK修改以及使用
- 新世界主机_XenServer7.0都有哪些优势?
- [国家集训队]排队 [cdq分治]
- VMware虚拟机配置嵌套虚拟化
- FireFox升级后FireBug不能使用
- D. Boxes Packing
- php 防止sql注入的简单方法
- [LeetCode&;Python] Problem 169. Majority Element