【发布时间】:2020-12-09 13:33:03
【问题描述】:
#include <iostream>
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
class My_Container
{
public:
My_Container(int y) : x{new int(y)}
{
//*x = y;
}
int get_value() const
{
return *x;
}
bool has_value() const
{
return x != nullptr;
}
private:
std::unique_ptr<int> x = std::make_unique<int>();
};
int test1(My_Container const &container)
{
if (container.has_value())
{
return container.get_value();
}
return -1;
}
int test2(My_Container const &container)
{
if (container.has_value())
{
return container.get_value();
}
return -1;
}
int main()
{
My_Container c1{5};
My_Container const c2{3};
std::cout << test1(c1) << std::endl;
std::cout << test1(c2) << std::endl;
std::cout << test2(c1) << std::endl;
std::cout << test2(c2) << std::endl;
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT);
if (_CrtDumpMemoryLeaks())
{
std::cout << "he" << std::endl;
}
return 0;
}
5 3 5 3 检测到内存泄漏!转储对象 -> {153} 普通块 在 0x011D0580,4 个字节长。数据: 03 00 00 00 {152}正常 块在 0x011D9E30,4 字节长。数据: 05 00 00 00 对象 转储完成。他
以上是输出。
谁能找到代码中产生这种内存泄漏的位置吗?
非常感谢。
【问题讨论】:
-
std::make_unique<int>();没有意义,删除它。但是您检测到的泄漏与此无关。检查指针地址,你会发现它们与x管理的地址无关。 -
不熟悉windows API,但是你在c1和c2被销毁之前调用了
_CrtDumpMemoryLeaks。试着把你的东西放在一个单独的范围内。
标签: c++