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

Vincent Penquerc'h Vincent.Penquerch at artworks.co.uk
Mon Mar 31 18:10:02 UTC 2003


> 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?
> The interface is no longer a safe one.

You can allocate Wiring as a dynamic object:

Light::Light(): wiring(new Wiring()) {}
Light::~Light() {delete wiring;}

and then:

struct Wiring: public Refcounted {
};

struct Refcounted {
protected:
  Refcounted(): refs(1) {}
  virtual ~Refcounted() {if (!--refs) delete this;}
private:
  size_t refs;
};

This way your wiring object won't get destroyed if it's still
used when the light is deleted. Refcounted can be a little tricky,
you have to handle assignment operators, etc. It can also be a
bit inefficient if you call these a lot.

-- 
Vincent Penquerc'h 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.linux.org.au/pipermail/tuxcpprogramming/attachments/20030331/2e1a202d/attachment.htm 


More information about the tuxCPProgramming mailing list