std :: unique_ptr :: reset和constructor异常 [英] std::unique_ptr::reset and constructor exceptions

查看:200
本文介绍了std :: unique_ptr :: reset和constructor异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果初始化一个 unique_ptr 如下:

std::unique_ptr<Foo> i;
i.reset( new Foo() ); 

但是从 Foo :: Foo(),问题是:分配的内存会发生什么? unique_ptr如何避免泄漏?这是在新的运算符内部处理的东西?

but an exception is thrown from Foo::Foo(), the question is: what happens with the memory allocated? how does unique_ptr avoid it being leaked? is this something handled inside new operator?

当范围退出时,析构函数一定会被调用。由于重置调用直到 new Foo()返回为止,似乎必须由 new ,通过在异常离开构造函数时释放分配的内存。

The destructor will certainly be called when the scope exits. Since the reset call is not invoked until new Foo() returns, it seems that this must be handled by new, by freeing the allocated memory when the exception leaves the constructor.

是否会发生什么?

推荐答案

Foo 的构造函数中,唯一指针的重置函数永远不会被执行。因此,唯一的指针保留其原始值。

If an exception is thrown in the constructor of Foo, then the reset function of the unique pointer never gets executed in the first place. Thus the unique pointer retains its original value.

如果对象构造抛出,新的表达式不会泄漏内存一个例外。

A new expression doesn't leak memory if the object construction throws an exception.

这篇关于std :: unique_ptr :: reset和constructor异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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