c++ - 如果指针已经被删除,指针容器如何拥有指针的所有权?

标签 c++ pointers c++11

在这段代码中,我尝试制作一个模板类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
}

所以我的问题很简单:

  1. 如果我删除存储在容器中的指针,容器会在析构函数中删除指针,那么容器如何知道这些指针是否真的被删除了?

  2. 删除一个指针会使它成为一个NULL指针吗?

  3. 如果容器无法检查已删除的指针,那么它如何才能获得这些指针的所有权,例如 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_ptrstd::shared_ptr,具体取决于它应该具有独占所有权还是共享所有权。

关于c++ - 如果指针已经被删除,指针容器如何拥有指针的所有权?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29634198/

相关文章:

pointers - 无法移出取消引用(由于索引,取消引用是隐式的)

c - C索引中的字符串指针

c++ - 我正在尝试为 Kruskal 算法实现一个 C++ 程序,它要求我按权重对图形进行排序。如何按权重对我的结构进行排序

c++ - GLFW keycallback 用户指针不携带数据

c++ - 使用初始化列表构造时如何避免创建(和删除)临时对象?

c++ - 使用 Ruby on Rails 进行复杂算法

c++使用通过数据包接收的 key 加密文本? key 沙皇?

c++ - OpenCV:反转图像的负片区域

c++ - 评估这个的顺序是什么?为什么? C++

c++ - 自动生成的 move 操作和原始指针成员