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


there code:

file a.hpp:

class a; 

file a.cpp:

#include "a.hpp"  struct {    int x = 777;    int y; };  a_zew; 

file main.cpp:

#include "a.hpp" #include <iostream>  class { // definition of class different above public:    int x; };  int main() {    a; // definition of class in main.cpp    extern a_zew; // definition of class in a.cpp    std::cout << a_zew.x << std::endl; // 777    std::cout << a.x << std::endl; // junk    return 0; } 

so class a defined both in file main.cpp , a.cpp , there 2 objects of these classes defined in each translation unit. definition in both translation units of class a different code compiles. 1 definition rule says there can many definitions of type in program (but single in each translation unit) , these definitions should same. why code compile if definition of class a different in both files?

your program has undefined behavior. paragaph 3.2/6 of c++11 standard specifies:

there can more 1 definition of class type (clause 9), [...] in program provided each definition appears in different translation unit, , provided definitions satisfy following requirements. given such entity named d defined in more 1 translation unit, [...]

and follows list of requirements program indeed violating. however, @ end of list, mentioned:

[...] if definitions of d satisfy these requirements, program shall behave if there single definition of d. if definitions of d not satisfy these requirements, behavior undefined.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -