C++值单例模式与auto_ptr

#include <iostream>
#include <memory>
using namespace std;

class Singleton
{
public:
    static Singleton* GetInstance()
    {
//        if (instance_ == nullptr)
//        {
//            instance_ = new Singleton;
//        }
//        return instance_;
        if(!instance_.get())
        {
            instance_ = auto_ptr<Singleton>(new Singleton);
        }
        return instance_.get();
    }

    ~Singleton()
    {
        cout << "~Singleton ..." << endl;
    }

private:
    // 禁止拷贝(只有声明,没有实现,要是有拷贝的操作,会直接报错)
    Singleton(const Singleton& other);
    Singleton& operator=(const Singleton& other);
    // 拷贝构造声明为私有,外部就不能构造对象
    Singleton()
    {
        cout << "Singleton ..." << endl;
    }
    // static Singleton* instance_;  // 这边使用智能指针,不然就必须手动释放instance_,在项目中,可能有很多地方调用,这样就很难控制在哪释放
    static auto_ptr<Singleton> instance_;
};

auto_ptr<Singleton> Singleton::instance_;

int main() {
    Singleton* s1 = Singleton::GetInstance();
    Singleton* s2 = Singleton::GetInstance();
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

// 输出
Singleton ...
Hello, World!
~Singleton ...

Noncopyable继承注意要点

class Noncopyable
{
protected:
    Noncopyable() {}
    ~Noncopyable() {}
private:
    Noncopyable(const Noncopyable&);
    const Noncopyable& operator=(const Noncopyable&);
};

class Parent : private Noncopyable
{
public:
    // 默认构造函数中,即使后面没有加上:Noncopyable(),也会自动调用基类的默认构造函数。但是拷贝构造函数就不一样。
    // 如果加上了: Noncopyable(),则基类必须要有: Noncopyable()的声明
    Parent() : Noncopyable()
    {

    }
    // 当你自己又重新定义了拷贝构造函数,则不会去调用基类的拷贝构造函数,这样基类的私有拷贝就会失效。这样就会被拷贝出来。
    // 所以这样的拷贝构造是不符合规范的
//    Parent(const Parent& other)
//    {
//
//    }

    // 下面是符合规范的拷贝构造函数(这样才能实现禁止拷贝)
    Parent(const Parent& other) : Noncopyable(other)
    {

    }
};

class Child : public Parent
{

};

int main() {
    Parent p1;
    Parent p2(p1);  // 要调用拷贝构造函数,Parent构造函数又调用Noncopyable的拷贝构造函数(私有且没有实现,所以会报错)

//    Child c1;
//    Child c2(c1);   // 也是同上的道理
    return 0;
}

自定义sizeof和内存对齐

#include <iostream>
using namespace std;

// 大小的宏
// 两个指针相减,得到的是相隔几个元素
#define sizeof_v(x) (char*)(&x+1) - (char*)(&x)
#define sizeof_t(t) ((size_t)((t*)0 + 1))

// 对齐
#define ALIGN(v, b) ((v+b-1) & ~(b-1))
class Empty
{

};
int main() {
    Empty e;
    int n;

    cout << sizeof_v(e) << endl;
    cout << sizeof_v(n) << endl;

    cout << sizeof_t(Empty) << endl;
    cout << sizeof_t(int) << endl;

    cout << ALIGN(3, 16) << endl;
    cout << ALIGN(31, 16) << endl;
    cout << ALIGN(0, 16) << endl;
    cout << ALIGN(4198, 4096) << endl;
    return 0;
}

// 输出
1
4
1
4
16
32
0
8192
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值