使用std :: unique_ptr时的memoryLeak

Memoryleak when using std::unique_ptr

本文关键字:时的 memoryLeak ptr unique std 使用      更新时间:2023-10-16

im尝试unique_ptr,以查看内存管理如何在C 中工作。

ding.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的构造函数和destrctor。

泄漏来自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;
}

代码不会创建任何Ding对象,这就是为什么从未调用构造函数的原因。std::unique_ptr<Ding> toAdd;创建一个持有空指针的unique_ptr对象;它不会创建Ding对象。要创建一个,请使用operator new

std::unique_ptr<Ding> toAdd(new Ding);