On (23 Mar 97) Jason Hendriks wrote to Cliff Rhodes...
CR> class A {
CR> private:
CR> int array[100];
CR> };
JH> Is there a way to make the private members static in the class itself,
JH> even if an objected has automatic (dynamic) duration?
Yes, but if you do, there's only one copy of the variables to be shared
by all instances of the class. You don't do this to save stack space -
you do it because the design of the class requires it. For instance, if
you wanted to keep track of the total number of instances of a class
that existed at a given time, you could do something like this:
class counted {
static int instances;
public:
counted() { instances++; }
~counted() { instances--; }
ostream &print(ostream &s) {
s << instances;
}
};
`instances' is a single variable that's shared across all instances of
the class, so each time you construct a new object of the class, you're
incrementing the same variable.
If you simply want to save stack space, you generally do so by
allocating the class' memory on the free store during construction.
E.g. a string class will typically contain a length, and a pointer to
the actual string. When you do something like this:
myfunc() {
string x("This is a very long string that won't be on the stack"
"but will be allocated from the free store instead.");
// ...
`string' will typically look vaguely like this:
class string {
unsigned length;
char *contents;
public:
string(char const *initial) {
length = strlen(initial);
contents = new char[length];
memcpy(contents, initial, length);
}
// MUCH more elided...
};
This way, when you create a string on the stack, you use only a small,
specific amount of stack space, rather than a large amount varying with
the length of the string you're working with. Further, most
implementations of strings are likely to use a copy-on-write setup that
allows you to have many copies of the same string occupy the same
storage.
Later,
Jerry.
... The Universe is a figment of its own imagination.
--- PPoint 1.90
---------------
* Origin: Point Pointedly Pointless (1:128/166.5)
|