2

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!

liym27
  • 21
  • 1
  • Smart pointers are "smart" because they manage *ownership* (the lifecycle of the object). For non-ownership situations, possibly a non-owning (non-smart) pointer is reasonable. Sometimes an identifier (such as a string or uuid) that is passed to a manager object to retrieve a pointer or reference to a managed object is reasonable. – Eljay Nov 06 '20 at 12:22
  • They do that when, after analyzing your program's requirements and how it should work, you reach the conclusion that your class members should be smart pointers instead of objects. This is a decision that ***you*** must make, as a C++ developer, based on your understanding of the fundamental differences between two approaches, and what it means for your program. – Sam Varshavchik Nov 06 '20 at 12:25

1 Answers1

2

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;
};
Mr.C64
  • 37,988
  • 11
  • 76
  • 141