Re: Heap stack Class questons
On Sat, 5 Jun 2010 08:59:51 -0400, "RB" <NoMail@NoSpam> wrote:
And to be complete in my former
comments, a static var could be initialized in the constructor
"if it was not a class member" which would make it a just
another global var with the exception of having only file
scope as you pointed out to me.
A couple of things. The use of "static" to confer "file scope" is
deprecated. Its replacement is the anonymous namespace, e.g.
namespace {
int x;
class Y
{
...
};
}
Note that you can put classes inside the anonymous namespace, which is very
important when defining classes for use inside just one file. It avoids
very weird problems when there are multiple such classes with the same
name. The "static" keyword never could deal with these violations of the
One Definition Rule (ODR).
Second, it usually wouldn't make sense to initialize a static object inside
a constructor for a class X. The reason of course is that the static object
would be initialized every time an X was created. However, I guess it could
potentially make sense to do something like:
namespace {
int x;
int y;
int z;
class Initializer
{
public:
Initializer()
{
// Do some complicated initialization of x, y, and z
// that is inconvenient to do with the normal syntax
// int x = whatever1;
// int y = whatever2;
// int z = whatever3;
}
};
Initializer init;
}
Note that only one Initializer is ever created. Note also that within a
single translation unit, initialization of namespace scope objects proceeds
from top to bottom. While x-z are ints, notionally they are initialized,
and if they had class type, and the class had a ctor, the ctor would be run
before the one for "init". Therefore, it's important that "init" be
declared last, after all the variables it's going to "initialize" (really
it's assignment, not initialization).
--
Doug Harrison
Visual C++ MVP