我的C++类有一个析构函数,尝试删除std::vector和std::array实例变量。
#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;
}
我不确定如何正确释放内存 - 为什么我不能删除这些变量?
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]
}
^
new
进行内存分配,为什么还想使用delete
释放内存呢?这些是自动变量 - 当它们超出其作用域时会被自动销毁。 - Igor Tandetniknew
附加。 - chrisstd::array
不会动态分配任何内存。std::vector
会动态分配内存,但同样不需要你担心。 - AnT stands with Russia