使用std :: move时内存泄漏

时间:2017-11-25 13:47:01

标签: c++ memory-leaks unique-ptr

我得到了包含带有以下构造函数的

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

1 个答案:

答案 0 :(得分:0)

std :: move不会移动任何东西。它抛出了使其可移动的论据。见cppreference.com

正如@Ankur在评论中所说,你需要使用像std :: memcpy这样的函数(如果T是微不足道或POD)或std :: copy。