提问人:Franco 提问时间:8/29/2023 最后编辑:LoSFranco 更新时间:11/19/2023 访问量:107
在 std::map 中理解 shared_ptr<void> 的用法时遇到问题
Problems understanding the use of shared_ptr<void> in std::map
问:
我有以下代码:
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <sstream>
using namespace std;
typedef std::map<std::string, std::shared_ptr<void>> M;
typedef std::vector<std::string> S;
void build_word_tree_from_sentences(const S& sentence_list, M& root)
{
for (const auto& sentence : sentence_list)
{
std::string word;
std::stringstream ss(sentence);
M* base = &root;
while (ss >> word)
{
auto found = base->find(word);
if (found == base->end())
{
base->insert(std::make_pair(word, std::make_shared<M>()));
}
auto b = base->find(word)->second;
base = std::static_pointer_cast<M>(b).get();
}
}
}
int main()
{
S sentence_list = {"Hello word", "Hello there"};
M tree;
build_word_tree_from_sentences(sentence_list, tree);
}
我想帮助理解地图中的用法。
在映射中插入新元素(如果尚不存在)时:std::shared_ptr
M
base->insert(std::make_pair(word, std::make_shared<M>()));
用空参数调用,这也让我感到困惑。std::shared_ptr
答:
您的问题需要在得出答案之前研究一些特征。std::shared_ptr
std::shared_ptr 是一个智能指针,它通过指针保留对象的共享所有权。多个对象可能拥有同一个对象。当发生以下任一情况时,对象将被销毁并解除分配其内存:std::shared_ptr
- 最后剩下的拥有该物品的人被摧毁;
std::shared_ptr
- 拥有该对象的最后一个剩余部分将分配给另一个指针。
std::shared_ptr
此指针和其他智能指针的基本思想是允许客户端像使用本机指针一样使用它们,但提供自动内存管理的附加功能。特别是,他们利用了 SBRM。
此机制对于容器非常有用,因为它们适用于对象的对象,而不是最终由对象引用的外部存储。例如,在擦除操作中,容器会销毁对象(在这种情况下,将销毁包含该对象的整个节点,然后解除分配)。如果使用本机指针来引用外部对象,则当指针被销毁时,外部存储将因此不会被释放,从而导致内存泄漏。除其他外,使用本机指针将无法像 .value_type
std::shared_ptr
由于对象删除过程是类型擦除的,因此可以专门用于不完整类型,这允许客户端以与使用本机指针相同的方式引用任何对象。std::shared_ptr
void
void*
调用不带参数的 std::make_shared() 函数,因为该类型不是数组,因此会分配该类型的值初始化对象。此外,该函数在性能和空间使用方面具有很小的优势,因为它为引用计数器和对象分配内存。M
我相信开发代码是为了创建一个包含类型对象的代码,以便创建一个节点本身就是树的树,依此类推。但是,将专业化定义为专业化本身会导致递归。std::map
std::map
mapped_type
std::map
using M = std::map<std::string, M>>;
因此,有必要将 定义为一个 void 指针,它可以引用类型的对象,而无需定义它。尽管 的使用可能看起来不合适,但由于资源共享从未在代码段中发生,因此它可能更受欢迎,因为需要更多注意才能与 一起使用。mapped_type
M
std::shared_ptr
std::unique_ptr
void
评论