Robert A <
robert.a...@gmail.com> writes:
> Say I have a global variable `thing` with certain properties:
>
> thing.foo
> thing.bar
>
> If I want `thing` to be lazily initialized on first use, I could turn
> all my uses of it into a function...
>
> thing().foo
>
> Thing &thing() {
> if (!_instance) { _instance = new Thing; }
> return *_instance;
> }
>
> Is there a way to get the same effect without the parens? Ie, so I can
> say `thing.foo`. I'm craving syntactic sugar.
If you are prepared to forego the dot and use -> instead, this pattern
class Thing {
struct ActualThing {
int foo;
int bar;
} actual_thing;
public:
const ActualThing *operator->() {
// Do what you like here to set up 'actual_thing'.
return &actual_thing;
}
};
gives you a function call at the time the member is accessed. You
could, as I think you were trying elsewhere, have a private pointer to
an 'actual_thing', and use that to decide if it needs to be allocated,
but that just means you need more machinery. There are lots of simpler
ways to ensure that 'actual_thing' gets initialised only once.
But I am tempted to ask what you are really doing. It looks odd to make
an object before the members can be usefully initialised.
--
Ben.