I have seen a great answer here which has helped me to a great extent (Proper way to create unique_ptr that holds an allocated array) but I still have an issue.
Code:
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;
}
}
If I turn pIndex
into a smart pointer:
auto pIndex = std::make_unique<int[]>(iSize);
So that I don't need the delete[] pIndex;
call. Then I can't pass pIndex
to GetSelItems
. I can pass pIndex.release()
here but then we have a problem for deleting again.
- I have looked at this discussion (Issue passing std::unique_ptr's) but we don't want to pass ownership.
- If I simplify this and declar my variable:
auto pIndex = std::make_unique<int[]>(iSize).release();
then I can pass it, but now have the issue of callingdelete[] pIndex;
.
Whats correct?