Morpheus wrote:
Hello,
Say I have a class with a member...
char mId;
Whenever an object is created, I want to assign an incrementing
character to this member, for instance the first would be A, then B, C,
D, E etc....
Unless I create a singleton class as a provider for this, the only way
I can think of tracking the last ID would be to use a global variable.
Is there a way to do this without either of the above?
Background: We are in the middle of renovating the entire structure of
our software. A customer needs the current build for other fixes
however at the moment I can not access the methods of a particular
class. A global would give me a temporary workaround to access the
member directly... This is probably not enough info to help out but...
(The actualy member is not a char, but for the purpose of this
question it will suffice.
The member type is more important then you may think.
If the type is NOT a POD type, and you have other global comlex types
trying to access them, you're going to run into problems in that the ID
types may or may not be initialized when called before main() starts.
That's because the C++ standard does not garantee the order of
construction for complex objects in multiple translation units.
Global POD types are garanteed to be initialized before global non-POD
types.
So if your ID type is an int type, and you have a global foo type that
tries to access the ID, then you should be safe. But if your ID is a
static std::string member, and you have a global foo type that tries to
access the ID (before main() starts), then you're going to run into
problems, because you have no garantee that the ID variable has been
initialized.
You also have a similar related problem when your application tries to
exit. You could have a static member variable (static std::string ID)
who's destructor has been called, and then have a global type try to
access it after it's been destroyed.
One easy safe workaround solution is to use a function that stores the
complex object as a local static variable.
std::string& GetID()
{
static std::string *strID = new std::string();
return *strID;
}
IAW C++ standard this would garantee that the object would be created
when fetching it from multiple translation (modules) units (via global
object).
You can also use a method MS used with it's CString class for default
emtpy CString's, but I'm not sure how portable that method would be.