如何将字符串指针数组转换为字符串类型的智能指针向量?

How to convert an array of string pointers into a vector of smart pointers of type string?

本文关键字:指针 字符串 智能 类型 向量 转换 数组      更新时间:2023-10-16

我有这样的代码:

std::string* string_ptr[] = { new std::string("x"), new std::string("y"), new std::string("z") }; 

我需要得到这样的向量:

std::vector<std::unique_ptr<string>> vec;

我还需要清除原始string_ptr数组和新向量中的内存。

如何做得更好?

如果你想将所有权转移到一个向量,你可以执行以下操作(在此之后你不必释放任何内存。

int main() {
std::string* string_ptr[] = { new std::string("x"), new std::string("y"), new std::string("z") }; // step 1
size_t sze = size(string_ptr);
std::vector<std::unique_ptr<std::string>> vec(sze); // step 2
for(size_t i{}; i < sze; ++i){
vec[i].reset( string_ptr[i]);
string_ptr[i] = nullptr;//transfer the elments ownership
}
}

如果您只想复制它们(您必须管理原始指针持有的内存(

int main() {
std::string* string_ptr[] = { new std::string("x"), new std::string("y"), new std::string("z") }; // step 1
size_t sze = size(string_ptr);
std::vector<std::unique_ptr<std::string>> vec(sze); // step 2
for(size_t i{}; i < sze; ++i){
;
vec[i].reset(new std::string{*string_ptr[i]});
}
vec.erase(vec.end()-1);
}

请参阅为什么我不能将unique_ptr push_back到矢量中?

你可以写

std::vector<std::unique_ptr<std::string>> vec{&string_ptr[0], &string_ptr[3]};

这会将指针传输到矢量内的std::unique_ptr<std::string>对象中。但请记住,您不需要释放string_ptr中的字符串,因为它们现在由向量内的唯一指针持有。

一些进一步的建议:不要在数组中分配字符串,稍后将它们传输到向量。这不是例外安全。如果在第二步结束之前发生异常,将会出现内存泄漏。如果可能,根本不要使用指针:

std::vector<std::string> vec{ "x", "y", "z" };

或者立即将字符串指针放入容器中:

std::vector<std::unique_ptr<std::string>> vec;
vec.emplace_back(std::make_unique<std::string>("x"));
// ...