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


in code tried make template classp_array store pointer object shown below. template class stores pointers , deletes them if not deleted after usage. should null check.

although problem addressed in other questions. don't understand how check if pointer null or not.

in destructor ~p_array() checking null pointers not effective.

i tried similar using std::shared_ptr explain idea.

p_array destructor:

~p_array() {     unsigned int = 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];      (int = 0; < 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 } 

so question is:

  1. if delete pointer stored in container deletes pointers in destructor how container know if these pointers deleted?

  2. does deleting pointer makes null pointer?

  3. if container can't check deleted pointers how can gain ownership of these pointers such in case of p_array example?

if delete pointer stored in container delete pointers in destructor how container knows if these pointers accually deleted?

it doesn't. pointer has no information beyond address of object points to. if need information determine whether object dynamically allocated, or whether it's been deleted, you'll need keep somewhere else, in smart pointer.

does deleting pointer makes null pointer ?

no.

if container can't check deleted pointers how can gain ownership of these pointers such in case of p_array example

use smart pointer std::unique_ptr or std::shared_ptr, depending on whether should have exclusive or shared ownership.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -