在这段代码中,我尝试制作一个模板类P_array
,它存储指向一个对象的指针,如下所示。模板类简单地存储指针并在使用后未删除时将其删除。所以我应该做一个 NULL
检查。
虽然这个问题在其他问题中已经解决了。我不太明白如何检查指针是否为 NULL。
在析构函数 ~P_array()
中检查 NULL 指针是无效的。
我尝试使用 std::shared_ptr
来解释这个想法。
p_array 析构函数:
~P_array() {
unsigned int i = 0;
while(i < total)
{
if (t_array[i]) //Not effective
{
std::cout << "deleting " << t_array[i] << "\n" ;
delete (t_array[i]); //Ownership of pointer
}
i++;
}
}
main.cpp :
#include <iostream>
#include <memory>
#include "p_array.h"
class Obj {
public: ~Obj () { std::cout << "Deleting Obj...\n" ;}
};
int main() {
P_array<Obj> ap;
Obj * op[10];
for (int i = 0; i < 10 ; i++)
{
op[i] = new (Obj);
ap.add(op[i]);
}
std::shared_ptr <Obj> sp = std::make_shared<Obj>();
//if (sp.get()) delete sp.get() ; // invalid pointer error
sp.reset();
//delete op[0] ;// gives double free error
}
所以我的问题很简单:
如果我删除存储在容器中的指针,容器会在析构函数中删除指针,那么容器如何知道这些指针是否真的被删除了?
删除一个指针会使它成为一个
NULL
指针吗?如果容器无法检查已删除的指针,那么它如何才能获得这些指针的所有权,例如
P_array
示例?
最佳答案
If I delete a pointer which is stored in a container which delete the pointers in the destructor then how the container knows if these pointers are accually deleted?
事实并非如此。除了它所指向的对象的地址之外,指针没有任何信息。如果您需要额外的信息来确定该对象是否是动态分配的,或者它是否已被删除,您需要将其保存在其他地方,比如在智能指针中。
Does deleting a pointer makes it a NULL pointer ?
没有。
if the container can't check for deleted pointers then how it can gain the ownership of these pointers such in case of P_array example
使用智能指针,例如 std::unique_ptr
或 std::shared_ptr
,具体取决于它应该具有独占所有权还是共享所有权。
关于c++ - 如果指针已经被删除,指针容器如何拥有指针的所有权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29634198/