如何将字符串推入shared_ptr向量?

How to push a string into a vector of shared_ptr?

本文关键字:ptr 向量 shared 字符串      更新时间:2023-10-16

如果我有一个共享指针的向量(V1(和一个包含大量字符串的向量(V2(。如何使用 V1 内部的shared_ptr指向 V2 内部的元素?

前任:

std::vector< std::shared_ptr< SImplementation > > V1;  
std::vector < std::string > V2; // there are strings in the V2 already
for(auto i : V2){
V1.push_back(i) // I tried this way, but it does not work because of the different types, different types mean int, string, unsigned long
}

我可以使用迭代器或使用其他shared_pointer指向 V2 中的字符串吗?

std::shared_ptr

是管理内存所有权的工具。这里的问题是std::vector已经管理了它的内存。此外,std::vector在调整元素大小或擦除元素时使指向其元素的引用和指针失效。

您可能想要的是共享资源的两个向量。该资源将在两个向量之间共享:

// there are strings in the V2 already
std::vector<std::shared_ptr<std::string>> V1;  
std::vector<std::shared_ptr<std::string>> V2;
for (auto ptr : V2) {
V1.push_back(ptr) // now works, ptr is a std::shared_ptr<std::string>
}

如果无法更改V2类型怎么办?然后,您必须以不同的方式引用对象,例如向量的索引并在擦除元素时保持同步。

std::shared_ptr

没有成员函数push_back。它最多可以指向一个对象(或自 C++17 以来的数组(。

如何将字符串推入shared_ptr向量?

喜欢这个:

std::string some_string;
std::vector<std::shared_ptr<std::string>> ptrs;
ptrs.push_back(std::make_shared<std::string>(some_string));