是函数本地静态默认或价值初始化
Are function local statics default- or value- initialized?
我使用的一种常见模式是:
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;
}
这具有不双动态分配的额外好处。
更一般地,使用哪种特定类型的初始化类型取决于您在代码中写的内容。
根据"轨道上的轻度比赛"的评论,答案是:
将使用与非静态对象完全相同的规则初始化静态对象/值。
相关文章:
- 初始化具有非默认构造函数的std::数组项的更好方法
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 副本初始化的默认模板参数推导
- 使用 std::分配器在 constexpr 中进行默认初始化
- 在C++中使用默认构造函数初始化对象的不同方法
- 强制使用默认构造函数对成员进行未初始化的声明
- 使用默认构造函数初始化对象的不同方法
- 在没有默认构造函数时使用垃圾数据初始化对象
- 为什么对象默认初始化,但基元不在C++?
- 默认参数和空列表初始化
- 为什么std::atomic的默认构造函数不默认初始化底层存储值
- C++中未初始化成员布尔变量的默认值是多少?
- 两个成员,在Base中默认初始化,可能在Derived中非默认初始化
- 默认初始化无法正常工作
- 如何用默认值0或-1初始化unordered_set
- C++11 默认类成员初始化与初始值设定项列表同时
- 使用聚合初始化模拟默认函数参数是否存在任何陷阱?
- 初始化在类类型 #define 中定义的非静态成员数组,不带默认 ctor
- 在皮条类中初始化默认值的最佳位置
- 值初始化:默认初始化或零初始化