简体   繁体   中英

Cannot insert std::unique_ptr with custom deleter with std::move

I use a std::unique_ptr with a custom deleter as a value of a std::map as follows:

#include <iostream>
#include <memory>
#include <map>

void deleter(int* p){
    std::cout<<"Deleting..."<<std::endl;
    delete p;
}

int main()
{   
    std::map<char, std::unique_ptr<int, void(*)(int*)>> a;
    std::unique_ptr<int, void(*)(int*)> p{new int{3}, deleter}; 
    a['k'] = std::move(p);
}

When inserting a value, I use std::move , but it will not compile.

What am I doing wrong?

You see the errors following link.

https://wandbox.org/permlink/fKL4QDkUTDsj4gDc

a['k'] will default construct the value type of the map if the key does not exist. Since your unique_ptr uses a custom deleter, it is not default constructable. You will have to use either map::emplace() or map::insert() to add the unique_ptr to the map. If you want to know if the element exists or not before you do so, you can use either map::count() or map::find() .

If you can use C++17, you can use map::try_emplace() instead, which will only add the object if the key does not exist, saving you a lookup.

The bug is in the default construction of the map entry before the assignment!

Sorry no time to work up the answer, but generally I would use insert instead?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM