I have a class like the following:
class node
{
public:
node* parent;
std::list<node*> children;
};
Should I use a smart pointer instead of raw pointers? Why? If yes, what kind of smart pointer?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Always use a smart pointer wherever you own resources (memory, files etc). Owning them manually is extremely error prone and violates many good practices, like DRY.
Which one to use depends on what ownership semantics you need.
unique_ptris best for single ownership, andshared_ptrshared ownership.As children do not own their parents, a raw parent pointer is fine. However, if the parents own their children,
unique_ptrworks best here.It’s also notable that what on earth, a linked list of pointers? That makes no sense. Why not a linked list of values?