Initialization of boost :: shared_ptr <std :: vector <T>> with boost :: shared_ptr <std :: list <T>>
I would like to initialize boost::shared_ptr<std::vector<std::string> > vec in the constructor initialization list with boost::shared_ptr<std::list<std::string> > list ?
Is it possible?
I tried this:
Test.hpp
class Test { public: Test(boost::shared_ptr<std::list<std::string> > list); private: boost::shared_ptr<std::vector<std::string> > vec; }; test.cpp
Test::Test(boost::shared_ptr<std::list<std::string> > list) : vec(list->begin(), list->end()) { } Part of the error message:
Test.cpp: In constructor 'Test::Test(boost::shared_ptr<std::list<std::basic_string<char> > >)': Test.cpp:6:85: error: no matching function for call to 'boost::shared_ptr<std::vector<std::basic_string<char> > >::shared_ptr(std::list<std::basic_string<char> >::iterator, std::list<std::basic_string<char> >::iterator)' Replace:
vec(list->begin(), list->end()) with:
vec(boost::make_shared(list->begin(), list->end())) Your constructor should look like this:
Test::Test(const boost::shared_ptr<std::list<std::string> >& list) : vec(boost::make_shared(list->begin(), list->end())){ } Keep in mind that you are copying data from std::list to std::vector .
If you need a less expensive solution, you can move them with std::make_move_iterator . However, since you are still using smart boost pointers, I think you don't have access to it.
Edit:
if it does not work, try the following:
vec(boost::make_shared<std::vector<std::string>>(list->begin(), list->end())) Edit 2:
To cover the case of nullptr , as mentioned by @Maxim Yegorushkin:
class Test{ public: Test(const boost::shared_ptr<std::list<std::string> >& list); private: boost::shared_ptr<std::vector<std::string> > convert_to_vec(const boost::shared_ptr<std::list<std::string> >& lst) const; boost::shared_ptr<std::vector<std::string> > vec; }; //in .cpp Test::Test(const boost::shared_ptr<std::list<std::string> >& list): vec(convert_to_vec(list)){ } boost::shared_ptr<std::vector<std::string> > Test::convert_to_vec(const boost::shared_ptr<std::list<std::string> >& lst) const{ if(lst!=nullptr){ return boost::make_shared<std::vector<std::string>>(list->begin(), list->end()); } return nullptr; } As a side note: it is not clear why the constructor accepts shared_ptr<X> but does not use shared_ptr<X> . Instead, take X& . Avoid using smart pointers if possible.
Ideally, your code should look like this:
class Test { public: Test(std::list<std::string> const& list) : vec(list.begin(), list.end()) {} private: std::vector<std::string> vec; };