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

#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,后面的调用已经是出问题了的。

上一篇:08、ADS使用记录之低通滤波器设计与优化


下一篇:labelImg操作