I came across the following rule (3.7.1/2 N3797):
If a variable with static storage duration has initialization or a destructor with side effects, it shall not be eliminated even if it appears to be unused, except that a class object or its copy/move may be eliminated as specified in 12.8.
Is it true that, if we declare a variable with static storage duration, having constructor or destructor with side-effect, then the memory will allocate for that variable even if it is unused?
In particular, I'm trying to experiment with the following code:
#include <csignal>
#include <iostream>
#include <cstdlib>
using std::cout;
struct data_member
{
data_member(){ cout << "data_member\n"; }
~data_member(){ cout << "~data_member\n"; }
};
struct Y
{
static data_member m;
Y(){ cout << "Y\n"; }
~Y(){ cout << "~Y\n"; }
};
Y y;
int main()
{
}
Why does data_member object not constructed in the example?
Well, that's what the standard says, so ... yes.
As always, there's the as-if rule, allowing a compiler to do practically anything, as long as the net effect is the same. I could imagine that if the class is huge data-wise, but the constructor and destructor (and anybody else) do not access that data, the compiler could just call the constructor and destructor in the proper order, without leaving space for the unused data.
As for your example, you're declaring Y::m
, but you never define it. So it doesn't exist. If you tried to access it, you'd get a linker error.