[LC++]Big objects in a class interface: good techniques?

Torsten Rennett Torsten at Rennett.de
Mon Mar 31 15:30:02 UTC 2003


Hi Mark,

Dr Mark H Phillips wrote:
> I could go:
> 
>    ...
>    Wiring const& wiring() const {return wiringVt;}
>    ...
> 
> but then this has memory management problems.  It is giving out the
> address of an internal object.  What if this address becomes invalid?

If the solution 

   struct Light
   {
      Wiring wiring;
      ...
   };

would work for you, then in every case the following would also do
without memory management problems:

   struct Light 
   {
       const Wiring &wiring() const	{ return _wiring; }
       Wiring &wiring()			{ return _wiring; }

     private:
       Wiring _wiring;
       ...
   };

This is because in both cases the Wiring-Object lives as long as the
Light-Object does.


> The interface is no longer a safe one.

The interface IS safe, but you must ensure that you reference
Light::_wiring only as long as the corresponding Light-Object exists.
That's not a matter of your interface, but a constraint you have with
every reference/pointer.


> So what is the solution?!

If you only need to have read access, I would use:

   struct Light 
   {
       const Wiring &wiring() const	{ return _wiring; }

     private:
       Wiring _wiring;
       ...
   };

If you need read/write access AND you can't think of a later situation,
where you have to control the access to wiring (e.g. on-demand
creation), then I would simply use: 

   struct Light
   {
      Wiring wiring;
      ...
   };


> P.S. With the solution:
> 
>    ...
>    Wiring const& wiring() const {return wiringVt;}
>    ...
> 
> will the inlining of the compiler get rid of the extra pointer
> reference here?  Ie, will it compile it as effectively:
> 
>   ...
>   Wiring const wiringVt;
>   ...

Yes, I think so, but I'm not sure. May be this depends on the compiler
and optimization flags. To be sure, have a look at the generated
assembler code :-(  Hi, Carlo, I think you know the right answer ;-)

BTW, I would not even spend a second about thinking how to optimize one
indirection! 

Torsten

--
Ingenieurbuero RENNETT      -- innovative Software-Entwicklung --
Torsten Rennett              
Ludwig-Thoma-Weg 14         E-Mail:     mailto:Torsten at Rennett.de
D-85551 Heimstetten         Telefon:              +49-89-90480538




More information about the tuxCPProgramming mailing list