是函数本地静态默认或价值初始化

Are function local statics default- or value- initialized?

本文关键字:初始化 默认 静态 函数      更新时间:2023-10-16

我使用的一种常见模式是:

const string& GetConstString() {
  static const auto* my_string = new string("useful const string");
  return *my_string;
}

[这不是泄漏!查看此视频]这解决了许多终生问题。string可以用非平凡的DTOR代替任何类型。

如果您的类型具有默认的ctor&琐碎的dtor,你可以简单地做

const MyType& GetConstMyType() {
  static MyType my_type;
  return my_type;
}

我正在与一个具有默认CTOR和TRIVIAL DTOR的班级合作。我想知道该类是默认或值初始化的。事实证明,对于班级类型并不重要。因此,这成为一个学术问题[例如,如果您有这个课程的数组]。

但会默认或价值初始化吗?

我看不到指针解决了什么生命周期。实际上,它添加了一个:内存泄漏。

you 应该使用第二版,它将(最终(像没有static关键字一样初始化。

const string& GetConstString()
{
   // Initialised on first use; destroyed properly on program exit
   static const std::string my_string("useful const string");
   return my_string;
}

这具有不双动态分配的额外好处。

更一般地,使用哪种特定类型的初始化类型取决于您在代码中写的内容。

根据"轨道上的轻度比赛"的评论,答案是:

将使用与非静态对象完全相同的规则初始化静态对象/值。