何时释放unique_ptr? [英] When a unique_ptr is deallocated?

查看:129
本文介绍了何时释放unique_ptr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码中:

void f(std::unique_ptr<int> q)
{
}

void g()
{
    std::unique_ptr<int> p{new int{42}};
    f(std::move(p));
}

在哪一行p被释放?我想在f函数的出口处说,因为它是使用std :: move移到那里的,但是我不确定对此答案也不确定.

At which line p is deallocated? I'd say at the exit of the f function because it was moved there using std::move, but I'm not sure nor confident about this answer.

推荐答案

p分配在哪一行?

At which line p is deallocated?

在声明它的作用域的末尾,即在这种情况下为函数g.那是当具有自动存储功能的对象被销毁并释放其内存时.

At the end of the scope where it was declared i.e the function g in this case. That is when objects with automatic storage are destroyed, and their memory deallocated.

您初始化为42的具有动态存储的整数将由q的析构函数在f的末尾释放.这是因为搬迁施工转移了所有权.

The integer with dynamic storage that you initialised to 42 will be deallocated by the destructor of q at the end of f. This is because the move construction transferred the ownership.

这篇关于何时释放unique_ptr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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