我正在尝试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的构造函数和析构函数。
泄漏来自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] 删除。
我来说两句