我在这里看到了一个很好的答案,这在很大程度上帮助了我(创建包含分配数组的 unique_ptr 的正确方法)但我仍然有一个问题。
代码:
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);
auto pIndex = new int[iSize];
m_lbBrothers.GetSelItems(iSize, pIndex);
for(auto i = 0; i < iSize; i++)
{
m_lbBrothers.GetText(pIndex[i], strText);
m_aryStrSelectedBro.Add(strText);
}
delete[] pIndex;
}
}
如果我pIndex
变成一个智能指针:
auto pIndex = std::make_unique<int[]>(iSize);
这样我就不需要delete[] pIndex;
打电话了。然后我不能pIndex
传给GetSelItems
. 我可以通过pIndex.release()
这里,但是我们再次删除时遇到了问题。
- 我看过这个讨论(问题传递 std::unique_ptr's),但我们不想传递所有权。
- 如果我简化它并声明我的变量:
auto pIndex = std::make_unique<int[]>(iSize).release();
那么我可以传递它,但现在有调用delete[] pIndex;
.
什么是正确的?