I'm trying to use a custom unique_ptr
inside a std::pair
inside collections. Below is what I have so far, but if I uncomment the first commented-out line then I get an error:
No matching constructor for initialization of PairedThing1
So I haven't gotten as far as putting these pairs in a container (the second commented-out line).
I've noted my intent in the comments. I'm seeking the right C++ incantation.
template<class T> using UniqueThingRef = typename std::unique_ptr<std::remove_pointer_t<T>, void(*)(T)>;
typedef struct Thing1* Thing1Ref;
using PairedThing1 = std::pair<UniqueThingRef<Thing1Ref>, int>;
Thing1Ref MakeThing1()
{
return (Thing1Ref)(new char()); //fake this for now
}
void KillThing1( Thing1Ref t)
{
delete (char*)t; //fake this for now
}
static void trythings()
{
UniqueThingRef<Thing1Ref> uni(MakeThing1(), KillThing1);
// PairedThing1 duo(uni, 42); //uni should drop ref and hand to duo
std::vector< PairedThing1> someThings;
// someThings.insert( someThings.begin(), duo); //duo should drop ref and hand to someThings
}
You can't copy a std::unique_ptr
(hence the name). You have to move it.
PairedThing1 duo(uni, 42);
should be
PairedThing1 duo(std::move(uni), 42);
likewise the 2nd commented piece of code should be
someThings.insert(someThings.begin(), std::move(duo));