c++11使用智能指针来代替new delete

一,智能指针的特点
1.使用后内存能够自动释放,不需要手动进行释放
2控制指针的所有权进行共享或者师独占
二,常用的智能指针
unique_ptr:独占指针,只能有一个变量指向这个地址,不能多个变量指向这个内存地址,创建了一个智能指针之后不能进行拷贝和复制,但是可以转移所有权
share_ptr:共享指针,多个变量指向同一个内存地址,使用了引用计数的方法
weak_ptr:解决循环引用的问题
三,使用new delete的场景,比如下面的这段代码,经常在项目中我们会这么用

    OprationFactory* addfac = new AddFactory();
	OprationFactory* subfac = new SubFactory();
	Opration* addnum = addfac->CreateOpration();
	Opration* subnum = subfac->CreateOpration();

	int a = addnum->GetResult(4, 3);
	int b = subnum->GetResult(4, 3);
	printf("a的值%d\n",a);
	printf("b的值%d\n", b);
	delete addfac;
	delete subfac;
    return 0;

要手动进行释放

四,使用只能指针在项目中代替new delete,实现RAII的程序机制,初始化的时候获取资源,变量销毁的时候资源也进行释放

#pragma once
#include <iostream>
class CZoo
{
public:
	CZoo();
	explicit CZoo(std::string data);
	~CZoo();
public:
	virtual  void Printname();
private:
	std::string name;
};

class Bear :public CZoo
{
public:
	Bear();
	~Bear();
	Bear(std::string zooname, std::string bearname);
public:
	void Printname();
private:
	std::string name;
};
#include "CZoo.h"

CZoo::CZoo()
{

}

CZoo::CZoo(std::string data) :name(data)
{

}

CZoo::~CZoo()
{

}

void CZoo::Printname()
{
	std::cout << name << std::endl;
}


Bear::Bear()
{

}

Bear::~Bear()
{

}

Bear::Bear(std::string zooname, std::string bearname) :name(bearname), CZoo(zooname)
{

}

void Bear::Printname()
{
	std::cout << name << std::endl;
}



#include <iostream>
#include "CZoo.h"
int main()
{
    std::shared_ptr<CZoo> p_czoo;
   // p_czoo = std::make_shared<Bear>("jack","littlebear");
    p_czoo = std::make_shared<Bear>();
    p_czoo.get()->Printname();
   // std::cout << "Hello World!\n";
}

Tips:给只能指针分配对象的时候,只需要把对象类型写入到<>中就行,如果需要初始化的变量在()中写入变量
p_czoo = std::make_shared();

五,智能指针和new 结合使用

int main()
{
	std::shared_ptr<int> sp1(new int(0));
	std::shared_ptr<int> sp2(sp1);
	std::shared_ptr<int> sp3(new int(1));
	*sp2 = 2;
    sp3 = sp1;
	cout << *sp3 << endl;
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值