I have several objects which share a data via a pointer. The pointer parameter was sent via in the constructor functions, as follows.
class A
{
public:
Shared* pB = new Shared();
User* object1 = new User(pB);
User* object2 = new User(pB);
}
class User
{
public:
User(Shared* pB) {m_sharedB = pB};
private:
Shared* m_sharedB;
}
class Shared
{
public:
struct Account
{
int account_number;
}
void method(){...};
}
My question is related with the C++ destructor function. What happens to the member variable “m_sharedB”, when object1 is deleted? Is there any problem of dangling pointer for other peers?
If you have a class that contains a member that is a pointer,
then upon destruction of a
Fooobject, nothing happens other than that the pointer, along with its containing object, goes out of scope. It’s the same as what happens topat the end of the following function:What you may have meant to ask about is “what happens to the object to which the pointer points”. That’s an entirely different question, and the answer is “nothing”.
(So usually when you have a class that contains a pointer member you should think carefully about who owns any resources that may need to be cleaned up.)
Since you mention the word “destructor” in your question, let us spell out once and for all: