Reputation: 4499
How could I check whether a pointer's content is deleted? If I use QPointer like this:
myClass::myClass(myStruct* p){
_p = p;//_p is a myStruct*
}
myClass::function(){
if(_p) {_p->function();}
}
then I have
myStruct* p = new myStruct();
myClass A(p);
delete p;
p = NULL;
A.function();
will the last A.function() cuase the _p->function() be called and therefore cause access violation? when I delete p, what will happen to _p?
Upvotes: 0
Views: 78
Reputation: 976
Using smart pointers in this context (properly) would actually cause a compiler error if you tried to do what you did above and it was invalid. For instance, if you knew that there should only be one owner of the struct at any one time, use a unique_ptr:
myClass::myClass(std::unique_ptr<myStruct>& p)
{
_p = p;//_p is a std::unique_ptr<myStruct>
}
then:
std::unique_ptr<MyStruct> p(new MyStruct());
MyClass a(p); // <-- compiler error, cannot copy a unique_ptr, only move it
Note, that you do not have to worry about delete
ing your struct, as the smart pointer handles it (as soon as the unique_ptr goes out of scope).
If, however, you wanted to share ownership of your struct, you could use a shared_ptr and copy it fine. Then, again, you would never need to delete it manually, because it will automatically delete its self when all objects no longer reference it.
myClass::myClass(std::shared_ptr<myStruct>& p)
{
_p = p;//_p is a std::shared_ptr<myStruct>
}
then:
std::shared_ptr<MyStruct> p(new MyStruct());
MyClass a(p); // <-- no compiler error, works OK
// no need to call delete! but if you wanted to no longer use `p` anymore, simply do:
p.reset(); // <-- now MyClass is the only owner of MyStruct.
Upvotes: 0
Reputation: 10733
You are implementing shallow copy that means delete p
would make your struct member _p
dangling.
You can implement deep copy like:-
myClass::myClass(myStruct* p)
{
//Allocate memory for _p.
//copy all data from p to _p.
}
Upvotes: 2