简体   繁体   中英

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?

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 . And you can't return reference of a local variable so returns House object pointer. And you have to pass the custom deleter to take care the cleaning process for the shared_ptr in that case.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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