Search code examples
c++vectormove

Copy vector of object to vector of shared_ptrs


I have a simple struct and vector of its objects. And I want to move all objects to the vector of shared_ptrs. I don't need the initial vector anymore. I presented you with my situation.

Is my approach correct? I want to do this the most effective way:

struct MyStruct
{
    int i_;
    std::string s_;
};

void copyVector(std::vector< MyStruct>&& vt)
{
    std::vector<std::shared_ptr<MyStruct>> ptrsVt;


    for (auto& v : vt)
        ptrsVt.push_back(std::make_shared<MyStruct>(std::move(v)));

    // ...
}

void processing()
{
    std::vector<MyStruct> vt = getVectorFromSomewhere();

    copyVector(std::move(vt));
}

Solution

  • Yes, that's correct. You might want to reserve the size of the destination beforehand though:

    #include <algorithm>
    #include <cstdio>
    #include <iterator>
    #include <memory>
    #include <string>
    #include <utility>
    #include <vector>
    
    template <class T>
    auto transform_vector(std::vector<T>&& src) -> std::vector<std::shared_ptr<T>> {
      std::vector<std::shared_ptr<T>> dst;
      dst.reserve(src.size());
    
      transform(begin(src), end(src), back_inserter(dst),
                [](T& elm) { return std::make_shared<T>(std::move(elm)); });
    
      return dst;
    }
    
    int main() {
      std::vector<std::string> elms{"a", "b", "c"};
      auto ptrs = transform_vector(std::move(elms));
    
      for (auto const& elm : elms) {
        std::printf("\"%s\", ", elm.c_str());  // moved strings, possibly empty
      }
    
      std::putchar('\n');
    
      for (auto const& ptr : ptrs) {
        std::printf("\"%s\", ", ptr->c_str());  // "a", "b", "c"
      }
    
      std::putchar('\n');
    }