STL 静态常量成员定义
以下是如何工作的?
#include <limits>
int main()
{
const int* const foo = &std::numeric_limits<int> ::digits;
}
我的印象是,为了获取静态 const-ant 成员的地址,我们必须在某些翻译单元中对其进行物理定义,以便取悦链接器。也就是说,在查看该 TU 的预处理代码后,我找不到 digits
成员(或任何其他相关成员)的外部定义。
我在两个编译器(VC++ 10 和 g++ 4.2.4)上对此进行了测试,并得到了相同的结果(即,它有效)。链接器是否自动神奇地链接到定义了这些内容的目标文件,或者我在这里遗漏了一些明显的东西?
How does the following work?
#include <limits>
int main()
{
const int* const foo = &std::numeric_limits<int> ::digits;
}
I was under the impression that in order to take an address of a static const
-ant member we had to physically define it in some translation unit in order to please the linker. That said, after looking at the preprocessed code for this TU, I couldn't find an external definition for the digits
member (or any other relevant members).
I tested this on two compilers (VC++ 10 and g++ 4.2.4) and got identical results from both (i.e., it works). Does the linker auto-magically link against an object file where this stuff is defined, or am I missing something obvious here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
那么,是什么让您认为它没有定义?事实上,您尝试获取地址会自动成功,这表明它已在某处定义。当然,它不需要驻留在翻译单元中,因此查看预处理器输出没有多大意义。
Well, what makes you think that it is not defined? The very fact that your attempt to take the address succeeded automatically indicates that it is defined somewhere. It is not required to reside in your tranlation unit, of course, so looking through the preprocessor output doesn't make much sense.