c++pointersdelete-operatorforward-list

Is it safe to delete a forward_list in C++?


I have a personal project that I'm working on it and in this personal project I used once a forward_list to store some informations about some files. Then I went to play a game and suddenly I thought: is it my f_list destroyed safe? In my project I just used delete the pointer to list.

std::forward_list<fileInfo> *lst;
lst = new std::forward_list<fileInfo>;
*lst = getDirectoryFiles(cfg->logDirectory);
lst->sort();
// do something
delete lst;

I ran a separate test (for (uint i = 0; i < 1000000; ++i) lst>push_front(i);) and the delete works as expected (in task manager the memory with this list is about 77 mb and after delete is about 400 kb).

But I'm still worried if this is safe in all compilers and OSes (I tried this in MSVC2013).

Should I call first clear() for list, then delete on the pointer ?


Solution

  • Imagine someone was walking around with a cellphone in a box. The box had a camera inside, and a display on the outside that displayed what was on the phone in the box. It had fancy touch waldos that would touch whatever you touched on the box, but on the phone.

    It would even damage the phone if the box was damaged!

    The phone screen is not displayed larger.

    They come to you and ask if they can send the box (with the phone in it) to electronics recycling.

    The answer is "sure, that is safe", but the real question is, why did they build the box in the first place?

    The box, in this analogy, is the pointer, The call to new is creating the box. The call to delete is recycling it (with the phone inside).

    The phone is the forward list.