0
我得到了類,它包含的unique_ptr陣列下面的構造內存泄漏,而使用的std ::移動
template <class T>
MyVector<T>::MyVector() : p_capacity(2), p_size(0) {
p_array = std::make_unique<T[]>(p_capacity);
}
我想在這樣的成員方法後重新初始化,將舊的陣列到新的數組多數民衆贊成在2倍大
template <class T>
void MyVector<T>::extendArray() {
p_capacity *= 2;
const auto &srcArray = p_array.get();
std::unique_ptr<T[]> destArray = std::make_unique<T[]>(p_capacity);;
std::move(srcArray, std::next(srcArray, p_capacity/2), destArray.get());
}
看來工作,彙編,擴展我的數組像我想要的,但顯示該Valgrind的檢查:
==17698== Invalid write of size 4
==17698== at 0x4030D4: MyVector<int>::pushBack(int const&) (my_vector.cpp:17)
==17698== by 0x402D9F: main (main.cpp:13)
==17698== Address 0x542bc88 is 0 bytes after a block of size 8 alloc'd
==17698== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==17698== by 0x404907: operator new(unsigned long) (in /home/maciek/Programming/MyVector/MyVector)
==17698== by 0x403B68: operator new[](unsigned long) (in /home/maciek/Programming/MyVector/MyVector)
==17698== by 0x40329D: std::_MakeUniq<int []>::__array std::make_unique<int []>(unsigned long) (in /home/maciek/Programming/MyVector/MyVector)
==17698== by 0x403010: MyVector<int>::MyVector() (my_vector.cpp:5)
==17698== by 0x402C9B: main (main.cpp:8)
==17698==
您是否試圖將第一個數組的內容複製到新數組中 – Ankur
是的,這就是指向。將舊數組複製到具有更大尺寸的新數組中。我知道有STL Vector我可以使用,但我實際上正在試圖自己做。 – Emdzej93
然後你不用移動它。 使用std:copy或memcpy。然後重置您的唯一指針。併爲變量分配一個新的唯一ptr。 移動用於轉讓所有權。沒有內容 – Ankur