unique_ptr 的矢量未被完全删除(内存泄漏)

vector of unique_ptr not being fully deleted (memory leaks)

我正在编写一个程序,最终需要我为自定义 class 的对象创建一个 unique_ptrs 的向量。我遇到了一些内存泄漏,所以我决定从等式中删除自定义 class 并尝试使用 unique_ptr。

当我尝试在堆栈上创建 unique_ptr 时,没有泄漏。但是,创建 unique_ptrs 的向量会 泄漏。为了好玩,我还尝试将 unique_ptr 移动到向量中以查看发生了什么。我的代码如下(包括 MSVS 内存检查):

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

#include <vector>
#include <memory>
using namespace std;

int main()
{
    vector<unique_ptr<int>> testvector;
    unique_ptr<int> addMe;

    testvector.emplace_back(move(addMe));
    testvector.clear();

    _CrtDumpMemoryLeaks();
    return 0;
}

当我注释掉除创建 "addMe" 之外的所有内容时,我没有泄漏。
当我注释掉除创建 "testvector" 之外的所有内容时,我得到 8 个字节的内存泄漏。
当我注释掉 "addme" 的 emplace_back 到 "testvector" 时,我得到了 8 个字节的内存泄漏。
当我什么都不注释时,我得到 12 字节的内存泄漏。
当我用 "shared_ptr" 替换所有 "unique_ptr" 时,一切都一样。

我是不是做错了什么,或者这是智能指针向量的预期结果?

谢谢!

std::vector::clear()

的文档中所述

http://www.cplusplus.com/reference/vector/vector/clear/

Removes all elements from the vector (which are destroyed), leaving the container with a size of 0. A reallocation is not guaranteed to happen, and the vector capacity is not guaranteed to change due to calling this function. A typical alternative that forces a reallocation is to use swap.

这意味着,元素会被删除,但 std::vector 使用的内部存储不会。

如果你的编译器支持C++11,那么你可以使用std::vector::shrink_to_fit()尝试使capacity设置为size, 清零后等于0.

http://www.cplusplus.com/reference/vector/vector/shrink_to_fit/

Shrink to fit Requests the container to reduce its capacity to fit its size.

The request is non-binding, and the container implementation is free to optimize otherwise and leave the vector with a capacity greater than its size.

This may cause a reallocation, but has no effect on the vector size and cannot alter its elements.