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