(ODR 使用问题)在不同文件中priority_queue名称相同的结构

(ODR-use question) priority_queue of identically named structs in different files

本文关键字:queue priority 结构 文件 ODR 问题      更新时间:2023-10-16

请考虑以下文件:

a.cpp

#include <queue>
struct Event {  
int a;
};
static bool operator<(const Event &a, const Event &b) {
return a.a < b.a;
}
void external_insert(std::priority_queue<Event> &pqu, Event event) {
pqu.push(event);
}
int main() {
// fails
std::priority_queue<Event> pqu;
external_insert(pqu, Event());
// works
// std::priority_queue<Event> pqu;
// pqu.push(Event());
return 0;
}

b.cpp

#include <queue>
struct Event {
int a, b;
};
static bool operator<(const Event &a, const Event &b) {
return a.a < b.a;
}
void some_unused_function() {
std::priority_queue<Event> evqu;
evqu.push(Event());
}

然后使用以下方法将这两个文件编译为两个可执行文件:

g++ a.cpp b.cpp -o ab
g++ b.cpp a.cpp -o ba

然后在瓦尔格林德下运行两者:

valgrind ./ab
# ... ERROR SUMMARY: 0 errors from 0 contexts ...
valgrind ./ba
# ... ERROR SUMMARY: 2 errors from 2 contexts ...

瓦尔格林德对这两个程序的确切输出可以在此要点中找到。

执行以下任一操作时不会发生错误:

  • 将"事件"替换为两个文件之一中的任何其他名称
  • 使两个结构的大小相同
  • main()中选择第二组两行而不是第一行
  • priority_queue替换为vector,并使用push_back代替push

我倾向于认为这是编译器(编译器错误?(中的一个问题,其中两个版本的模板即时方法的命名priority_queue相互冲突。

这是一个已知问题,这是一个新错误,还是我错过了什么?

您违反了一个定义规则,因此您的程序具有未定义的行为。

若要修复它,可以将一个或两个结构放入命名空间中,以使它们唯一。 如果在它们自己的 .cpp 文件之外不需要它们,则可以将它们放入匿名命名空间中。

正如John Zwinck所说,这是违反ODR的行为。 您可以使用-flto来诊断此类违规行为:

$ g++ -O2 -flto a.cpp b.cpp 
a.cpp:3:8: warning: type 'struct Event' violates the C++ One Definition Rule [-Wodr]
struct Event {
^
b.cpp:3:8: note: a different type is defined in another translation unit
struct Event {
^
b.cpp:4:12: note: the first difference of corresponding definitions is field 'b'
int a, b;
^
b.cpp:3:8: note: a type with different number of fields is defined in another translation unit
struct Event {
^