Does the standard guarantee that std::getenv()
and std::setenv()
have the same access protections as cout
? For which the standard allows access after main returns, in the destructor (and constructor) of static objects
Constructors and destructors for static objects can access these objects to read input from
stdin
or write output tostdout
orstderr
.
From reading code that seems like it would be called from std::setenv()
, it seems like it operates on a global variable (as per https://github.com/digitalocean/gnulib/blob/master/lib/setenv.c#L113). So curious if it's required to use the same tricks as cout
, cin
, and cerr
to make them accessible on shutdown.
cout
and its ilk are namespace-scoped objects in C++. As such, when main
exits, they will be destroyed. And they will be destroyed in an order relative to the destruction of other global objects over which you have absolutely no control.
Therefore, to ensure that you can interact with these objects during static object constructor/destructor calls, the standard requires that the implementation ensure that these objects remain valid and undestroyed. This statement is necessary, as otherwise it would be impossible to access those objects safely during static object constructor/destructor calls.
By contrast, getenv
is a function, not an object. It cannot be destroyed. The behavior of a function is determined entirely and only by the standard's definition of its behavior, and that behavior must always happen. Therefore, unless those functions are stated by the standard to have different behavior when called within the scope of static object construction/destruction, they will continue to do what they say they do in those circumstances.