[英]Is this the correct way to use pointer,or I have to use smart pointers?
如何檢查指針的內容是否被刪除? 如果我像這樣使用QPointer:
myClass::myClass(myStruct* p){
_p = p;//_p is a myStruct*
}
myClass::function(){
if(_p) {_p->function();}
}
那我有
myStruct* p = new myStruct();
myClass A(p);
delete p;
p = NULL;
A.function();
最后一個A.function()會導致_p-> function()被調用,從而導致訪問沖突? 當我刪除p時,_p會發生什么?
您正在實現淺表復制,這意味着delete p
會使struct成員_p
懸空。
您可以實現深層復制,例如:
myClass::myClass(myStruct* p)
{
//Allocate memory for _p.
//copy all data from p to _p.
}
如果您嘗試執行上面的操作,則在這種情況下(正確)使用智能指針實際上會導致編譯器錯誤,並且它是無效的。 例如,如果您知道一次只能有一個結構的所有者,請使用unique_ptr:
myClass::myClass(std::unique_ptr<myStruct>& p)
{
_p = p;//_p is a std::unique_ptr<myStruct>
}
然后:
std::unique_ptr<MyStruct> p(new MyStruct());
MyClass a(p); // <-- compiler error, cannot copy a unique_ptr, only move it
請注意,您不必擔心delete
結構,因為智能指針會處理它(只要unique_ptr超出范圍)。
但是,如果您想共享結構的所有權,則可以使用shared_ptr並復制它。 然后,您再也不需要手動刪除它,因為當所有對象不再引用它時,它將自動刪除它的自身。
myClass::myClass(std::shared_ptr<myStruct>& p)
{
_p = p;//_p is a std::shared_ptr<myStruct>
}
然后:
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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.