mercredi 20 novembre 2019

Error in pushing unique_ptrs from map into a vector

I have a std::map of std::string and std::unique_ptr<BaseInt>. Basically I want to have a map with the class name as string key and a unique pointer as the corresponding value. And access the pointer as map["Derived1"] etc (explained in code below).

When I iterate over the std::map and try to push each value to a std::vector, I see the following error

Error C2280 'std::unique_ptr>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function CreateInstanceFromList c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.16.27023\include\xmemory

I am on Visual Studio 2017 Version 15.9.16 MSVC 14.16.27023

The implementation code is as follows. BaseInt is a BaseClass with an int member and a pure virtual replaceInt(). DerivedInt1 and DerivedInt2 implement the virtual function with different int values and differ by a parameter in their construction.

#include "UserClass.h"
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <memory>
#include <typeinfo>

typedef std::vector<std::unique_ptr<BaseInt>> vec_type;
typedef std::map<std::string, std::unique_ptr<BaseInt>> map_type;

template<typename T> std::unique_ptr<T> createInstance(vec_type& vec) { return std::move(std::make_unique<T>()); };
template<typename T, typename U> std::unique_ptr<T> createInstance(vec_type& vec, U u) { return std::move(std::make_unique<T>(u)); };

void fillVector(map_type& map)
{
    vec_type my_vec;
    for (auto const& it : map )
    {
        std::cout << it.first << std::endl;
        it.second->replaceInt();

        //my_vec.emplace_back(std::move(it.second)); //this line gives error
    }
    // idea is to be able to access the pointer as map["Derived1"]
    std::cout << my_vec.size() << std::endl;
}

int main()
{
    map_type my_map;

    my_map.emplace("Derived1", createInstance<DerivedInt1>(my_vec, 7));
    my_map.emplace("Derived2", createInstance<DerivedInt2>(my_vec));

    fillVector(my_map);

    return 0;
}

Kindly help me understand the error and why this happens. My intuition is somehow I am trying to call the copyconstructor of the unique_ptr but I don't actually see how. Thanks.

Aucun commentaire:

Enregistrer un commentaire