调用函数填充const wchar_t*类型vector后字符串为空,错误原因是什么
问题根源
你代码的问题是产生了悬垂指针,指针指向的内存已经被释放。
std::list<std::wstring> Inserts 是 convertListtoVector 函数内的局部变量,函数执行结束后,这个局部变量会被自动销毁,列表内存储的所有std::wstring对象也会随之析构,其内部管理的字符串内存会被回收。
你在循环中调用(*itr).c_str()获取的是每个std::wstring内部字符串的裸指针,这些指针的有效性完全绑定对应std::wstring的生命周期。当函数退出、列表被销毁后,vector<const wchar_t*>里存储的所有指针都变成了无效的野指针,访问这些指针指向的内存属于未定义行为,你观察到的内容为空就是该行为的表现。
修复方案
- 方案1(更推荐,无需手动管理生命周期):将存储目标改为
std::vector<std::wstring>,直接拷贝字符串内容,生命周期和vector绑定。
改后代码示例: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 (const auto& str : Inserts) { messageInserts.push_back(str); } } // 调用方式 std::vector<std::wstring> msg; convertListtoVector(msg); // 需要使用const wchar_t*时,在使用处调用对应wstring的c_str()方法即可 - 方案2(必须保留
std::vector<const wchar_t*>时使用):延长存储字符串的列表的生命周期,保证使用vector期间,原始字符串对象不会被销毁。
改后代码示例:void convertListtoVector(std::list<std::wstring>& Inserts, std::vector<const wchar_t *>& messageInserts) { Inserts.push_back(L"str1"); Inserts.push_back(L"str2"); Inserts.push_back(L"str3"); for (const auto& str : Inserts) { messageInserts.push_back(str.c_str()); } } // 调用方式 std::list<std::wstring> inserts; std::vector<const wchar_t *> msg; convertListtoVector(inserts, msg); // 注意:使用msg的全程必须保证inserts不会被销毁、不会被修改
内容的提问来源于stack exchange,提问作者RituV
相关产品推荐
相关产品推荐

