英文:
Why does the C++ standard library uses names like '__r' for variables?
问题
我了解您的请求,以下是翻译好的内容:
越了解C++,就越觉得不解,C++标准库源代码(包括所有std
函数的实现)为什么大量使用带有__
前缀的变量名。比如,std::addressof()
使用__r
作为其唯一参数。我尝试找到有意义的答案,为什么会这样(甚至向ChatGPT提问过!),但没有运气。我知道__
前缀是保留的,用户代码不能使用这种名称。但用户代码如何可能与std
函数的参数名发生冲突呢?!这让我感到困惑。对于std
中的私有成员也是如此。甚至局部变量也以__
前缀开头!在这些情况下使用__
前缀的目的是什么?这几乎像是标准库的实现者通过他们的实践在建议,从某种程度上,将实现细节隐藏在用户代码之外取决于这一约定。似乎,没有这种做法,用户可能会依赖那些“不是为他们而设计”的名称。
顺便说一句,这使得C++标准库源代码变得更难阅读。也许这是有意为之?
英文:
The more I learn about C++ the less sense it makes to me that the C++ standard library source code (where all those std
functions are implemented) makes heavy use of variable names with __
prefix. Like std::addressof()
uses __r
as its single argument. I tried to get meaningful answers why this is the case (even asked ChatGPT!) but no luck. I know that __
prefix is reserved and user code cannot use such names. But how could user code collide with, say, the argument name of a function in std
?! That's what's puzzling to me. Same goes for private members in std
. Even local variables start with the __
prefix! What's the point of using __
prefix in those cases? It's almost like the standard library implementers are suggesting through their practice that somehow hiding implementation details from user code depends on this convention. That, without this practice, users could somehow rely on those names that 'were not intended for them'.
By the way, this makes C++ standard library source code much harder to read. Maybe intentionally so?
答案1
得分: 1
假设他们会使用“正常”标识符。假设实现中使用 foo
作为标识符。然后你可能会写这段代码:
#define foo
#include <一些标准头文件>
如果 一些标准头文件
使用标识符 foo
,可能会发生不好的事情。
这就是为什么对于实现,有一些标识符是保留的。你不能使用它们,否则可能会产生冲突。实现必须使用它们,否则可能会出现上述冲突。
详情请参阅此处:https://en.cppreference.com/w/cpp/language/identifiers
英文:
Suppose they would use "normal" identifiers. Suppose the implementation uses foo
as an identifier. Then you might write this code:
#define foo
#include <some standard header>
If some standard header
uses the identifier foo
bad things might happen.
Thats why for the implementation there are certain identifiers resevered. You must not use them because otherwise there might be conflict. The implementation must use them, otherwise there might be conflict as above.
See here for details: https://en.cppreference.com/w/cpp/language/identifiers
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论