lundi 19 août 2019

Creating objects in place that contain unique_ptr

The following piece of code compiles fine under gcc/clang

#include <memory>
#include <vector>
#include <unordered_map>

int main() {
    using hash_int_uptr = std::unordered_map<int, std::unique_ptr<int>>;
    std::vector<hash_int_uptr> v;
    v.emplace_back(hash_int_uptr{}); 
}

but fails under MSVC 16.2.1 (2019) with the error

xmemory(761,1): error C2280: 'std::pair::pair(const std::pair &)': attempting to reference a deleted function

This should be related to the non-copyability of unique_ptr, but I'm trying to create the object in place and move semantics should kick in.

Same error if I simply use v.emplace_back(); or v.emplace_back({});.

Is this a MSVC bug and is there any workaround this?

BTW, the code works fine if I just replace unique_ptr with shared_ptr, or if I simply try to emplace_back only unique_ptrs (and not maps of them).

Aucun commentaire:

Enregistrer un commentaire