我想向你展示這個非常簡單的例子,其目的是對一些動態分配的字符串進行排序,並清理重新調整向量大小並重新分配無用的佔用內存的副本。擦除指針向量中的元素並釋放先前通過new運算符分配的動態內存?
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
void print_v (vector<string *>& v)
{
cout << "----" << endl;
for (string*& str : v)
cout << *str << " ";
cout << endl << "----" << endl;
}
typedef string * string_ptr;
int main()
{
vector<string_ptr> v;
v.push_back(new string("aba"));
v.push_back(new string("baba"));
v.push_back(new string("saba"));
v.push_back(new string("aba"));
v.push_back(new string("naba"));
v.push_back(new string("aba"));
v.push_back(new string("saba"));
v.push_back(new string("laba"));
print_v(v);
sort(v.begin(), v.end(), [](const string_ptr &a, const string_ptr &b){
return a->compare(*b) < 0;
});
auto last = unique(v.begin(), v.end(), [](const string_ptr &a, const string_ptr &b) {
return a->compare(*b) == 0;
});
print_v(v);
for_each(last, v.end(), [](string_ptr &a){
delete a; //if I comment this line everything works "fine"
a = nullptr;
});
v.erase(find(v.begin(), v.end(), nullptr) , v.end());
print_v(v);
}
爲什麼這種東西不起作用?如果我用delete
評論該行,一切正常,但我當然有內存泄漏。另一個問題:如果在使用lambda函數的簽名中使用string*
(而不是typedef string_ptr
),我會收到令人討厭的編譯錯誤,爲什麼?
對不起,我的英語不好,我希望問題很清楚。
只要有一個「矢量」就好多了。你需要額外的動態分配?除非你有重要的理由沒有在這裏陳述/展示,否則大部分上述代碼是不必要的。 –
'std :: string'並不是動態使用的,你不應該試圖自己管理這樣的內存問題,因爲'std :: unique_ptr'已經在管理STL集合中對象的銷燬方面做了它的工作。 STL已經提供了2個數據結構來管理唯一對象:'std :: set'和'std :: unordered_set'。 –
Jack
如果這只是一個例子,爲什麼不使用unique_ptr?當元素被擦除時它將刪除內存。然而,請謹慎使用,即首先需要將std :: move放入數組中。 –
Robinson