Reputation: 5500
I am learning C++ OO design. When to declare class member on heap vs stack?
class RacingLiveEvent
{
public:
playerlist *pl;
}
vs
class RacingLiveEvent
{
public:
playerlist pl;
}
What design/runtime/compiletime considerations will help me decide. Any suggestions please?
I see with heap, I can define each class in its own header file. If I use static object, I need all the dependent class to be in one file.
Edit: This question is more about class design than difference between pointer and reference as pointed out by some moderator/stackoverflow AI. We already have some answers from Peter and Sombrero in comments.
Upvotes: 0
Views: 187
Reputation: 7374
If you need to share/pass the member to other functions/classes use a pointer (better shared_ptr
) given that the member is big such that copy is costly.
Pointer allows the member to outlive its scope, and you want to allow the member live longer than its scope if it is in use within some other classes or function when your object destructed.
A good use case for shared_ptr
is some different type of objects sharing the same member:
class A{
public:
A(std::shared_ptr<SomeType> member) :
member(member){}
std::shared_ptr<SomeType> member;
//
};
class B{
public:
B(std::shared_ptr<SomeType> member) :
member(member){}
std::shared_ptr<SomeType> member;
//
};
Here A and B can share the same member and if they share, member
dies only when everyone who are using member
go out of their scope.
Please note that if you share your member with others using a bare pointer is not a good idea.
Other than this use stack.
Upvotes: 1