使用STD ::移动时的内存泄漏

Memory leak while using std::move

本文关键字:内存 泄漏 移动 STD 使用      更新时间:2023-10-16

我获得了包含unique_ptr数组的类,带有以下构造函数

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==

std ::移动不会移动任何东西。它提出了使其可移动的论点。请参阅cppreference.com

正如@ankur在评论中所说的那样,您需要使用一个诸如std :: memcpy(如果t是微不足道或pod)或std ::复制的函数。