C++ standard: ODR and constexpr std::string_view

回眸只為那壹抹淺笑 提交于 2019-12-05 23:22:03

Merely including foo.h from multiple translation units will not violate the ODR. However, indeed, there are some uses of kSomeString that will violate the ODR. See here for details and standard wording: https://stackoverflow.com/a/34446445

It is not guaranteed that kSomeString.data() will return the same value in all translation units because it is not guaranteed that the string literal "blah" is the same object in all translation units. According to [lex.string]/16,

Evaluating a string-literal results in a string literal object with static storage duration, initialized from the given characters as specified above. Whether all string literals are distinct (that is, are stored in nonoverlapping objects) and whether successive evaluations of a string-literal yield the same or a different object is unspecified. [ Note: The effect of attempting to modify a string literal is undefined. — end note ]

In C++17, the potential ODR violations can be prevented by defining kSomeString to be inline. This will give it external linkage and hence a single address throughout the program (see [basic.link]/3 and [basic.link]/4) and allow it to be multiply defined (see [basic.def.odr]/4). Obviously .data() can then only return one possible value.

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