如何将std::unique_ptr<int[]>参数正确传递给CListBox::GetSelItems方法
正确实现方案
你只需要调用std::unique_ptr的get()方法获取其持有的原始指针即可,该操作不会转移所有权,智能指针会在作用域结束时自动释放数组内存。
修改后的完整代码如下:
void CSelectedBroHighlight::BuildSelectedArray() { CString strText; // empty current array m_aryStrSelectedBro.RemoveAll(); // get selected count const auto iSize = m_lbBrothers.GetSelCount(); if(iSize > 0) { auto pIndex = std::make_unique<int[]>(iSize); // 用get()获取原始指针传入接口,所有权仍由pIndex持有 m_lbBrothers.GetSelItems(iSize, pIndex.get()); for(auto i = 0; i < iSize; i++) { m_lbBrothers.GetText(pIndex[i], strText); m_aryStrSelectedBro.Add(strText); } // 无需手动调用delete[],pIndex离开作用域时自动释放内存 } }
关键说明
很多人会混淆get()和release()两个方法的作用:
get():仅返回当前持有的原始指针,智能指针仍保留内存所有权,适合需要将原始指针传递给第三方接口读写、但不需要对方管理内存的场景release():释放智能指针对内存的所有权,返回原始指针,调用后智能指针不再关联这块内存,需要开发者手动释放,所以你之前尝试用release()的方案会失去智能指针的内存管理能力
更推荐的替代方案
如果没有特殊限制,直接使用std::vector实现会更符合现代C++开发习惯,代码可读性更高:
void CSelectedBroHighlight::BuildSelectedArray() { CString strText; m_aryStrSelectedBro.RemoveAll(); const auto iSize = m_lbBrothers.GetSelCount(); if(iSize > 0) { std::vector<int> pIndex(iSize); m_lbBrothers.GetSelItems(iSize, pIndex.data()); for(auto i = 0; i < iSize; i++) { m_lbBrothers.GetText(pIndex[i], strText); m_aryStrSelectedBro.Add(strText); } } }
std::vector会自动管理内存,同时支持下标访问,和原有代码的使用习惯完全一致。
内容的提问来源于stack exchange,提问作者Andrew Truckle
相关产品推荐
相关产品推荐

