If I have a class called Test ::
class Test
{
static std::vector<int> staticVector;
};
when does staticVector get constructed and when does it get destructed ?
Is it with the instantiation of the first object of Test class, or just like regular static variables ?
Just to clarify, this question came to my mind after reading Concepts of Programming Languages (Sebesta Ch-5.4.3.1) and it says ::
Note that when the static modifier appears in the declaration of a variable in a class definition in C++, Java and C#, it has nothing to do with the lifetime of the variable. In that context, it means the variable is a class variable, rather than an instance variable. The multiple use of a reserved word can be confusing particularly to those learning the language.
did you understand? :(
I want to write some text about initializaton too, which i can later link to.
First the list of possibilities.
std::terminate
is called. Examples:
The following program prints A(1) A(2)
struct A {
A(int n) { std::printf(" A(%d) ", n); }
};
A a(1);
A b(2);
And the following, based on the same class, prints A(2) A(1)
extern A a;
A b(2);
A a(1);
Let's pretend there is a translation unit where msg
is defined as the following
char const *msg = "abc";
Then the following prints abc
. Note that p
receives dynamic initialization. But because the static initialization (char const*
is a POD type, and "abc"
is an address constant expression) of msg
happens before that, this is fine, and msg
is guaranteed to be correctly initialized.
extern const char *msg;
struct P { P() { std::printf("%s", msg); } };
P p;
Example: The following program prints 0 1
:
struct C {
C(int n) {
if(n == 0)
throw n;
this->n = n;
}
int n;
};
int f(int n) {
static C c(n);
return c.n;
}
int main() {
try {
f(0);
} catch(int n) {
std::cout << n << " ";
}
f(1); // initializes successfully
std::cout << f(2);
}
In all the above cases, in certain limited cases, for some objects that are not required to be initialized statically, the compiler can statically initialize it, instead of dynamically initializing it. This is a tricky issue, see this answer for a more detailed example.
Also note that the order of destruction is the exact order of the completion of construction of the objects. This is a common and happens in all sort of situations in C++, including in destructing temporaries.
Exactly like regular static (global) variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With