dimanche 29 octobre 2017

ambigous struct definition in different modules

I have a large C++11 project with MS Visual Studio 2015, that defines in two modules (= compilation units, cpp-files) two structs with same name but different content. Since the stucts are only defined and used within the modules and not exported for shared use via any header file, this should be allowed, and indeed neither the compiler nor the linker reports any error or warning. But at run time, I get an access violation from the constructor of an unordered map that contains the struct. The problem does also occur with Visual Studio 2017, but NOT with gcc5.4. In my opinion it is a compiler bug, but I am not absolutely sure. Here is some minimized source code to reproduce the problem, just link with any executable to get the access violation during startup before main().

module1.cpp:

#include <unordered_map>
struct AmbigousStruct {
    int i1;
    int i2;
    int i3;
};
static const std::unordered_map<int, AmbigousStruct>
s_ambigousStructMap{
    { 0, { 0, 1, 2 } }
};

module2.cpp:

#include <unordered_map>
struct AmbigousStruct {
    int i1;
    int i2;
};
static const std::unordered_map<int, AmbigousStruct>
s_ambigousStructMap{
    { 0, { 0, 1 } }
};

The problems seems to be related to using the struct in a template class (unordered_map in this case), since it does not occur with a simple instance of the struct, i.e. module2.cpp:

static const AmbigousStruct s_ambigousStructInstance{ 0, 1 };

Aucun commentaire:

Enregistrer un commentaire