I apologize in advance as I'm not after a specific answer as such. Just some insight would be appreciated. The comments (along with the code) below, outline some observations, clarifications, and uncertainties. The issue here is really lifetime of members.
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 ...
}
In terms of context, let's assume that SomeClass
is not aware of any other classes around it and doesn't expect to be passing anything in/out for now...so the constructor might just initialise its members with whatever and the person who wrote it has no idea of how the class may be used. The only concern is the members staying alive.
I've read through these threads but they aren't quite related:
Why should I use a pointer rather than the object itself?