郑州网站建设哪家,一般网站后台都是哪里做,旅游企业seo官网分析报告,深圳建网站服务基础介绍
虽然在c11版本std::unique_ptrT已经引入#xff0c;但是在c14版本引入之前#xff0c;std::unique_ptrT的创建还是通过new操作符来完成的。在c14版本已经引入了类似make_shared的std::make_unique#xff0c;目的是提供更加安全的方法创建std::un…基础介绍
虽然在c11版本std::unique_ptrT已经引入但是在c14版本引入之前std::unique_ptrT的创建还是通过new操作符来完成的。在c14版本已经引入了类似make_shared的std::make_unique目的是提供更加安全的方法创建std::unique_ptrT防止产生资源泄露等问题。
为什么要引入std::make_uniqueT?
首先请看下面这句话 std::make_unique is the recommended way to create instances of std::unique_ptrs due to the following reasons: Avoid having to use the new operator. 避免使用new操作符 Prevents code repetition when specifying the underlying type the pointer shall hold. 避免类型重复结合auto关键字可以使用类型推导 Most importantly, it provides exception-safety. 最重要的是它提供了异常安全。 下面我们着重分析一下第2点和第3点先说第二点避免代码重复(code repetition)应该按下面的方式理解
//不使用std::make_unique
// 需要重复写类型名
std::unique_ptrstd::vectorstd::string ptr(new std::vectorstd::string());// 模板类中更麻烦
templatetypename T
class Container {std::unique_ptrstd::vectorT data(new std::vectorT());
};//使用std::make_unique
// 类型推导无需重复
auto ptr std::make_uniquestd::vectorstd::string();// 模板类中更简洁
templatetypename T
class Container {auto data std::make_uniquestd::vectorT();
};现在分析最重要的第3点即为什么std::make_unique可以提供异常安全。看下面的例子:
foo(std::unique_ptrT{new T{}}, function_that_throws(), std::unique_ptrT{new T{}});
上例中foo函数为什么不安全呢原因是编译器并不会规定参数求值的执行顺序那么可能是顺序是
执行new T参数一执行new T 参数二执行function_that_throws() --抛出异常构造std::unique_ptrT 参数一构造std::unique_ptrT 参数二
我们知道std::unique_ptrT自身可以管理资源当std::unique_ptrT对象出了其作用后会自动释放资源但是如果在第3步的时候抛出了异常导致后面的std::unique_ptrT对象未创建成功则会导致内存泄露。
而使用std::make_uniqueT方式创建对象如下所示
foo(std::make_uniqueT(), function_that_throws(), std::make_uniqueT());
std::make_unique可以保证参数一创建完成即生成std::unique_ptrT后再执行后面的操作此时由于std::unique_strT对象已经生成即使后续抛出异常那么这块内存也会得到释放。