my first question:
If I create a shared_ptr<class A>
inside of class B constructor:
class B{
public:
B(){
auto a = make_shared<A>();
}
};
will the owner of the object A be the instance of B or only the constructor of B? in other words is the lifetime of the shared_ptr be the lifetime of the the instance or when the constructor finishes the lifetime of that object will end?
my second question is:
class A takes in a raw pointer of an instance of class B in the constructor, class A has a weak_ptr<B>
pointing to that object as a member variable since weak_ptr
can only be used on shared_ptr
and other weak_ptr
and not raw pointers how do I create a weak_ptr
to point to the raw pointer of instance B in my class A? right now what I am doing is:
class A{
public:
A(class B* b){
mB = std::shared_ptr<B>(b);
}
private:
std::weak_ptr<B> mB;
};
I have a hunch that this is not right specially if the lifetime of shared_ptr
end with the constructor. So if there is a better way to store a raw pointer as a weak_ptr
let me know.
Thanks
PS. it must be a weak_ptr
not a shared_ptr
that is stored in class A
because if the instance of class B
gets destroyed I do not want it to linger around any other class which will happen if shared_ptr
is used since the ref count of that object will increase.
also class B
is calling class A
so the instance is passed as this
to the class A
constructor.