std::getenv() 在 main 函数返回后调用是否安全?

huangapple go评论67阅读模式
英文:

Is std::getenv() safe to call after main returns?

问题

以下是翻译好的部分:

标准是否保证std::getenv()std::setenv()具有与cout相同的访问保护?标准允许在main函数返回后,在静态对象的析构函数(和构造函数)中访问它们。

静态对象的构造函数和析构函数可以访问这些对象,从stdin读取输入或向stdoutstderr写入输出。

从阅读代码来看,似乎std::setenv()被调用时会操作全局变量(参考https://github.com/digitalocean/gnulib/blob/master/lib/setenv.c#L113)。因此,我想知道是否需要使用与coutcincerr相同的技巧,以使它们在程序关闭时仍然可以访问。

英文:

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 to stdout or stderr.

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.

答案1

得分: 4

cout及其类似物是C++中的命名空间作用域对象。因此,当main退出时,它们将被销毁。它们将按照相对于其他全局对象的销毁顺序被销毁,而您对这些对象绝对没有控制权。

因此,为了确保您可以在静态对象构造/析构函数调用期间与这些对象交互,标准要求实现确保这些对象保持有效且未被销毁。这个陈述是必要的,否则在静态对象构造/析构函数调用期间安全访问这些对象将是不可能的。

相比之下,getenv是一个函数,而不是一个对象。它不能被销毁。函数的行为完全由标准对其行为的定义确定,而且该行为必须始终发生。因此,除非标准规定在静态对象构造/析构函数范围内调用这些函数时具有不同的行为,否则它们将继续在这些情况下执行它们所声明的操作。

英文:

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.

huangapple
  • 本文由 发表于 2023年5月14日 23:13:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76248214.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定