[C++][Demo]unique_ptr进行内存的转移(附内存检测)
Demo Code
#include <stdlib.h>
#include <crtdbg.h>
#include <stdint.h>
#include <iostream>
#include <memory>
using namespace std;
static int32_t g_ptr;
static int32_t g_size;
void set_data(int32_t _ptr, int32_t _size){
g_ptr = _ptr;
g_size = _size;
}
void show_data(void){
unique_ptr<char[]> str(reinterpret_cast<char *>(g_ptr));
str.get()[9] = c;
printf("===[%s]=[%c]==
", str, str.get()[9]);
}
void test_data(void){
unique_ptr<char[]> str = make_unique<char[]>(10);
str.get()[0] = a;
str.get()[1] = b;
str.get()[2] = c;
str.get()[3] = ;
set_data(reinterpret_cast<int32_t>(str.get()), 10);
str.release();
}
int _tmain(int argc, _TCHAR* argv[])
{
int* pa = new int;
test_data();
show_data();
_CrtDumpMemoryLeaks();
return 0;
}
Demo Result
===[abc]=[c]==
Detected memory leaks!
Dumping objects ->
{209} normal block at 0x00455798, 4 bytes long.
Data: < > CD CD CD CD
Object dump complete.
Summary
Point1 C++智能指针unique_ptr维护一块内存,并保留一个所属,其所管理的内存会自动进行回收
Point2 系统中可能存在申请了内存之后需要通过指针地址传递给其他模块的情况,这里是运用unique_ptr来确保这段内存可以被自动正确的释放
Point3 可以尝试将 str.release(); 这句屏蔽掉,可以发现最后内存的访问存在问题,所以请注意在内存转移之前保证unique_ptr原所属已经释放了权限
Point4 _CrtDumpMemoryLeaks 此函数可以查看当前位置内存泄漏的情况,有兴趣的同学可以尝试搜索一下
Thanks For Watching, Have a nice day!
