特殊类的设计

目录

 1.传值返回

 2.final

 3.单例模式

【饿汉模式】

 【懒汉模式】

4.设计一个类,只能在堆/栈上创建对象


 1.传值返回

 右值走移动构造

 2.final

 3.单例模式

静态的必须在类外初始化

【饿汉模式】

在main之前就创建对象

 【懒汉模式】

C++11懒汉模式可以这么写,不用gc专门析构等

优缺点

 

单例对象的回收

class Singleton
{
public:
    ...

    // 单例对象回收
	    class GC
	    {
	    public:
		    ~GC()
		    {
		    	DelInstance();
		    }
	    };	

        static GC _gc;        //这里会调用析构

    ...

private:
    static Singleton* _ins;   //内置类型不会调用析构

    ...

}

4.设计一个类,只能在堆/栈上创建对象

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <math.h>
#include <unordered_set>
#include <unordered_map>
using namespace std;

class HeapOnly
{
public:
	static HeapOnly* CreateObj(int x = 0)
	{
		HeapOnly* p = new HeapOnly(x);//堆上
		return p;
	}

private:
	HeapOnly(int x = 0)
		:_x(x)
	{}

	HeapOnly(const HeapOnly& hp) = delete;
	HeapOnly& operator=(const HeapOnly& hp) = delete;

	int _x;
};

class StackOnly
{
public:
	static StackOnly CreateObj(int x = 0)
	{
		return StackOnly(x);
	}

	StackOnly(StackOnly&& st)
		:_x(st._x)
	{}

private:
	StackOnly(int x = 0)
		:_x(x)
	{}

	StackOnly(const StackOnly& st) = delete;

	int _x;
};

int main()
{
	//HeapOnly a;无参构造不可访问
	static HeapOnly c;
	HeapOnly* a = HeapOnly::CreateObj();
	HeapOnly* b = a;
	//HeapOnly d();函数
	//HeapOnly e(*a);拷贝构造不可访问
	//HeapOnly f = *a;

	//StackOnly g;无参构造不可访问
	static StackOnly h;
	//StackOnly i = new StackOnly;

	//StackOnly j = StackOnly::CreateObj();
	//static StackOnly k = j;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值