释放向量的 wchar_t*
我有一个像这样的 wchar_t* 向量:
std::vector<wchar_t*> myvector;
以及一个函数,它接受一个字符串并将其插入到向量中,
void myfunction(wchar_t* mystring)
{
myvector.push_back(mystring);
}
myfunction(L"this is my string");
当我关闭程序时,我需要删除向量的分配内存,这样我就不会出现内存泄漏,这样做我正在尝试这样做:
for (std::vector<wchar_t*>::iterator it = myvector.begin(); it != myvector.end(); ++it)
{
delete [] *it;
}
它可以编译,一切正常,但是当需要释放内存时,我有一个运行时错误:
为什么?我该如何解决这个问题?
I have a vector of wchar_t* like this:
std::vector<wchar_t*> myvector;
and a function that take a string and insert it into the vector
void myfunction(wchar_t* mystring)
{
myvector.push_back(mystring);
}
myfunction(L"this is my string");
when I close the program I need to delete the allocated memory of the vector so that I don't have a memory leak, to do this I'm trying to do this:
for (std::vector<wchar_t*>::iterator it = myvector.begin(); it != myvector.end(); ++it)
{
delete [] *it;
}
it compiles, all works fine but when it's time to deallocated the memory I have a rountime error:
error http://k.min.us/iklWGE.png
why? how can I fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用此
myfunction(L"this is my string");
您不会创建新字符串。它是一个常量字符串,存储在您的 exe 中的某个位置。由于您没有显式新建
它,因此您也不需要删除
它。只能成对使用
new 和delete
以及new[] 和delete[]
!With this
myfunction(L"this is my string");
you don't create a new string. It's a constant string that's stored somewhere in your exe. And since you don't explicitlynew
it, you don't need todelete
it either.Only use
new and delete
andnew[] and delete[]
in pairs!仅
删除
您新建
的内容。您没有在任何地方直接或间接使用new
,因此没有任何可删除的内容。正如 Xeo 所说,更好的解决方案是使用 std::wstring。Only
delete
what younew
. You are not usingnew
anywhere, neither directly nor indirectly so there’s nothing to delete. As Xeo said, a better solution is to usestd::wstring
.您不应删除字符串文字。
You should not delete string literals.
您自己还没有分配任何内存。如果您的代码中没有任何 new[],则也不需要任何 delete[]。
You haven't allocated any memory yourself. If you haven't got any new[]'s in your code you don't need any delete[]'s either.