问题
I was reading about One Definition Rule. It says that:
if one .cpp file defines struct S { int x; }; and the other .cpp file defines struct S { int y; };, the behavior of the program that links them together is undefined. This is usually resolved with unnamed namespaces.
I don't understand why & how it is undefined? Will someone explain me the actual reason behind this? How it is resolved with unnamed namespaces?
回答1:
It's just as it says. You defined the same class S
twice, with different definitions. The makers of the language have declared that you shall not do this. The reason is that allowing it would be clearly nonsensical, and result in breaking compatibility across your translation units. Which definition is the "right" one? Which should your compiler use?
An unnamed namespace results in the two definitions actually defining different classes S
, which are properly named something akin to my-anonymous-namespace-1::S
and my-anonymous-namespace-2::S
, though you can never refer to them like that because the namespaces are, well, anonymous.
来源:https://stackoverflow.com/questions/32700125/c-confusion-about-one-definition-rule