make_shared returns error C2665: no overloaded function could convert all the argument types

1k Views Asked by At

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.

2

There are 2 best solutions below

0
wohlstad On BEST ANSWER

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; }
4
JANDEE On

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.