简体   繁体   English

C ++从对象创建shared_ptr

[英]C++ Create shared_ptr from Object

So on my header file I have this declaration: 因此,在我的头文件中,我有以下声明:

typedef std::map<const std::string, std::shared_ptr<House> > myHouseMap;
myHouseMap _myHouseMap;

On my source file I can insert an object in my map like this: 在源文件中,我可以像这样在地图中插入一个对象:

_myHouseMap.insert(std::pair<const std::string, std::shared_ptr<House>>("apartment", std::make_shared<House>("apartment")));

But now, I need to return the reference of the object. 但是现在,我需要返回对象的引用。 Therefore, I need to create first the object, add him to the map, and return the reference to it. 因此,我需要先创建对象,将其添加到地图,然后返回对该对象的引用。

House& Obj::CreateHouse (const char *name)
{
     House aaa ("apartment");
    _myHouseMap.insert(std::pair<const std::string, std::shared_ptr<House>>(aaa)); <--- ERROR!
     return &aaa;
}

How can I, after creating an Object, create a shared_ptr from it, and insert into a map? 创建对象后,如何从该对象创建一个shared_ptr并插入到地图中?

Thanks in advance 提前致谢

You can simply construct the shared pointer first rather than inline when inserting it into the map. 将共享指针插入地图时,您可以简单地首先构造共享指针,而不是内联。

House& Obj::CreateHouse(const char *name)
{
    // make the ptr first!
    auto aaa = std::make_shared<House>("apartment");
    _myHouseMap.insert(std::make_pair("apartment", aaa));
    return *aaa;
}

You can create object House pointer using new operator to initialize the shared_ptr . 您可以使用new运算符创建对象House指针,以初始化shared_ptr And you can't return reference of a local variable so returns House object pointer. 而且您无法返回局部变量的引用,因此将返回House对象指针。 And you have to pass the custom deleter to take care the cleaning process for the shared_ptr in that case. 在这种情况下,您必须传递自定义删除器,以保管shared_ptr的清理过程。

House* Obj::CreateHouse (const char *name)
{
     House* aaa = new Hash("apartment");
    _myHouseMap.insert(std::pair<const std::string, std::shared_ptr<House>>(aaa,[=](House * aaa) {delete aaa;}));
     return aaa;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM