智能指针被释放后的原始指针不可再用

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

class MyClass
{
public:

	MyClass()
	{
		m_count = 1;
		m_strName = "xiao ming";
	}

	void Increase()
	{
		m_count++;
		std::cout << m_strName << " increase 1 " << std::endl;
	}

	void ChangeName()
	{
		std::cout << "ChangeName function()" << std::endl;
		m_strName = "xiao gang";
		std::cout << "The new name is  " << m_strName << std::endl;
	}

	std::string GetName()
	{
		return m_strName;
	}

	~MyClass()
	{
		std::cout << " Destructor" << std::endl;
	}

private:

	int m_count;
	std::string m_strName;
};

void Process(std ::shared_ptr<MyClass>& ptrParam)
{
	ptrParam->Increase();
	std::cout << ptrParam->GetName() << " enter Procees function" << std::endl;
}

void CallFunction()
{
	MyClass* pNewInstance = new MyClass();
	{
		std::shared_ptr<MyClass> ptrParam(pNewInstance);
		Process(ptrParam); //ptrParam释放管理的指针,但是pNewInstance并没有置为nullptr
	}
	if (pNewInstance == nullptr) {
		std::cout << "pNewInstance == nullptr" << std::endl;
	}
	else {
		std::cout << "pNewInstance != nullptr" << std::endl;
		pNewInstance->ChangeName();
	}
}

int main(int argc, char* argv[])
{
	{
		CallFunction();
	}
	
	system("pause");
	return 0;
}

运行结果:

xiao ming increase 1
xiao ming enter Procees function
~MyClass()
pNewInstance != nullptr
ChangeName function()

重点看这段代码:

MyClass* pNewInstance = new MyClass();
	{
		std::shared_ptr<MyClass> ptrParam(pNewInstance);
		Process(ptrParam); //ptrParam释放管理的指针,但是pNewInstance并没有置为nullptr
	}
	if (pNewInstance == nullptr) {
		std::cout << "pNewInstance == nullptr" << std::endl;
	}
	else {
		std::cout << "pNewInstance != nullptr" << std::endl;
		pNewInstance->ChangeName();
	}

ptrParam这个智能指针在其作用域结束后,会释放其管理的指针(计数为0时),看到~MyClass()已经执行了,但是没有将这个指针置为nullptr,后面的调用已经是出问题了的。

参考:https://www.cnblogs.com/lanzhi/archive/2012/03/23/6470827.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值