c++ - Why does this let me get a non-const pointer to a field of a const object? -
i compiling snippet clang++ ("apple clang version 4.1 (tags/apple/clang-421.11.66) (based on llvm 3.1svn)"), although gcc fine:
#include <iostream> struct foo { typedef unsigned char memorypage[0x1000]; memorypage* pages; foo() { pages = new memorypage[16]; } ~foo() { delete[] pages; } unsigned char* pointertooffset(unsigned offset) const { homecoming pages[offset >> 12] + (offset & 0xfff); } }; and compiles fine. i'm surprised because pointertooffset has const qualifier, homecoming value non-const unsigned char pointer.
i ensure returns values within memory range of pages, means actual non-const pointer actual const object data, , not dangling reference eventual re-create of target array.
the result, seems, const-incorrect method compiles nonetheless. makes legal?
in simplest words variable,
memorypage* pages; will become as:
memorypage* const pages; // , not `const memorypage*` // ^^^^^ inside const function: pointertooffset().
the meaning of const class variable cannot modified. create pages unmutable entity, const has apply on pages , not contents pointed it. that's why there no error in compiler.
for sake of understanding, simpy seek declaring pages const memorypage* , notice compiler emit error in non-const functions.
c++ const
No comments:
Post a Comment