gpt4 book ai didi

c++ - 从原始指针创建 shared_ptr

转载 作者:IT老高 更新时间:2023-10-28 13:59:00 43 4
gpt4 key购买 nike

我有一个指向对象的指针。我想将它存储在两个都有所有权的容器中。因此,我认为将其设为 C++0x 的 shared_ptr 会很好。如何将原始指针转换为 shared_pointer?

typedef unordered_map<string, shared_ptr<classA>>MAP1;
MAP1 map1;
classA* obj = new classA();
map1[ID] = how could I store obj in map1??

谢谢

最佳答案

您需要确保不要使用相同的原始指针初始化两个 shared_ptr 对象,否则它将被删除两次。一种更好(但仍然很糟糕)的方法:

classA* raw_ptr = new classA;
shared_ptr<classA> my_ptr(raw_ptr);

// or shared_ptr<classA> my_ptr = raw_ptr;

// ...

shared_ptr<classA> other_ptr(my_ptr);
// or shared_ptr<classA> other_ptr = my_ptr;
// WRONG: shared_ptr<classA> other_ptr(raw_ptr);
// ALSO WRONG: shared_ptr<classA> other_ptr = raw_ptr;

警告:上面的代码显示了不好的做法! raw_ptr 根本不应该作为变量存在。如果你直接用 new 的结果初始化你的智能指针,你可以减少意外初始化其他智能指针不正确的风险。你应该做的是:

shared_ptr<classA> my_ptr(new classA);

shared_ptr<classA> other_ptr(my_ptr);

好在代码也更简洁了。

编辑

我可能应该详细说明它如何与 map 一起使用。如果你有一个原始指针和两个 map ,你可以做一些类似于我上面展示的事情。

unordered_map<string, shared_ptr<classA> > my_map;
unordered_map<string, shared_ptr<classA> > that_guys_map;

shared_ptr<classA> my_ptr(new classA);

my_map.insert(make_pair("oi", my_ptr));
that_guys_map.insert(make_pair("oi", my_ptr));
// or my_map["oi"].reset(my_ptr);
// or my_map["oi"] = my_ptr;
// so many choices!

关于c++ - 从原始指针创建 shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4665266/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com