C++标准库为什么会用像'__r'这样的变量名?

huangapple go评论114阅读模式
英文:

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 &lt;some standard header&gt;

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

huangapple
  • 本文由 发表于 2023年6月27日 17:55:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76563677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定