Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do class members use smart pointers or objects [duplicate]

For example:

class Teacher{
 // ...
}


class Student{
   string name;
   Teacher math_teacher; // or use: std::share_ptr<Teacher> math_teacher;

}

Different students may have the same math teacher and I think they should share the same theacher. But I don't know whether smart points are better than objects?

And when do class members use smart pointers or objects?

Thanks!

like image 493
liym27 Avatar asked Jul 06 '26 23:07

liym27


1 Answers

The general rule is to make the code as simple as possible.

So, for example, if you have a string as class member, like the student's name, you would definitely use std::string, and not a smart pointer to it:

class Student { 
    ...
    std::string m_name; // *not* std::shared_ptr<std::string> m_name !!
};

On the other hand, if you need to represent shared ownership, like in your teacher-student example, using a std::shared_ptr would be a better choice:

class Student { 
    ...
    std::shared_ptr<Teacher> m_teacher;
};

In this case, a single Teacher instance is shared among different Students.

Moreover, if you can guarantee that the lifetime of the Teacher instance is appropriate, i.e. it's longer than that of its Students, you can even simply use a raw observing pointer:

class Student { 
    ...
    // Raw observing pointer to Teacher.
    // Note: Pay attention to the Teacher instance lifetime.
    Teacher* m_teacher;
};
like image 163
Mr.C64 Avatar answered Jul 09 '26 16:07

Mr.C64



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!