STL 静态常量成员定义

发布于 2024-08-30 03:28:00 字数 391 浏览 3 评论 0原文

以下是如何工作的?

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

逆蝶 2024-09-06 03:28:00

那么,是什么让您认为它没有定义?事实上,您尝试获取地址会自动成功,这表明它已在某处定义。当然,它不需要驻留在翻译单元中,因此查看预处理器输出没有多大意义。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文