【发布时间】:2014-10-15 18:08:25
【问题描述】:
我通过将其内存分配给堆来创建了一个向量。然后我创建了 10 个也分配给堆内存的字符串对象,并将它们存储在向量中。我尝试使用delete 运算符释放与每个新字符串对象关联的内存,但我不知道该怎么做。我正在使用 C++ 11。
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int main()
{
vector<string> *v = new vector<string>;
for(int i = 0; i < 10; i++) {
// allocate a new string object on the heap
string *a = new string("Hello World");
//de-reference the string object
v->push_back(*a);
}
// show the contents of the vector
for(auto i = v->begin(); i != v->end(); ++i) {
// okay so this makes a lot more sense than:
// const string &s = *i;
// this way we create a pointer to a string object
// it is a lot more clear this way
const string *s = &(*i);
cout << *s << " " << s->length() << endl;
}
cout << endl << endl;
for(vector<string>::iterator it = v->begin(); it != v->end(); ++it) {
delete ⁢
v->erase(it);
}
for(auto i = v->begin(); i != v->end(); ++i) {
cout << *i << endl;
}
cout << endl << "Size: " << v->size() << endl;
delete v;
}
g++ -std=c++11 main.cc -o main
我的错误是并非所有对象都被删除。在最后 4 个语句之后,我最终得到了 5 个对象。一旦这些操作完成,我希望向量内有零个对象。
我的输出:
Hello World 11
Hello World 11
Hello World 11
Hello World 11
Hello World 11
Hello World 11
Hello World 11
Hello World 11
Hello World 11
Hello World 11
Hello World
Hello World
Hello World
Hello World
Hello World
Size: 5
问题在于并非所有对象都被删除。
【问题讨论】:
-
为什么要动态分配向量?没有理由这样做。您根本不需要执行任何手动内存管理。
-
这是出于教育目的。除了学习,我所做的一切都是徒劳的。
-
只需删除所有指针和所有新闻,它就会按照您想要的方式工作。
-
第一个 for 循环是内存泄漏的天堂。更不用说所有这些动态分配容易出错且无用。容器正是为您处理这个问题。
*new X();是“内存泄漏运算符”顺便说一句,这就是你在 for 循环中所做的事情。 -
@self -
This is for educational purposes.这并不难——你用new/new[]分配的东西你用delete/delete[]释放。你真正学到的(如果你可以称之为学习的话)就是如何编写一系列代码,以便释放分配的内容。
标签: c++ memory-management vector