静态数组常量会影响共享库布局吗?
考虑以下两种 C++ 标头情况:
情况 1:
class Test {
public:
static int TEST_DATA[];
};
int Test::TEST_DATA[] = { 1, 2, 3, 4 };
情况 2:
class Test {
public:
static int const TEST_DATA[];
};
int const Test::TEST_DATA[] = { 1, 2, 3, 4 };
后一种情况中的 const 是否仅用于自我强加的编译时检查,还是会影响 Mac/Linux/Windows 上的共享库布局?
更新:根据答案,编译器可能将 const 内容放在只读页面上。 是否在 Windows 或 GCC 上运行 Visual C++ 在 Mac 或 Linux 上实际上将 const 数据放置在只读页面上? 也许我测试的方式是错误的,但在 Intel 上的 Mac 上,const 版本的元素似乎是可写的。
Consider these two C++ header cases:
Case 1:
class Test {
public:
static int TEST_DATA[];
};
int Test::TEST_DATA[] = { 1, 2, 3, 4 };
Case 2:
class Test {
public:
static int const TEST_DATA[];
};
int const Test::TEST_DATA[] = { 1, 2, 3, 4 };
Is const in the latter case only for self-imposed compile-time checks or does it affect shared library layout on Mac/Linux/Windows?
Update: According to the answers, the compiler may put the const stuff on a read-only page. Does Visual C++ on Windows or GCC
on Mac or Linux actually place const data on a read-only page? Perhaps I tested the wrong way but on Mac on Intel, the elements of the const version seemed writable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编译器可能会将数据放入二进制文件的不同部分,具体取决于它是否为 const - 这完全由编译器决定。
The compiler may put the data into a different section of the binary depending on whether it's const or not - that's entirely at the discretion of the compiler.
编译器(或者实际上是链接器)可以将第二个放入标记为只读的段中,以便在您尝试写入时触发硬件异常。 由于写入不打算写入的内容是安全攻击的载体,因此越来越多的系统正在保护其只读数据。
The compiler (or, actually, the linker) could place the second into a segment marked as read-only, to trigger a hardware exception if you tried to write to it. Since writing to things not intended to be written to is a vector for security attacks, more systems are securing their read-only data.
尽管不能保证,但 const 不太可能破坏数组的二进制兼容性,因此共享库最终应该具有相同的布局。
请注意,对于单个 int 来说,这可能不是这种情况:
因为 TEST 是一个编译时常量。
Although there are no guarantees, the const is unlikely to break binary compatibility in the case of an array, so shared libraries should end up with the same layout.
Note this would likely not be the case for a single int:
because TEST is a compile-time constant.