从原始指针创建shared_ptr [英] Creating shared_ptr from raw pointer

查看:225
本文介绍了从原始指针创建shared_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a pointer to an object. I would like to store it in two containers which both have the ownership. So I think I would be good to make it a shared_ptr of C++0x. How could I convert a raw pointer to a 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对象,否则它将被删除两次。更好(但仍然不好)的方法:

You need to make sure you don't initialize both shared_ptr objects with the same raw pointer, or it will be deleted twice. A better (but still bad) way to do it:

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 的结果直接初始化智能指针,则可以降低意外初始化其他智能指针的风险。您应该做的是:

WARNING: the above code shows bad practice! raw_ptr simply should not exist as a variable. If you directly initialize your smart pointers with the result of new, you reduce your risk of accidentally initializing other smart pointers incorrectly. What you should do is:

shared_ptr<classA> my_ptr(new classA);

shared_ptr<classA> other_ptr(my_ptr);

更好的是代码更简洁。

EDIT

我应该详细说明如何使用地图。如果你有一个原始指针和两个地图,你可以做类似于我上面显示的东西。

I should probably elaborate on how it would work with a map. If you had a raw pointer and two maps, you could do something similar to what I showed above.

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!

这篇关于从原始指针创建shared_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆