Making a struct field constant, when this struct is imported to a particular Cpp files

Dave Korn dave.korn.cygwin@googlemail.com
Thu Nov 12 21:12:00 GMT 2009


  First point: the main gcc list is for discussions about programming the
internals of the compiler itself; discussions about how to /use/ the compiler
should go to the gcc-help list, so I've redirected this reply.

  Secondly ...

ansis atteka wrote:

> I already have approach, but I am not quite sure whether it is
> safe(especially regarding the compiler optimizations). Below are uplaoded
> files.
> 
> In this case util.cpp is not allowed to edit S.y contents, while rw.cpp is
> allowed to do that. File h.hpp contains the struct which is customized at
> the preprocessor execution time by looking at the READONLY define.


  No, this is not safe.  Trust me, I speak from experience, having made and
had to debug the same mistake myself many years ago!  In the modules that see
the field as 'const', the compiler will feel free to load it into a register
in any function that accesses it, and if the register is saved across function
calls, it will feel free to save the value in that register across function
calls and keep using it after the function call, safe in the knowledge that
the value of the field in the actual struct in memory cannot have changed
because it is const.  But if that function call is to a function in another
module (which was compiled without the const) then that function call could
change the field in the struct in memory, and the compiler would never know
that the value it has cached in a register in the calling function is now out
of date.

  Long story short: don't do it.  Use C++ member visibility and make the
functions that want to access it members or friends, or some other robust
technique like that(*).

    cheers,
      DaveK
-- 
(*) - I have left this as a footnote because it should not be done, but what I
did years ago was to hack my way around it by making the variable 'const
volatile'.  This is an ugly and pessimal hack at best, and there's no need to
resort to it in C++.  The whole thing was in fact just a convenient step in
refactoring a massive legacy application that had a whole bunch of globals
that I needed to get under control and make sure they were all only ever
changed through accessors, so that as a second step I could then add getters
and hide all the global declarations away for good, removing the const hack in
the process.



More information about the Gcc-help mailing list