> This means that with your new design, all sub-objects of Person must be
> smart pointers (instead of regular pointers) everywhere in my program now, right?
Yes, a
complete objects of a derived type of person must be dynamically allocated and the object and its sub-objects must not be accessed through
owning raw pointers.
Private or protected constructors with public static factory functions returning shared pointers can facilitate this usage.
As in the earlier snippet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
class Girl : public Person
{
Girl( const std::string& name ) : Person( name ) { // private
std::cout << "Girl::constructor: " << name << ' ' << this << '\n' ;
}
public:
// enforce dynamic storage duration
static std::shared_ptr<Girl> make(const std::string& name) {
return std::shared_ptr<Girl>( new Girl( name ) ) ;
}
// ...
};
|
Note: technically, for an object that would never be accessed via a proxy, and for which
shared_from_this() would never be invoked, this is not required.
> In other words, no more use of regular pointers for Person and its derived types anywhere.
Yes. To be precise, no
owning raw pointers anywhere, and no multiple
unrelated shared pointers to the same object.