Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot delete std::vector & std::array?

My C++ class has a destructor that tries to delete std::vector and std::array instance variables.

#include <iostream>
#include <vector>
#include <array>

int main()
{
    std::array<int, 3> foo;
    std::vector< std::array<float, 4> > vertices;

    foo[0] = 1;
    foo[1] = 2;
    foo[2] = 3;
    std::cout << foo[0] << std::endl;
    delete foo;
    delete vertices;

    return 0;
}

I'm not sure how to properly free up the memory - how come I can't delete those variables?

clang++ -std=c++11 -stdlib=libc++ -Weverything ccc.cpp 
ccc.cpp:14:2: error: cannot delete expression of type 'std::array<int, 3>'
        delete foo;
        ^      ~~~
ccc.cpp:15:2: error: cannot delete expression of type 'std::vector<std::array<float, 4>
      >'
        delete vertices;
        ^      ~~~~~~~~
ccc.cpp:18:2: warning: C++98 requires newline at end of file [-Wc++98-compat-pedantic]
}
 ^
like image 692
ejang Avatar asked Sep 22 '13 04:09

ejang


1 Answers

Delete these variables? The only "variables" you should delete are the ones you allocated by new. Did you allocate anything by new in this code? No. So, stop trying to delete anything.

Objects foo and vertices are local objects with automatic storage duration. The memory for these objects is allocated automatically and freed automatically. You cannot do it yourself. This is completely outside of your control.

If you want to control memory allocation manually, you have to create these objects dynamically, using new. For example

std::array<int, 3> *foo = new std::array<int, 3>();
...
(*foo)[0] = 1;
(*foo)[1] = 2;
(*foo)[2] = 3;
...
delete foo;

The above will work. But there's no real reason to involve dynamic memory in your example. It works perfectly fine as is, with automatic objects. Just stop trying to delete them.

delete expects a pointer as argument. When you will allocate objects through new, you will access these objects through pointers. These pointers is what you will later pass to delete to destroy such objects. In this code none of this is applicable.

like image 158
AnT Avatar answered Oct 06 '22 02:10

AnT