On Feb 12, 7:54 pm, "Sam.Gun...@gmail.com" <Sam.Gun...@gmail.com>
wrote:
> Hi,
>
> I wish to share an object through a bunch of functions without
> declaring it globally. I have achieved this through the following
> function:
>
> VideoReceiver* getReceiver()
> {
> static VideoReceiver *vr = new VideoReceiver();
> return vr;
>
> }
>
> So, the first time it is called a new VideoReceiver object is created.
> Subsequent calls return this object (without creating new ones).
>
> E.g, All one needs to do to access the VideoReceiver is:
>
> function blah()
> {
> VideoReceiver vr = getReceiver();
> vr->update()
>
> //do blah
>
> }
>
> Are there any problems or issues I should be aware of using this type
> of code? Is it a no-no? I make multiple calls to getReceiver() each
> frame.
>
> It was originally a hack to get going but now that I've advanced a
> reasonable way I'm considering just leaving it, since it is currently
> working as expected.
>
> Thanks for any advice or suggestions,
> Sam.
The function is fine except I would return
a reference to the object - this way there
is no chance of anyone deleting the object
by accident.
Also, as another poster said, there's no
need for dynamic allocation - just use a
static local.
But for multi-threaded programs, the construction
of the object is not safe. See, for instance,
Modern C++ Design for a good discussion on this.
Some times, this is ok. For instance, I use a
static local log object inside a function. But
I make sure it is used (and hence constructed)
in the main thread before any other threads are
invoked.
|