使用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.


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值