Good evening.
Immediately to the topic: there is a container map<int, unique_ptr<MySet>> mymap; (MySet is a custom type). There is another container: forward_list<shared_ptr<MySet>> myset;
Question: how from forward_list to copy elements in map (from shared_ptr to unique_ptr)?

  • 3
    And the meaning of such a copy? If you have unique_ptr in the second container, then this should be the only pointer to the object, which means there should not be a shared_ptr for it. You are doing something seriously wrong. - VladD

1 answer 1

As I understand it, an object of class std::map<int, std::unique_ptr<MySet>> must be the owner of pointers to MySet objects, and therefore when copying it is necessary to create copies of objects stored in std::forward_list<std::shared_ptr<MySet>>

For these purposes, you can use either a regular loop or standard algorithms, such as, for example, std::transform .

Below is a sample program that shows how you can use the std::transform algorithm to copy items from one container to another. For clarity, in the calls of the constructors and destructors of the class used as the base element, I included the console output.

 #include <iostream> #include <memory> #include <forward_list> #include <map> #include <algorithm> #include <iterator> #include <utility> struct A { A() { std::cout << "A::A()" << std::endl; } A( const A & ) { std::cout << "A::A( const A & )" << std::endl; } ~A() { std::cout << "A::~A" << std::endl; } A & operator =( const A & ) { std::cout << "A::operator =( const A & )" << std::endl; return *this; } }; int main() { std::forward_list<std::shared_ptr<A>> lst; lst.push_front( std::shared_ptr<A>( new A ) ); std::map<int, std::unique_ptr<A>> m; std::transform( lst.begin(), lst.end(), std::inserter( m, m.end() ), []( auto p ) { return std::make_pair( 1, std::unique_ptr<A>( new A( *p.get() ) ) ); } ); return 0; } 

The console output will be:

 A::A() A::A( const A & ) A::~A A::~A