将原始指针的所有权转移到 unique_ptr [英] Transferring ownership of raw pointer to unique_ptr

查看:35
本文介绍了将原始指针的所有权转移到 unique_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经分配了一个带有 new 运算符的指针,并将内存的所有权分配给了一个新的 unique_ptr .我是否必须删除使用 new 分配的指针?这里有内存泄漏吗?

I have allocated a pointer with new operator and assigned the ownership of the memory to a new unique_ptr . Do I have to delete the pointer allocated using new? Is there a memory leak here?

#include <iostream>
#include <memory>

using namespace std;


int main()
{
    int *a = new int;

    *a = 5;
    std::unique_ptr<int> auptr;

    auptr.reset(a);
    int *b = auptr.get();
    cout << *b << endl;

    cout << *a << endl;



    return 0;
}

推荐答案

当你的代码到达 return 时,你有三个指针(a, auptrb) 指向同一个对象,由 new 分配.返回后 auptr 将超出范围,它的析构函数将释放对象,因此您不必手动执行此操作,也不会出现内存泄漏.

When your code reaches return, you have three pointers (a, auptr and b) pointing at the same object, which was allocated by new. After return auptr will go out of scope and it's destructor will deallocate the object, so you don't have to do it manually and there are no memory leaks.

请注意,您的代码看起来像是对 unique_ptr 的滥用.您最初创建一个原始指针,然后从中间智能指针获取另一个原始指针.考虑使用 std::make_unique 和摆脱原始指针.

Just note that your code looks as misuse of unique_ptr. You make a raw pointer initially, and get another raw pointer from an intermediate smart pointer. Consider using std::make_unique and get rid of raw pointers.

这篇关于将原始指针的所有权转移到 unique_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆