0

How to correct move resource from existed unique_ptr to another created in container? I want to put to container some unique_ptr with resource from another unique_ptr. Or maybe move one unique_ptr from one container to another container.

Some code with creation is here:

#include <memory>
#include <map>
#include <string>

struct MyClass
{
    std::string s;
};

int main(int argc, char* argv[])
{
    std::map<std::string, MyClass> container;
    
    std::unique_ptr<MyClass> tmp = std::make_unique<MyClass>();
    tmp->s = "test string";

    auto result = container.emplace(std::piecewise_construct,
        std::make_tuple("test"),
        std::make_tuple(std::move(tmp))
    );
    return 0;
}
Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Pasha
  • 89
  • 9
  • 1
    You cannot move the object itself to be held by the map, but in your case the members of `MyClass` are movable and thus `MyClass` will be movable. So you will get a new Object of type `MyClass` and I am aware of no mechanism to retain the object and have it be managed by the map instead of the unique_ptr. – bitmask Jan 24 '22 at 14:49

1 Answers1

1

Your map holds MyClass, but you are trying to move a std::unique_ptr<MyClass> into it.

You need to get the instance from your std::unique_ptr and move that.

std::make_tuple(std::move(*tmp))
                          ^___ Dereference the unique_ptr
super
  • 12,335
  • 2
  • 19
  • 29
  • error `message : see reference to function template instantiation 'std::tuple std::make_tuple(MyClass &&)' being compiled` – Pasha Jan 24 '22 at 11:35
  • @Pasha [Can't reproduce](https://godbolt.org/z/bETv8o46T). – super Jan 24 '22 at 11:40
  • That is in Visual Studio 2019 – Pasha Jan 24 '22 at 14:14
  • `1>Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\tuple(890,18): error C2440: '': cannot convert from '_Ty' to '_Ttype' 1> with 1> [ 1> _Ty=MyClass 1> ] 1>Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\tuple(888,1): message : No constructor could take the source type, or constructor overload resolution was ambiguous 1>test.cpp(144): message : see reference to function template instantiation 'std::tuple std::make_tuple(MyClass &&)' being compiled` – Pasha Jan 24 '22 at 14:31
  • 1
    You sure are a stubborn one huh... ? It compiles fine with [msvc](https://godbolt.org/z/oxc814EGW) as well. You probably have something more in your code that makes `MyClass` non-movable... if I had to guess. The point I'm trying to get across here is that I shouldn't have to guess. Update your question with a proper [mre]. – super Jan 24 '22 at 16:26