首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

施用unique_ptr代替C风格数组的一个例子

2012-07-18 
使用unique_ptr代替C风格数组的一个例子使用C风数组:void COperationsWorkerBase::GetFileViewerDownloadL

使用unique_ptr代替C风格数组的一个例子

使用C风格数组:


void COperationsWorkerBase::GetFileViewerDownloadLink(const std::wstring& sSourcePath, std::wstring& sEncPath)
{
size_t nSize = ENCRYPTED_BUFFER_SIZE(sSourcePath.size());
TCHAR* sPathEncrypted = new TCHAR[nSize + 1];//encrypt will append a ICC_NULL_A at the end.


set_seed(_T("attachments"));


encrypt(sSourcePath.c_str(), sPathEncrypted);


sEncPath.assign(sPathEncrypted, nSize);


delete[] sPathEncrypted;
}


使用unique_ptr:


void COperationsWorkerBase::GetFileViewerDownloadLink(const std::wstring& sSourcePath, std::wstring& sEncPath)
{
size_t nSize = ENCRYPTED_BUFFER_SIZE(sSourcePath.size());
std::unique_ptr<TCHAR[]> sPathEncrypted(new TCHAR[nSize + 1]);//encrypt will append a ICC_NULL_A at the end.


set_seed(_T("attachments"));


encrypt(sSourcePath.c_str(), sPathEncrypted.get());


sEncPath.assign(sPathEncrypted.get(), nSize);
}


好处: 不在需要delete语句了. 在这个例子中好处还不明显,但是如果上面函数中有很多try-catch, 就安全多了,不用担心在某个路径上忘了delete.

坏处: 除了上面这条, 没看出还有其他什么好处. 一旦用了unique_ptr::get(), 被包裹起来的指针实际上已经失去控制了. 使用该指针的代码必须和直接使用C数组一样小心, '智能'指针帮不上任何忙. 而且要记住千万不要自己delete.


热点排行