Effective C++(总是初始化)


author:

  • luixiao1223
    title: 使用前初始化

C part of C++

问题:这部分是不保证被初始化。要想完全记住那些初始化了,哪些没有是很困难的。

解决:在使用前都初始化

如何初始化类成员

  1. C++中成员变量的初始化发生在构造函数之前
  2. 最好总是会用初始化列表来初始化,可以避免初始化后再赋值
ABEntry::ABEntry(const std::string& name, const std::string& address, const std::list<PhoneNumber>& phones)
    : theName(name), theAddress(address), thePhones(phones), numTimesConsulted(0)
{}
  1. 参数化列表的初始化顺序,是按照类里面声明顺序执行的
  2. 如果有很多构造函数,那么都写初始化列表可能会很繁琐。那么可以把赋值和初始化开销不大的一部分内容写道一个private函数中执行。可以节约代码量

non-local static 对象的初始化

范围

  1. global对象
  2. 定义于namespace、class内、函数内和file作用域内被声明为static的对象。
  3. 函数内的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;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值