[C/C++标准库]_[初级]_[使用auto_ptr智能指针]

本文介绍了在C/C++编程中,如何利用auto_ptr智能指针来管理类对象指针的生命周期。特别是在函数内部,当需要在函数调用结束后自动销毁传入的对象时,auto_ptr能提供方便。不过需要注意的是,auto_ptr不适用于跨函数传递。
摘要由CSDN通过智能技术生成


场景:

1.在函数里如果使用了外边传进去的类对象指针,如果这些对象需要在函数完成调用时自动销毁,这时候可以使用auto_ptr.帮你管理类对象指针的生命周期。

2.auto_ptr只在同一个函数里使用,不要传递.


#include <iostream>
#include <string>
#include <memory>

using std::cout;
using std::endl;

class A
{
	public:
		A()
		{
			cout << "A" << endl;
		}
	~A()
	{
		cout << "~A" << endl;
	}
	int i_;
};

int main(int argc, char *argv[])
{
	cout << "begin" << endl;
	
	A* a = new A();
	cout << "a is: " << a << endl;
	std::auto_ptr<A> a_auto(a);
	std::auto_ptr<A> a_auto2 = a_auto;//传递了owner,会导致无法分清owner最终指向谁.禁用.
	std::auto_ptr<A> a_auto3(a);//指向同一个指针,禁用.这样会连续调用两次析构.
	//auto_ptr只在一个函数里使用,不要在函数参数里使用.
	cout << "a_auto is: " << a_auto.get() << endl;
	cout << "a_auto2 is: " << a_auto2.get() << endl;
	cout << "endl" << endl;
	
	return 0;
}


输出:

begin
A
a is: 0x2f1000
a_auto is: 0
a_auto2 is: 0x2f1000
endl
~A
~A



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Peter(阿斯拉达)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值