两个本地结构,每个都在单独的cpp文件中-未定义的行为

Two local struct, each in separate cpp file - undefined behavior?

本文关键字:文件 cpp 单独 未定义 两个 结构      更新时间:2023-10-16

如果我有两个具有相同名称的struct,但它们都被写入自己的.cpp文件中,那么它真的应该是未定义的行为吗?

///////////////////////////////
// test1.h
class Foo
{
public :
    void bar();
};
///////////////////////////////
// test2.h
class Foo2
{
public:
    void bar();
};
///////////////////////////////
// test1.cpp
#include "test1.h"
struct Test
{
    Test() :a(0){}
    int a;
};
void Foo::bar()
{
    Test t;
}
///////////////////////////////
// test2.cpp
#include "test2.h"
struct Test
{
    Test() :a(0), b(0){}
    int a, b;
};
void Foo2::bar()
{
    Test t;
}
///////////////////////////////
// main.cpp
#include "test1.h"
#include "test2.h"
int main()
{
    Foo2 f;
    f.bar();
}

我已经向微软报告了这是一个错误,但他们回应说,这是未定义的。真的吗?我觉得很奇怪。

这确实给出了未定义的行为。"一个定义规则"的一部分指出,如果在多个翻译单元中定义具有外部链接的同一类,则定义必须相同。(该规则的确切措辞相当冗长,所以我不会引用它;如果你想了解血腥的细节,请参阅C++11 3.2/5)。通过在两个翻译单位中以不同的方式定义Test,可以打破这一规则。

避免这种名称冲突的最简单方法是将文件本地的定义放在未命名的命名空间中:

namespace {
    struct Test {
        // whatever
    };
}