C++ confusion about one definition rule

旧城冷巷雨未停 提交于 2019-12-11 11:34:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!