Re: question re. usage of "static" within static member functions of
a class
On 7 Set, 07:50, Shrikumar <s.sharm...@gmail.com> wrote:
On Sep 7, 10:24 am, "Chris M. Thomasson" <n...@spam.invalid> wrote:
"ssb" <s.sharm...@gmail.com> wrote in message
news:97dc452a-f6a5-4a77-9a9c-ea8491d37e40@e4g2000prn.googlegroups.com...
Hi All,
During a code review, I found the following lines of code:
[...]
The "instance" method was implemented as follows:
Data* Data::instance()
{
static Data* model = new Data();
return model;
}
I have never come across a situation where a pointer was set to static
in such a case. Is this valid?
It's a singleton.
What are the potential pitfalls in such programming practices?
The storage that `model' points to will never be destroyed, also it's not
thread-safe.
Thanks for the quick reply, Chris.
I was wondering about the static pointer part - I have always seen
static variables (that are not pointers) in use, but never a static
pointer (even if it is to guarantee that the singleton always returns
the *same* instance of the Class). Is a static pointer (as in the
instance function) a perfectly valid use of the "static" keyword?
I think it is. After all, that pointer should be initialized only once
and operator new should be called only once - the first time the
method is invoked - but this confirmation should be implied into
Chris' sentence: "It's a singleton".
As usual, there are many ways to achieve the same target while
programming.
But was that coder really meant to implement it that way?
The implementation you reviewed:
-------
Data* Data::instance()
{
static Data* model = new Data();
return model;
}
-------
Gives the same result[1] of:
-------
Data* Data::instance() {
static Data model;
return &model;
}
-------
[1] Well, more or less "the same result". My mod could be preferred
because it doesn't use dynamic memory, but in order to avoid some
client to see the pointer as something that could/should be deleted
sooner or later, the code could return the object as a reference.
Changing the method declaration, it could be implemented it in this
way:
-------
Data& Data::instance() {
static Data model;
return model;
}
-------
or also as:
-------
// data.cpp
#include "data.h"
namespace {
Data model;
}
Data& Data::instance() {
return &model;
}
-------
Which doesn't use the "static" keyword at all.
But of course, being a code-reviewer, you should already know all the
above.
Let's say I'm taking the chance to see if _I_ got it right, showing my
code for review here in clc++ ;-)
Cheers,
Francesco
PS: please do not top-post the next time, moreover because it messes
up subsequent replies to your top-posting.