quote:Original post by dcosborn
I don''t understand how references subvert const correctness. If you need constant references, just make them constant. If you mean that non-const references can be made to point constant variables, then thats not really an issue since you can do the same sort of thing with const_cast if you want, but any sensible person would avoid such a thing.
As for code size, I''d hope that a compiler would optimize it away.
Consider for a moment this code:
struct A { float x; float y; float z;};struct B { B() : a(x), b(y), c(z) {} float x; float y; float z; float & a; float & b; float & c; void assign_x(float v); void assign_a(float v);};void B::assign_x(float v) { x = v; }void B::assign_a(float v) { a = v; }int main(int, char **) { std::cout << "sizeof(A): " << sizeof(A) << std::endl; std::cout << "sizeof(B): " << sizeof(B) << std::endl; const B const_b; const_b.a = 5.0; //const_b.x = 5.0; return 0;}
When compiled an run with MSVC .NET 2003, in release mode with full optimization, sizeof(B) is twice the value of sizeof(A). Meaning data size is greater when using references.
When I take a look at the dissassembly for B::assign_a() versus B::assign_x() there''s see an extra mov instruction in the generated assembly code. Which means code size is greater.
What''s more alarming is that I was able to assign to the value of a const object, because the references are there adding a nasty layer of indirection. No warning message. No red-flag from a const_cast. Just a straight up alteration to a const object. I might also add that it also subborns the DFA pass that many compilers perform when doing code generation.