使用std :: unique_ptr时出现内存泄漏

斯文·范·登·博加特(Sven van den Boogaart)

我正在尝试unique_ptr以查看内存管理在c ++中的工作方式。

丁h

#pragma once
class Ding
{
public:
    int value;
    Ding();
    ~Ding();
};

Ding.cpp

#include "stdafx.h"
#include "Ding.h"
#include <iostream>

Ding::Ding()
{
    value = 90000;
    std::cout << "Constructor for ding called.";
}


Ding::~Ding()
{
    std::cout << "Destructor for ding called.";
}

Main.cpp

#include "stdafx.h"
#include <memory>
#include "Ding.h"

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

int main()
{
    std::cout << "starting." << std::endl;
    std::vector<std::unique_ptr<Ding>> dingen;
    for (int i = 0; i < 10; i++)
    {
         std::unique_ptr<Ding> toAdd(new Ding);
         dingen.push_back(std::move(toAdd));
    }
    std::cout << "ending" <<std::endl;

    _CrtDumpMemoryLeaks();
    return 0;
}

运行此代码时,我可以在调试输出视图中看到内存错误:

Detected memory leaks!

Dumping objects -> {151} normal block at

0x00000155B0798140, 104 bytes long.  Data: <                > 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00  {144} normal block at
0x00000155B07A2300, 16 bytes long.  Data: <  S             > 08 FB 53
D3 14 00 00 00 00 00 00 00 00 00 00 00  Object dump complete.

是什么造成这些泄漏?

编辑:正如dasblinkenlight答案所述,我需要使用(新的Ding),在尝试查找泄漏时,我不小心删除了该零件。将其添加到问题中,因为它不能解决内存泄漏,但是会调用ding的构造函数和析构函数。

谢尔盖·卡里尼琴科(Sergey Kalinichenko)

泄漏来自std :: vector。放入嵌套范围应该可以解决此问题:

int main() {
    { // Open new scope
        std::cout << "starting." << std::endl;
        std::vector<std::unique_ptr<Ding>> dingen;
        for (int i = 0; i < 10; i++)
        {
             std::unique_ptr<Ding> toAdd;
             dingen.push_back(std::move(toAdd));
        }
        std::cout << "ending" <<std::endl;
    } // Close the scope

    _CrtDumpMemoryLeaks();

    return 0;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用operator ==时std :: set中unique_ptr的深度比较

使用地图内的std :: unique_ptr作为键

使用ʻas_ptr()`时如何停止内存泄漏?

我应该使用QScopedPointer还是std :: unique_ptr?

奇怪的错误:当未真正创建指针时,使用删除的函数'std :: unique_ptr <_Tp,_Dp> :: unique_ptr

如何在std :: copy中使用unique_ptr?

在移动构造函数中的unique_ptr上调用std :: move时出现“错误:使用已删除的函数”

出现unique_ptr问题:不是“ std”的成员

使用什么std :: optional或std :: unique_ptr

将std :: unique_ptr传递给类时出错

使用静态const初始化unique_ptr时出现未定义的参考错误

为什么Google Test / Mock显示std :: unique_ptr泄漏的模拟对象错误?

使用std :: unique_ptr <T>&代替std :: unique_ptr <T>有什么优势吗?

如何使用std:unique_ptr擦除包含结构的向量?

在地图内使用unique_ptr时std :: pair中已删除的函数

使用`std :: unique_ptr`时`std :: vector`中的数据不同

使用std :: unique_ptr创建对象数组

当unique_ptr在向量中时,对std :: unique_ptr <>拥有的对象的引用/ ptr是否安全?

重新分配std :: unique_ptr时是否释放内存?

一些std :: unique_ptr使用和“陷阱”

std :: unique_ptr <T>而不在堆上分配内存

使用std :: move(nullptr)的unique_ptr的operator =的C ++错误

使用shared_ptr时发生内存泄漏

使用 std::unique_ptr 使用 CRTP 进行转换

在 QVector<std::unique_ptr<Type>> 上使用 std::find

在 Qt 上使用 std::unique_ptr

使用 std::move 分配 unique_ptr 不起作用

对 unique_ptr 使用强化静态代码分析器时的内存泄漏

使用内存池中的自定义删除器将 std::unique_ptr 返回到抽象类型