1

A sample question on c++ primer: Add member named get_file that returns a shared_ptr to the file in the QueryResult object.

class QueryResult
{
    friend std::ostream& print(std::ostream&, const QueryResult&);
public:
    using line_no = std::vector<std::string>::size_type;
    QueryResult(std::string s, std::shared_ptr<std::set<line_no>> p, std::shared_ptr<std::vector<std::string>> f) :sought(s), lines(p), file(f) {}
    std::set<line_no>::iterator begin(std::string) const { return lines->begin(); };
    std::set<line_no>::iterator end(std::string) const { return lines->end(); };
    std::shared_ptr<std::vector<std::string>> get_file() const { return std::make_shared<std::vector<std::string>>(file); };
private:
    std::string sought;
    std::shared_ptr < std::set<line_no>> lines;
    std::shared_ptr<std::vector<std::string>> file;
};

compile error:

error C2665: std::vectorstd::string,std::allocator<std::string>::vector: no overloaded function could convert all the argument types.

wohlstad
  • 12,661
  • 10
  • 26
  • 39
gaofeng
  • 393
  • 1
  • 3
  • 11

2 Answers2

3

As you can see in the std::make_shared documentation, in order to create a std::shared_ptr<T>, you need to pass the arguments for T's constructor.

However in this line:

std::shared_ptr<std::vector<std::string>> get_file() const 
             { return std::make_shared<std::vector<std::string>>(file); };

You pass file which is not a proper argument for constructing a std::vector<std::string> (your T).

But since file is already a std::shared_ptr<std::vector<std::string>>, you can simply return it instead (no need for make_shared):

std::shared_ptr<std::vector<std::string>> get_file() const 
             { return file; }
wohlstad
  • 12,661
  • 10
  • 26
  • 39
0

By calling std::make_shared(), you're calling the constructor of std::vector<std::string> with a std::shared_ptr<std::vector<std::string>> as input. That's not how std::vector is created (see the constructor of std::vector<T>).

As @NathanOliver said in a comment, just returning the member file as-is will be enough.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
JANDEE
  • 1
  • 3
  • @RemyLebeau Thanks for editing my answer. As you see I'm a newbie here, and I'm wondering how can I get the link for comment. Would you kindly give me any links I can find information or some explain? – JANDEE Mar 30 '23 at 05:09
  • 1
    The timestamp of the comment "hides" a URL for the comment - you can e.g. open it in a new tab to get the URL. – wohlstad Mar 30 '23 at 05:50
  • @wohlstad Wow, I had completely no idea. Thanks a lot! – JANDEE Mar 30 '23 at 06:19
  • 1
    @wohlstad since the timestamp is a hyperlink, you can right-click/long-click on it to get popup options, which in most browsers includes copying the url. – Remy Lebeau Mar 30 '23 at 14:24