【原创&交流】智能指针变量做函数参数的一个值得注意的地方
先考考大家,下面一段程序,会有什么问题:
#include <iostream>#include <string>#include "boost/smart_ptr.hpp"class MyClass{public: MyClass() { m_count = 1; m_strName = _T("xiao ming"); } void Increase() { m_count++; std::wcout<<m_strName<<_T(" increase 1 ")<<std::endl; } void ChangeName() { m_strName = _T("xiao gang"); std::wcout<<_T("The new name is ")<<m_strName<<std::endl; } std::wstring GetName() { return m_strName; } ~MyClass() { std::wcout<<_T(" Destructor")<<std::endl; }private: int m_count; std::wstring m_strName;};void Process(boost::shared_ptr<MyClass>& ptrParam){ ptrParam->Increase(); std::wcout<<ptrParam->GetName()<<_T(" enter Procees function")<<std::endl;}void CallFunction(){ MyClass* pNewInstance = new MyClass(); { boost::shared_ptr<MyClass> ptrParam(pNewInstance); Process(ptrParam); } pNewInstance->ChangeName();}int _tmain(int argc, _TCHAR* argv[]){ CallFunction(); system("pause"); return 0;}