使用std :: unique_ptr时的memoryLeak
Memoryleak when using std::unique_ptr
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);
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- ostream过载时的缓冲区冲洗
- 具有未知值时的时间复杂性
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 当比特(而不是字节)的顺序至关重要时的持久性
- 旋转模型矩阵时的形状失真
- 讨论 - 创建矩阵时的数组与向量的向量 - 什么是最实用的选择
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 打印第二列时的2d字符矢量打印空间
- 读取文件时运行时的未知行为
- posix_spawn():使用posix_scawn()时的错误处理问题
- 查找最近配对时的OpenMP竞赛条件
- 如何修复valgrind启动时的致命错误(与libc6-dbg和libc6-dbg:i386连接)
- 在 c++ 中在开关情况下使用和不使用"break"时的不同输出
- 求和 int 乘以双倍时的欠/过近似
- 打包可变参数模板具有零元素时的递归
- 在Qt5中使用QTextSteam时的"使用已删除功能"
- 内存错误低于在C++年实现埃拉托色尼筛分时的预期
- 尝试了解在导入的静态方法上使用删除方法时的错误
- 使用std :: unique_ptr时的memoryLeak