在使用地址清理程序构建程序时,我们检测到内存错误:AddressSanitizer: heap-use-after-free。
通常在现代 c++ 中,我们不建议使用原始指针:我们更喜欢使用容器。
你已经存储了本地std::list拥有的字符串地址,函数返回后,这些地址不可访问(打印时你得到一个空字符串,但实际上它可能会崩溃),修复它我们可以有3个选择:
- 制作副本
void convertListtoVector(std::vector<std::wstring>& messageInserts)
{
std::list<std::wstring> Inserts;
Inserts.push_back(L"str1");
Inserts.push_back(L"str2");
Inserts.push_back(L"str3");
std::list<std::wstring>::iterator itr;
for (itr = Inserts.begin(); itr != Inserts.end(); itr++) {
messageInserts.push_back(*itr);
}
}
或使用 STL 算法
void convertListtoVector(std::vector<std::wstring>& messageInserts)
{
std::list<std::wstring> Inserts;
Inserts.push_back(L"str1");
Inserts.push_back(L"str2");
Inserts.push_back(L"str3");
messageInserts.insert(messageInserts.end(), Inserts.begin(), Inserts.end());
}
- 从本地容器移动,因为不再需要本地列表,对于大字符串,移动它们将获得性能提升
void convertListtoVector(std::vector<std::wstring>& messageInserts)
{
std::list<std::wstring> Inserts;
Inserts.push_back(L"str1");
Inserts.push_back(L"str2");
Inserts.push_back(L"str3");
for (itr = Inserts.begin(); itr != Inserts.end(); itr++) {
messageInserts.push_back(std::move(*itr));
}
}
或使用 STL 算法
void convertListtoVector(std::vector<std::wstring>& messageInserts)
{
std::list<std::wstring> Inserts;
Inserts.push_back(L"str1");
Inserts.push_back(L"str2");
Inserts.push_back(L"str3");
messageInserts.insert(messageInserts.end(), std::make_move_iterator(Inserts.begin()), std::make_move_iterator(Inserts.end()));
}
- 将本地
list 设为静态,但这可能容易出错:
void convertListtoVector(std::vector<const wchar_t*>& messageInserts)
{
static std::list<std::wstring> Inserts;
Inserts.push_back(L"str1");
Inserts.push_back(L"str2");
Inserts.push_back(L"str3");
std::list<std::wstring>::iterator itr;
for (itr = Inserts.begin(); itr != Inserts.end(); itr++) {
messageInserts.push_back(itr->c_str());
}
}