Search code examples
c++pointersshared-ptr

Changing a function to return a pointer


I'm quite new to C++ and I have written the class and function below:

class Person {
    public:
        boost::shared_ptr<Details> GetDetails(const std::string& name) const;
        ...
    private:
        std::map<std::string, boost::shared_ptr<Details> > map;
        ...
};

inline
boost::shared_ptr<Details>
Person::GetDetails(const std::string& name) const {
    return map.find(name)->second;
}

This works fine, but I have been told to make the function return the pointer instead, and return NULL if the find fails.

I have tried a couple of things, one of which is:

class Person {
    public:
        boost::shared_ptr<Details> *GetDetails(const std::string& name) const;
        ...
    private:
        std::map<std::string, boost::shared_ptr<Details> > map;
        ...
};

inline
boost::shared_ptr<Details>
*Person::GetDetails(const std::string& name) const {
    if (!map.find(name)->first.empty()) {
        return *map.find(name)->second;
    }
    return NULL;
}

which gives me the error:

error: cannot convert 'Details' to 'boost::shared_ptr<Details>*' in return

I'm not entirely sure what to do here. Any help or resources would be of great help.

Thanks.


Solution

  • You want to return the address of a shared pointer, so you need to use &, not *.

    Note that dealing with pointers to shared-pointers is a little bit weird. Why not just return an empty shared-pointer if you can't find the item?