mardi 14 avril 2015

How can pointers container can have the ownership of pointers if pointers are already deleted?

In this code I tryed to make a template classP_array which store pointer to an object as shown below. simply the template class store pointers and delete them if not deleted after usage. so i should make NULL checking


Although this problem was addressed in other questions. I dont really understand how to check if pointer is NULL or not.


in the Destructor ~P_array() checking NULL pointers is not effective


I tryed something similar using std::share_ptr to explain the idea


p_array destructor:



~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]);
}

//if (sp.get()) delete sp.get() ; // invalid pointer error
sp.reset() ;

//delete op[0] ;// gives double free error
}


So simply my question is:


1- 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?


2- Does deleting a pointer makes it a NULL pointer ?


3- 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


My thanks


Aucun commentaire:

Enregistrer un commentaire