开发者

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,开发者_C百科 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.


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?


You need to return empty boost::shared_ptr<Details>

return boost::shared_ptr<Details>();

instead of this

return NULL;

Also returning a pointer to shared_ptr is bad idea. You previous version looks better.


You should test what you get by find before accessing first or second:

inline
boost::shared_ptr<Details> 
Person::GetDetails(const std::string& name) const {
    std::map<std::string, boost::shared_ptr<Details> >::iterator i = map.find(name);

    if (i != map.end()) return i->second;
    return boost::shared_ptr<Details>(); // empty shared_ptr if not found
}

but don't return naked pointers. It would be dangerous.

Rationale:

  • find() returns map.end() iterator after the last entry. So there is no entry to access.
  • map.find(name)->first.empty() would be undefined behavior, since there may be now empty string at the end of your map.
  • shared_ptr does all the memory management. Returning raw pointers could ruin all that.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜