c++ - Is deleting every index individually the only way? -


i trying make array of pointers of class data type pool deleting if array not work.

this code:

struct pool {     /* in reality, complicated stuff here */     int size; };  pool* createlargepool() { return new pool{100}; } pool* createmediumpool() { return new pool{20}; } pool* createsmallpool() { return new pool{5}; }  int main() {     using namespace std;      enum epool{         small,         medium,         large,         last     };      pool *pools[epool::last] = {         createlargepool()         , createmediumpool()         , createsmallpool()     };      //individually works.      delete pools[0];     delete pools[1];     delete pools[2];     //delete[] pools;// error. (assertion error?)     system("pause");     return 0; } 

to understanding, line pool *pools[] creating array of pool pointers. , ide saying i'm doing. i'm running code without problems until reach delete statement.

for reason delete[] causing me problems, deleting each 1 individually not:

what's going on , how can delete[] work?

the way delete each element single command make std::vector<std::unique_ptr<pool>> , call pools.clear().

all other solutions require loop on elements , delete them individually.


moreover, create*pool() functions should not return raw pointers. should return smart pointers, 2 reasons:

  • users know responsible deleting pointer.

    (with raw pointers they'd have @ internal implementations and/or documentation know that.)

  • this makes memory leaks virtually impossible, because user doesn't have remember call delete somewhere, can difficult right in complex project.

so i'd recommend returning std::unique_ptr:

std::unique_ptr<pool> createlargepool() { return std::unique_ptr<pool>(new pool{100}); } 

or better yet (in c++14):

std::unique_ptr<pool> createlargepool() { return std::make_unique<pool>(100); } 

now, if store smart pointers in raw static array:

std::unique_ptr<pool> pools[epool::last] = {     createlargepool()     , createmediumpool()     , createsmallpool() }; 

they delete managed pointer when array goes out of scope.


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -