std::make_unique返回值校验
时间: 2024-01-16 15:17:49 浏览: 146
std::make_unique是C++14中引入的一个函数模板,用于创建一个独占所有权的智能指针std::unique_ptr,并将其初始化为一个动态分配的对象。它的返回值是一个std::unique_ptr指针。
在使用std::make_unique时,我们通常需要对其返回值进行校验,以确保内存分配成功。如果内存分配失败,std::make_unique将抛出std::bad_alloc异常。
以下是一个使用std::make_unique的示例,同时对其返回值进行校验:
```cpp
#include <iostream>
#include <memory>
int main() {
std::unique_ptr<int> ptr = std::make_unique<int>(42);
if (ptr) {
std::cout << "Memory allocation successful." << std::endl;
std::cout << "Value: " << *ptr << std::endl;
} else {
std::cout << "Memory allocation failed." << std::endl;
}
return 0;
}
```
在上述示例中,我们使用std::make_unique创建了一个指向整数的std::unique_ptr,并将其初始化为值为42的整数。然后,我们对返回值进行了校验,如果内存分配成功,则输出相应的信息和值;如果内存分配失败,则输出相应的失败信息。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)