Return unique_ptr from a C ++ 0x class method

If there is a method in my SomeType class that returns an element from the map (using the key), say

std::unique_ptr<OtherType> get_othertype(std::string name)
{
   return otMap.find(name);
}

What would ensure that the calling user receives a pointer to the one that was on the map, and not to a copy? Is it possible to do this or try to call the copy constructor (and not delete because it was deleted) because it is being returned?

Assuming I should use unique_ptr as elements of my map.

UPDATE ::

After trying to implement the code, it seems that unique_ptr and std: map /: pair dont work together in gcc 4.4.4, the couple simply did not like unique_ptr as a type parameter. (see Unable to create MoveConstructibles map ).

I changed ptr to std :: shared_ptr and it all worked.

, ?

+3
4

unique_ptr - . unique_ptr , unique_ptr .

, ? . , :

OtherType* get_othertype(const std::string& name)
{
    return otMap.find(name)->second.get();
}

, , .

, , . , :

#include <stdexcept>

OtherType* get_othertype(const std::string& name)
{
    auto it = otMap.find(name);
    if (it == otMap.end()) throw std::invalid_argument("entry not found");
    return it->second.get();
}

OtherType* get_othertype(const std::string& name)
{
    auto it = otMap.find(name);
    return (it == otMap.end()) ? 0 : it->second.get();
}

, :

OtherType& get_othertype(const std::string& name)
{
    auto it = otMap.find(name);
    if (it == otMap.end()) throw std::invalid_argument("entry not found");
    return *(it->second);
}

unique_ptr , const, :

unique_ptr<OtherType> const& get_othertype(const std::string& name)
{
    auto it = otMap.find(name);
    if (it == otMap.end()) throw std::invalid_argument("entry not found");
    return it->second;
}
+11

otMap?

otMap.find(name) std::unique_ptr<OtherType> rvalue, . , , . , , std::map<>.

, std::shared_ptr<OtherType> , get_othertype().

std::map<std::string,std::shared_ptr<OtherType>> otMap;
std::shared_ptr<OtherType> get_othertype(std::string name)
{
    auto found=otMap.find(name);
    if(found!=otMap.end())
        return found->second;
    return std::shared_ptr<OtherType>();
}
+2

otMap.find rvalue, , , rvalue , RVO'd. , , . , , , find , .

0

shared_ptr unique_ptr s? . unique_ptr , (.. ).

0

Source: https://habr.com/ru/post/1766188/


All Articles