简体   繁体   中英

What is the rationale for paragraph 12.1.14 of the C++ standard?

This is from C++11.

During the construction of a const object, if the value of the object or any of its subobjects is accessed through a glvalue 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) { int i = cobj.c * 100; // value of cobj.c is unspecified cptr->c = 1; cout << cobj.c * 100 // value of cobj.c is unspecified << '\\n'; } 

end example ]

And why does it only apply to const objects?

To truly understand the rationale you would need to correspond with the members of the Committee, or at least read the relevant discussion. I can't help you with that.

The purpose that this serves in context is to place more stringent restrictions on the construction of const objects than apply generally. The rules that apply generally are covered at some length in S12.7, and broadly they focus on the lifetime of the object. They do not forbid aliasing, for example.

The restrictions on const objects will allow implementers more aggressive optimisation strategies. For example, an object might be constructed at translate time, or constructed only once by hoisting it out of a loop, or optimised away entirely. Since const objects don't change, compilers do not ordinarily have to worry about aliasing but (as shown in the example code) in this particular case they would.

I can't help thinking there must be a case where this rule prevents some other externally-visible breach of the const requirements. The example given is not such a case, and I've not been able to find one. Perhaps some other contributor can assist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM