使用STD ::移动时的内存泄漏
Memory leak while using std::move
我获得了包含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 ::复制的函数。
相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- malloc() 可能出现内存泄漏
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 尽管遵循了规则,内存泄漏在哪里
- 为什么调用堆栈数组会导致内存泄漏
- 在简单示例中,Python3 + ctypes 回调会导致内存泄漏
- 使用模板类的自定义列表类型中的内存泄漏
- 为什么以下C++代码中存在内存泄漏?
- OpenCV 我应该使用智能指针来防止内存泄漏吗?
- 我是否生成线程并导致内存泄漏?
- 多线程程序中出现意外的内存泄漏
- 为什么此函数会导致内存泄漏?
- 在 C++ 库中使用cythonized python时内存泄漏
- 需要帮助查找内存泄漏
- 瓦尔格林德的内存泄漏使用新的
- 无法找出我的代码中的内存泄漏
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 可视化 使用 VS Code 查找C++应用程序中的内存泄漏
- Shared_ptr双链接列表内存泄漏
- C++ 在类中使用常量引用文本时 O2 内存泄漏