2

我有一个vector字符串,但是这些字符串是通过为它们分配一个字符数组来创建的。这个数组是在堆中动态创建的new。我知道释放在堆中分配的内存是一个好习惯,但是我不确定应该如何释放 this 的内存vector

当我尝试做这样的事情时:

for(i = 0; i < myVector.size(); i++)
     delete myVector[i];

它给了我这个错误:

表达式必须有指针类型

这是我声明向量的方式

vector<string> myVector;
char* s1 = new char[2];
s1[0] = 'a';
s1[1] = '\0';
myVector.push_back(s1);
char* s2 = new char[2];
s2[0] = 'b';
s2[1] = '\0';
myVector.push_back(s2);
//etc..

在这种情况下我该怎么办?

4

2 回答 2

5

Since you use a vector<string> and because std::string objects manage their own memory, you do not need to delete the elements of the vector: the strings have copied the content that you passed to them on creation.

However, you need to delete the C strings that you allocated with new[]. You should do it right after you created your string object: once the string is created, the character data can be safely deleted:

char s1 = new char[2];
s1[0] = 'a';
s1[1] = '\0';
myVector.push_back(s1);
delete[] s1;  // Here

Note that you picked a rather roundabout way of creating strings: you can accomplish the same exact thing by calling

myVector.push_back("a");
于 2013-03-07T00:00:05.653 回答
1

Another possibility would be the use of std::string, i.e. std::vector<std::string>.

In that case you can't delete the initial memory anymore, unless you kept the pointers (which is pointless, because the std::string will keep ist own string copy anyway).


Considering your posted code, you should keep in mind that std::string will create ist own copy of the string you passed in the constructor, even though the constructor isn't visible due to using implicit type conversion.

Just free (delete) the memory right after you've put the string inside the vector. The string won't be affected by this.

于 2013-03-07T00:00:27.927 回答