Hey,
i'm lacking a proper search term for my problem, so i hope this question hasn't been answered already.
So, i have a class called Parent.On instantiation it creates two other objects and holds reference to them with shared_pointers.The other objects need to know, who their "creator" is.Because of that they store a simple pointer to the parent object.Is the following approach correct for this use ? Or are there any reasons to use weak_ptr or anything different from below ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Member {
Parent* p = nullptr;
Member(Parent* p) : p(p) {}
Parent* getParen() { return p; }
};
class Parent {
shared_ptr<Member> m1{ nullptr };
shared_ptr<Member> m2{ nullptr };
int status = 0;
Parent() {
m1 = make_shared<Member>(this);
m2 = make_shared<Member>(this);
}
};
@doug4 yes that makes sense, thanks!
If p would be a shared_ptr to parent and both member objects would be destroyed, the destructor of the parent object would be called, right?
@cire it aactually is shared, i just stripped down the example
That's a great idea, if shared pointers aren't needed! I'm always too focused on the constructor :D
1 2 3 4 5 6 7
class Parent {
Member m1 {*this} ;
Member m2 {*this} ;
// ...
};
By the way:
There is no way to create a shared pointer of an object while in the constructor of the same object, right?
That totally makes sense to me, just want to be sure...
1 2 3 4
class Parent {
Member m1 {std::shared_ptr<Parent>(*this)};
//....
};