author:
- luixiao1223
title: 使用前初始化
C part of C++
问题:这部分是不保证被初始化。要想完全记住那些初始化了,哪些没有是很困难的。
解决:在使用前都初始化
如何初始化类成员
- C++中成员变量的初始化发生在构造函数之前
- 最好总是会用初始化列表来初始化,可以避免初始化后再赋值
ABEntry::ABEntry(const std::string& name, const std::string& address, const std::list<PhoneNumber>& phones)
: theName(name), theAddress(address), thePhones(phones), numTimesConsulted(0)
{}
- 参数化列表的初始化顺序,是按照类里面声明顺序执行的
- 如果有很多构造函数,那么都写初始化列表可能会很繁琐。那么可以把赋值和初始化开销不大的一部分内容写道一个private函数中执行。可以节约代码量
non-local static 对象的初始化
范围
- global对象
- 定义于namespace、class内、函数内和file作用域内被声明为static的对象。
- 函数内的static对象为local static其他的为non-local static
static对象在main结束后开始析构
如何保证出力不同文件中的static对象的初始化顺序
问题:如果B文件调用了A文件中定义的static对象。但是A文件的static对象还没有初始化好。就会出现问题。编译器是不保证这个顺序的。
解决:每个static对象使用一个函数包裹起来。返回对象的引用
class FileSystem
{
// ...
};
FileSystem& tfs() {
static FileSystem fs;
return fs;
}
class Directory
{
//...
};
Directory::Directory( params )
{
//...
std::size_t disks = tfs().numDisks();
//...
}
Directory& tempDir()
{
static Directory td( params );
return td;
}
注意问题,多线程问题。
多线程单例
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
mutex mu;//线程互斥对象
class Singleton_Hungry
{
private:
Singleton_Hungry()
{
cout << "我是饿汉式,在程序加载时,我就已经存在了。" << endl;
}
static Singleton_Hungry* singleton;
public:
static Singleton_Hungry* getInstace()
{
return singleton;
}
};
//静态属性类外初始化
Singleton_Hungry* Singleton_Hungry::singleton = new Singleton_Hungry;
class Singleton_Lazy
{
private:
Singleton_Lazy()
{
cout << "我是懒汉式,在别人需要我的时候,我才现身。" << endl;
}
static Singleton_Lazy* singleton;
public:
static Singleton_Lazy* getInstance()
{
if (NULL == singleton)
{
mu.lock();//关闭锁
if (NULL == singleton)
{
singleton = new Singleton_Lazy;
}
mu.unlock();//打开锁
}
return singleton;
}
};
Singleton_Lazy* Singleton_Lazy::singleton = NULL;