> struct foo{ int const x; };
> void some_func(foo*);
> int bar() {
> foo f { 123 };
> some_func(&f);
> return f.x;
> }
> bar will always return 123. The compiler may generate code that actually accesses the object. But the object model does not require this. f.x is a const object (not a reference/pointer to const), and therefore it cannot be changed.I like to think I know quite a bit about C++, but I don’t get this at all. Why is f.x a const object even when accessed through a non-const variable? f isn’t const; there’s no const_cast here. At first glance, this looks like a bug in the spec, roughly like confusing
int const *p
(pointer to const) with int const *const p
(const pointer to const). Only the latter will always point to the same thing.What am I missing?
(Edit: Since it’s a bit hidden in the SO question, the idea is that some_func does something like this:
void some_func(foo *f) {
new(f) foo { 42 };
}
Note that there’s no const_cast here, and f’s storage isn’t const, so this isn’t UB to the best of my knowledge.BTW, in case it’s not obvious, it’s not all that helpful to reply to the question why the spec is a certain way by tautologically repeating the spec.)
(Edit 2: Unfortunately also very typical for C++ discussions, I just love how people think that C++ confusing me must mean that I’m dumb, and then condescendingly post a wrong answer. Rule of thumb: If you’re confident in your ability to understand C++, you don’t understand it very well.)