C++11 §12.1/14:
During the construction of a const object, if the value of the object or any of its subobjects is accessed through an lvalue that is not obtained, directly or indirectly, from the constructor’s this pointer, the value of the object or subobject thus obtained is unspecified. [Example:
struct C; void no_opt(C*); struct C { int c; C() : c(0) { no_opt(this); } }; const C cobj; void no_opt(C* cptr) { // value of cobj.c is unspecified int i = cobj.c * 100; cptr->c = 1; // value of cobj.c is unspecified cout << cobj.c * 100 << '\n'; } Compiling the above example outputs 100. My question is why is the value of cobj.c should be unspecified when the initialization list sets it to 0 before entering constructor? How is this behavior different in case if a non-const object is used?
cobj.cis accessed beforecobjis fully constructed. It seems to me that even for non-const objects this action is dubious.cptris obtained fromthis, but the quote says "not obtained" (how else)? Also, this quote means constructor body shall not modify any members, or else behavior will be unspecified for const objects?cobjbefore the constructor returns. The read access is the offending one.