mercredi 19 juin 2019

Cannot add unmovable type to unordered_map

Please consider the following code:

#include <mutex>
#include <unordered_map>

struct S {
    std::mutex m;
};

int main() {
    std::unordered_map< int, S > u;

    u.emplace( 0, S() );
}

While the error message reported by gcc is unreadable, the gist of it is that because std::mutex is unmovable, I cannot create an element in the map of type S. Since the actual elements of the map never move, this is not a real problem. Indeed, the following program does compile:

#include <mutex>
#include <unordered_map>

struct S {
    std::mutex m;

    explicit S( int dummyArg ) {}
};

int main() {
    std::unordered_map< int, S > u;

    u.emplace( 0, 1 );
}

I am looking for a way to emplace an instance of S in the map without generating a dummy argument constructor.

Aucun commentaire:

Enregistrer un commentaire