Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

c++ - One definition rule and different class definitions in two translation units

There is this code:

file a.hpp:

class A;

file a.cpp:

#include "a.hpp"

struct A {
   int x = 777;
   int y;
};

A a_zew;

file main.cpp:

#include "a.hpp"
#include <iostream>

class A { // definition of class A is different than above
public:
   int x;
};

int main() {
   A a; // definition of class A in main.cpp
   extern A a_zew; // definition of class A in a.cpp
   std::cout << a_zew.x << std::endl; // 777
   std::cout << a.x << std::endl; // junk
   return 0;
}

So class A is defined both in file main.cpp and a.cpp and there are also two objects of these classes defined in each translation unit. Definition in both translation units of class A is different but this code compiles. However one definition rule says that there can be many definitions of the type in the program (but only single in each translation unit) and these definitions should be the same. So why does this code compile even if definition of class A is different in both files?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your program has undefined behavior. Paragaph 3.2/6 of the C++11 Standard specifies:

There can be more than one definition of a class type (Clause 9), [...] in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit, then [...]

And what follows is a list of requirements that your program is indeed violating. However, at the end of the list, this is mentioned:

[...] If the definitions of D satisfy all these requirements, then the program shall behave as if there were a single definition of D. If the definitions of D do not satisfy these requirements, then the behavior is undefined.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...