views:

175

answers:

3

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.

+2  A: 

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.

Mark Ransom
A: 

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:

struct Test
{
    static int const TEST;
};
int const Test::TEST = 7;

because TEST is a compile-time constant.

James Hopkin
+1  A: 

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.

James Curran