我提前道歉,因爲我沒有特定的答案。只有一些見解,將不勝感激。下面的評論(以及代碼)概述了一些觀察,澄清和不確定性。這裏的問題真的是會員的一生。堆棧成員VS C++對象中的堆成員
class SomeClass {
int m_int; // primitive type. hardly ever see a pointer
// For class instances, you always* seem to see this
SomeOtherClass* m_some_other_class_instance_1;
// and not this
SomeOtherClass m_some_other_class_instance_2;
// But lately, I've noticed that for std:: templates, it doesn't seem to be this
vector<double>* m_vector_instance_1;
// but rather this
vector<double> m_vector_instance_2;
};
// So it got me thinking ...
void mainThread() {
SomeClass* some_class_instance_1 = new SomeClass();
// SomeClass instance on heap
// So all its members (both <xx>_1 and <xx>_2) are on heap as well
// Hence all its members will stay alive beyond the scope of this function (or do they?)
SomeClass some_class_instance_2;
// SomeClass instance on stack
// So the only piece of data relating to SomeClass that's on the heap is what's pointed to by <xx>_1 members
// But everything else will still stay alive within the scope of this function
// In conclusion, using either case above, members of a SomeClass instance stay alive for their intended period
// So are <xx>_1 members overkill?
// Ah, ha, ha, ha, stayin' alive, stayin' alive ...
}
在背景方面,我們假設SomeClass
不知道它周圍的其他類的,不期望能夠通過任何在/出去......這樣的構造可能只是初始化其成員無論如何,編寫它的人都不知道如何使用這個類。唯一擔心的是會員活着。
我已經通過這些線程讀取,但他們都不太相關:
Why should I use a pointer rather than the object itself?
Class members and explicit stack/heap allocation
Class members that are objects - Pointers or not? C++
您有問題要問? –
閱讀代碼中的評論。其中一些是問題。 – Ash
如何更清晰和具體的比*「那麼 _1成員過度殺傷?」* –