像Java一樣管理對象:T&形式僅僅用在參數傳遞
類的對象為了關聯/包含一個T類型的instance,若成員變量包括T*/ T&, 這種設計叫做“aggregation”(聚合);而若采用T 形式,則稱為"composition"(組合)
1 //組合Composition 2 class Man { 3 Eye eye; 4 Nose nose; 5 } 6 7 //聚合Aggregation 8 class Man { 9 Dog* dog; 10 House& house; 11 }
這個回答不錯,百度知道:? 組合和聚合的區別?
怎樣看待“引用類型作為類的成員變量”?
參考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&)。
像Java一樣管理對象:T&形式僅僅用在參數傳遞