How to delete an object inside of a class declared with “new” alongside the class [duplicate]












0
















This question already has an answer here:




  • When should I provide a destructor for my class?

    3 answers




Suppose we want to create a class / struct which contains an object, and repeatedly replace a pointer to an object of that class / struct with a new instance of it.



struct foo {
int a[128];
};

int main() {
foo* bar;

for(int i = 0; i < 120000; i++) {
delete bar;
bar = new foo();
}

return 0;
}


This program works, as far as I can tell, and successfully frees up the memory used by 'a' at the deletion of 'foo' (Task Manager tells me it uses about 14.5 MB of RAM). But instead of declaring it this way, let's say we need a dynamic object instead:



struct FOO {
int* A;
FOO() {
A = new int[128];
}
};

int main() {
FOO* BAR;

for(int i = 0; i < 120000; i++) {
delete BAR;
BAR = new FOO();
}

return 0;
}


In this case, the program does not seem to successfully free up the memory stored at 'A' (Task Manager tells me this uses about 78.1 MB of RAM). Why does the call to delete BAR fail to free the memory at 'A', and how can this code be reconfigured so that that can be done?










share|improve this question















marked as duplicate by n.m. c++
Users with the  c++ badge can single-handedly close c++ questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 18 '18 at 4:55


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • 1





    Pop quiz: where is your code that deletes A?

    – Sam Varshavchik
    Nov 18 '18 at 4:35











  • Classic rule of three violation.

    – David Schwartz
    Nov 18 '18 at 4:36






  • 1





    This link might help: en.cppreference.com/w/cpp/language/destructor

    – GeminiDakota
    Nov 18 '18 at 4:39











  • you do it in the destructor of the struct

    – Chris Rollins
    Nov 18 '18 at 4:42






  • 2





    "This program works". You are being overly optimistic. The code has undefined behaviour from using an uninitialised bar. Crank up your compiler warning level, and treat warnings as errors.

    – n.m.
    Nov 18 '18 at 4:48
















0
















This question already has an answer here:




  • When should I provide a destructor for my class?

    3 answers




Suppose we want to create a class / struct which contains an object, and repeatedly replace a pointer to an object of that class / struct with a new instance of it.



struct foo {
int a[128];
};

int main() {
foo* bar;

for(int i = 0; i < 120000; i++) {
delete bar;
bar = new foo();
}

return 0;
}


This program works, as far as I can tell, and successfully frees up the memory used by 'a' at the deletion of 'foo' (Task Manager tells me it uses about 14.5 MB of RAM). But instead of declaring it this way, let's say we need a dynamic object instead:



struct FOO {
int* A;
FOO() {
A = new int[128];
}
};

int main() {
FOO* BAR;

for(int i = 0; i < 120000; i++) {
delete BAR;
BAR = new FOO();
}

return 0;
}


In this case, the program does not seem to successfully free up the memory stored at 'A' (Task Manager tells me this uses about 78.1 MB of RAM). Why does the call to delete BAR fail to free the memory at 'A', and how can this code be reconfigured so that that can be done?










share|improve this question















marked as duplicate by n.m. c++
Users with the  c++ badge can single-handedly close c++ questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 18 '18 at 4:55


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.














  • 1





    Pop quiz: where is your code that deletes A?

    – Sam Varshavchik
    Nov 18 '18 at 4:35











  • Classic rule of three violation.

    – David Schwartz
    Nov 18 '18 at 4:36






  • 1





    This link might help: en.cppreference.com/w/cpp/language/destructor

    – GeminiDakota
    Nov 18 '18 at 4:39











  • you do it in the destructor of the struct

    – Chris Rollins
    Nov 18 '18 at 4:42






  • 2





    "This program works". You are being overly optimistic. The code has undefined behaviour from using an uninitialised bar. Crank up your compiler warning level, and treat warnings as errors.

    – n.m.
    Nov 18 '18 at 4:48














0












0








0









This question already has an answer here:




  • When should I provide a destructor for my class?

    3 answers




Suppose we want to create a class / struct which contains an object, and repeatedly replace a pointer to an object of that class / struct with a new instance of it.



struct foo {
int a[128];
};

int main() {
foo* bar;

for(int i = 0; i < 120000; i++) {
delete bar;
bar = new foo();
}

return 0;
}


This program works, as far as I can tell, and successfully frees up the memory used by 'a' at the deletion of 'foo' (Task Manager tells me it uses about 14.5 MB of RAM). But instead of declaring it this way, let's say we need a dynamic object instead:



struct FOO {
int* A;
FOO() {
A = new int[128];
}
};

int main() {
FOO* BAR;

for(int i = 0; i < 120000; i++) {
delete BAR;
BAR = new FOO();
}

return 0;
}


In this case, the program does not seem to successfully free up the memory stored at 'A' (Task Manager tells me this uses about 78.1 MB of RAM). Why does the call to delete BAR fail to free the memory at 'A', and how can this code be reconfigured so that that can be done?










share|improve this question

















This question already has an answer here:




  • When should I provide a destructor for my class?

    3 answers




Suppose we want to create a class / struct which contains an object, and repeatedly replace a pointer to an object of that class / struct with a new instance of it.



struct foo {
int a[128];
};

int main() {
foo* bar;

for(int i = 0; i < 120000; i++) {
delete bar;
bar = new foo();
}

return 0;
}


This program works, as far as I can tell, and successfully frees up the memory used by 'a' at the deletion of 'foo' (Task Manager tells me it uses about 14.5 MB of RAM). But instead of declaring it this way, let's say we need a dynamic object instead:



struct FOO {
int* A;
FOO() {
A = new int[128];
}
};

int main() {
FOO* BAR;

for(int i = 0; i < 120000; i++) {
delete BAR;
BAR = new FOO();
}

return 0;
}


In this case, the program does not seem to successfully free up the memory stored at 'A' (Task Manager tells me this uses about 78.1 MB of RAM). Why does the call to delete BAR fail to free the memory at 'A', and how can this code be reconfigured so that that can be done?





This question already has an answer here:




  • When should I provide a destructor for my class?

    3 answers








c++ class struct new-operator delete-operator






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 18 '18 at 4:34









eyllanesc

77.4k103156




77.4k103156










asked Nov 18 '18 at 4:32









MCosmoMCosmo

81




81




marked as duplicate by n.m. c++
Users with the  c++ badge can single-handedly close c++ questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 18 '18 at 4:55


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.









marked as duplicate by n.m. c++
Users with the  c++ badge can single-handedly close c++ questions as duplicates and reopen them as needed.

StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;

$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');

$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Nov 18 '18 at 4:55


This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.










  • 1





    Pop quiz: where is your code that deletes A?

    – Sam Varshavchik
    Nov 18 '18 at 4:35











  • Classic rule of three violation.

    – David Schwartz
    Nov 18 '18 at 4:36






  • 1





    This link might help: en.cppreference.com/w/cpp/language/destructor

    – GeminiDakota
    Nov 18 '18 at 4:39











  • you do it in the destructor of the struct

    – Chris Rollins
    Nov 18 '18 at 4:42






  • 2





    "This program works". You are being overly optimistic. The code has undefined behaviour from using an uninitialised bar. Crank up your compiler warning level, and treat warnings as errors.

    – n.m.
    Nov 18 '18 at 4:48














  • 1





    Pop quiz: where is your code that deletes A?

    – Sam Varshavchik
    Nov 18 '18 at 4:35











  • Classic rule of three violation.

    – David Schwartz
    Nov 18 '18 at 4:36






  • 1





    This link might help: en.cppreference.com/w/cpp/language/destructor

    – GeminiDakota
    Nov 18 '18 at 4:39











  • you do it in the destructor of the struct

    – Chris Rollins
    Nov 18 '18 at 4:42






  • 2





    "This program works". You are being overly optimistic. The code has undefined behaviour from using an uninitialised bar. Crank up your compiler warning level, and treat warnings as errors.

    – n.m.
    Nov 18 '18 at 4:48








1




1





Pop quiz: where is your code that deletes A?

– Sam Varshavchik
Nov 18 '18 at 4:35





Pop quiz: where is your code that deletes A?

– Sam Varshavchik
Nov 18 '18 at 4:35













Classic rule of three violation.

– David Schwartz
Nov 18 '18 at 4:36





Classic rule of three violation.

– David Schwartz
Nov 18 '18 at 4:36




1




1





This link might help: en.cppreference.com/w/cpp/language/destructor

– GeminiDakota
Nov 18 '18 at 4:39





This link might help: en.cppreference.com/w/cpp/language/destructor

– GeminiDakota
Nov 18 '18 at 4:39













you do it in the destructor of the struct

– Chris Rollins
Nov 18 '18 at 4:42





you do it in the destructor of the struct

– Chris Rollins
Nov 18 '18 at 4:42




2




2





"This program works". You are being overly optimistic. The code has undefined behaviour from using an uninitialised bar. Crank up your compiler warning level, and treat warnings as errors.

– n.m.
Nov 18 '18 at 4:48





"This program works". You are being overly optimistic. The code has undefined behaviour from using an uninitialised bar. Crank up your compiler warning level, and treat warnings as errors.

– n.m.
Nov 18 '18 at 4:48












2 Answers
2






active

oldest

votes


















-1














You need to implement the destructor to free the memory allocated inside constructor. However, memory allocation inside constructor is a bad idea and there are better alternatives to it.

Also, since you are dealing with pointers, please make sure you are checking memory allocation result and properly assigning NULL as and when required along with checking if it is safe to delete the pointer

Note1: since you have used new to allocate array, you have to use delete rather than delete.

Note2: You also started deleting the BAR even before allocating.

It should look at least something like this:



    struct FOO {
int* A;
FOO() {
A = new int[128];
}
~FOO() {
if(A) delete A; // use delete instead of delete for an array
A = nullptr;
}
};

int main() {
FOO* BAR;
BAR = new FOO();
for(int i = 0; i < 120000; i++) {
if( BAR) {
delete BAR;
BAR = nullptr;
}
BAR = new FOO();
}

return 0;
}





share|improve this answer































    -1














    What you are missing is destructor in Foo struct. See this variant :



    struct FOO {
    int* A;
    FOO() {
    A = new int[128];
    }
    ~FOO()
    {
    delete A;
    }
    };

    int main() {
    FOO* BAR;

    for(int i = 0; i < 120000; i++) {
    delete BAR;
    BAR = new FOO();
    }

    return 0;
    }


    The destructor of FOO should now take care of deleting the memory created dynamically in the constructor.






    share|improve this answer
























    • I think you mean delete A;?

      – Galik
      Nov 18 '18 at 4:46











    • Correct, sorry for typo and thanks @Galik for pointing it out!

      – user3164323
      Nov 18 '18 at 4:47


















    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    -1














    You need to implement the destructor to free the memory allocated inside constructor. However, memory allocation inside constructor is a bad idea and there are better alternatives to it.

    Also, since you are dealing with pointers, please make sure you are checking memory allocation result and properly assigning NULL as and when required along with checking if it is safe to delete the pointer

    Note1: since you have used new to allocate array, you have to use delete rather than delete.

    Note2: You also started deleting the BAR even before allocating.

    It should look at least something like this:



        struct FOO {
    int* A;
    FOO() {
    A = new int[128];
    }
    ~FOO() {
    if(A) delete A; // use delete instead of delete for an array
    A = nullptr;
    }
    };

    int main() {
    FOO* BAR;
    BAR = new FOO();
    for(int i = 0; i < 120000; i++) {
    if( BAR) {
    delete BAR;
    BAR = nullptr;
    }
    BAR = new FOO();
    }

    return 0;
    }





    share|improve this answer




























      -1














      You need to implement the destructor to free the memory allocated inside constructor. However, memory allocation inside constructor is a bad idea and there are better alternatives to it.

      Also, since you are dealing with pointers, please make sure you are checking memory allocation result and properly assigning NULL as and when required along with checking if it is safe to delete the pointer

      Note1: since you have used new to allocate array, you have to use delete rather than delete.

      Note2: You also started deleting the BAR even before allocating.

      It should look at least something like this:



          struct FOO {
      int* A;
      FOO() {
      A = new int[128];
      }
      ~FOO() {
      if(A) delete A; // use delete instead of delete for an array
      A = nullptr;
      }
      };

      int main() {
      FOO* BAR;
      BAR = new FOO();
      for(int i = 0; i < 120000; i++) {
      if( BAR) {
      delete BAR;
      BAR = nullptr;
      }
      BAR = new FOO();
      }

      return 0;
      }





      share|improve this answer


























        -1












        -1








        -1







        You need to implement the destructor to free the memory allocated inside constructor. However, memory allocation inside constructor is a bad idea and there are better alternatives to it.

        Also, since you are dealing with pointers, please make sure you are checking memory allocation result and properly assigning NULL as and when required along with checking if it is safe to delete the pointer

        Note1: since you have used new to allocate array, you have to use delete rather than delete.

        Note2: You also started deleting the BAR even before allocating.

        It should look at least something like this:



            struct FOO {
        int* A;
        FOO() {
        A = new int[128];
        }
        ~FOO() {
        if(A) delete A; // use delete instead of delete for an array
        A = nullptr;
        }
        };

        int main() {
        FOO* BAR;
        BAR = new FOO();
        for(int i = 0; i < 120000; i++) {
        if( BAR) {
        delete BAR;
        BAR = nullptr;
        }
        BAR = new FOO();
        }

        return 0;
        }





        share|improve this answer













        You need to implement the destructor to free the memory allocated inside constructor. However, memory allocation inside constructor is a bad idea and there are better alternatives to it.

        Also, since you are dealing with pointers, please make sure you are checking memory allocation result and properly assigning NULL as and when required along with checking if it is safe to delete the pointer

        Note1: since you have used new to allocate array, you have to use delete rather than delete.

        Note2: You also started deleting the BAR even before allocating.

        It should look at least something like this:



            struct FOO {
        int* A;
        FOO() {
        A = new int[128];
        }
        ~FOO() {
        if(A) delete A; // use delete instead of delete for an array
        A = nullptr;
        }
        };

        int main() {
        FOO* BAR;
        BAR = new FOO();
        for(int i = 0; i < 120000; i++) {
        if( BAR) {
        delete BAR;
        BAR = nullptr;
        }
        BAR = new FOO();
        }

        return 0;
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 18 '18 at 4:45









        AbhinavAbhinav

        962827




        962827

























            -1














            What you are missing is destructor in Foo struct. See this variant :



            struct FOO {
            int* A;
            FOO() {
            A = new int[128];
            }
            ~FOO()
            {
            delete A;
            }
            };

            int main() {
            FOO* BAR;

            for(int i = 0; i < 120000; i++) {
            delete BAR;
            BAR = new FOO();
            }

            return 0;
            }


            The destructor of FOO should now take care of deleting the memory created dynamically in the constructor.






            share|improve this answer
























            • I think you mean delete A;?

              – Galik
              Nov 18 '18 at 4:46











            • Correct, sorry for typo and thanks @Galik for pointing it out!

              – user3164323
              Nov 18 '18 at 4:47
















            -1














            What you are missing is destructor in Foo struct. See this variant :



            struct FOO {
            int* A;
            FOO() {
            A = new int[128];
            }
            ~FOO()
            {
            delete A;
            }
            };

            int main() {
            FOO* BAR;

            for(int i = 0; i < 120000; i++) {
            delete BAR;
            BAR = new FOO();
            }

            return 0;
            }


            The destructor of FOO should now take care of deleting the memory created dynamically in the constructor.






            share|improve this answer
























            • I think you mean delete A;?

              – Galik
              Nov 18 '18 at 4:46











            • Correct, sorry for typo and thanks @Galik for pointing it out!

              – user3164323
              Nov 18 '18 at 4:47














            -1












            -1








            -1







            What you are missing is destructor in Foo struct. See this variant :



            struct FOO {
            int* A;
            FOO() {
            A = new int[128];
            }
            ~FOO()
            {
            delete A;
            }
            };

            int main() {
            FOO* BAR;

            for(int i = 0; i < 120000; i++) {
            delete BAR;
            BAR = new FOO();
            }

            return 0;
            }


            The destructor of FOO should now take care of deleting the memory created dynamically in the constructor.






            share|improve this answer













            What you are missing is destructor in Foo struct. See this variant :



            struct FOO {
            int* A;
            FOO() {
            A = new int[128];
            }
            ~FOO()
            {
            delete A;
            }
            };

            int main() {
            FOO* BAR;

            for(int i = 0; i < 120000; i++) {
            delete BAR;
            BAR = new FOO();
            }

            return 0;
            }


            The destructor of FOO should now take care of deleting the memory created dynamically in the constructor.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 18 '18 at 4:44









            user3164323user3164323

            626




            626













            • I think you mean delete A;?

              – Galik
              Nov 18 '18 at 4:46











            • Correct, sorry for typo and thanks @Galik for pointing it out!

              – user3164323
              Nov 18 '18 at 4:47



















            • I think you mean delete A;?

              – Galik
              Nov 18 '18 at 4:46











            • Correct, sorry for typo and thanks @Galik for pointing it out!

              – user3164323
              Nov 18 '18 at 4:47

















            I think you mean delete A;?

            – Galik
            Nov 18 '18 at 4:46





            I think you mean delete A;?

            – Galik
            Nov 18 '18 at 4:46













            Correct, sorry for typo and thanks @Galik for pointing it out!

            – user3164323
            Nov 18 '18 at 4:47





            Correct, sorry for typo and thanks @Galik for pointing it out!

            – user3164323
            Nov 18 '18 at 4:47



            這個網誌中的熱門文章

            Academy of Television Arts & Sciences

            L'Équipe

            1995 France bombings