我使用的常见模式是:
const string& GetConstString() {
static const auto* my_string = new string("useful const string");
return *my_string;
}
Run Code Online (Sandbox Code Playgroud)
[这不是泄漏!观看此视频]
这解决了许多终身问题.string可以用任何具有重要dtor的类型替换.
如果你的类型有默认的ctor和普通的dtor,你可以这样做
const MyType& GetConstMyType() {
static MyType my_type;
return my_type;
}
Run Code Online (Sandbox Code Playgroud)
我正在和一个有默认ctor和普通dtor的班级一起工作.我想知道这个类是默认值还是值初始化.事实证明,它对于类类型并不重要.所以这成了一个学术问题[例如,如果你有这个类的数组].
但它是默认值还是值初始化?
我没有看到指针解决的生命周期问题.实际上,它增加了一个:内存泄漏.
您应该使用第二个版本,它将(最终)初始化,就像没有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;
}
Run Code Online (Sandbox Code Playgroud)
这具有不是双动态分配的额外好处.
更一般地说,使用哪种特定类型的初始化取决于您在代码中编写的内容.