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;
}
v开发者_如何学Pythonoid 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,
class Foo
{
Bar * mp_bar;
};
then upon destruction of a Foo
object, nothing happens other than that the pointer, along with its containing object, goes out of scope. It's the same as what happens to p
at the end of the following function:
void bar()
{
int * p;
}
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:
A pointer type object has no destructor. When a pointer goes out of scope, there is no automatic invocation of
delete
.
Destructing a raw pointer variable is a no-op (read more). The shared object will still be available.
When object1 is deleted, the memory pointed to by m_sharedB will not be released as you haven't provided a destructor for class User. That leaves it up to the containing class (class A) to manage the lifetime of the Shared pointer as well, making sure that it is properly deleted once no more references to it exist (i.e., all User instances which share the same Shared pointer are dead).
What happens to the member variable "m_sharedB", when object1 is deleted?
When object1 is deleted, nothing is made to pointer pB. But variable m_shared is destroyed. Also I want to advice you use smart pointers from boost library. Particularly shared_ptr
It sounds like your question was answered, but I just wanted mention boost::shared_ptr. This may not meet your current needs, but it is useful situations like you describe above.
精彩评论