【C++14算法】make_unique

1. 前言
在C++14标准中引入了一系列方便而强大的函数模板,旨在简化和改进代码的编写和可读性。其中之一是std::make_unique函数模板,它提供了一种更安全和方便的方式来创建和管理动态分配对象。本文将介绍std::make_unique的作用,它是如何使用的,以及四个示例代码来展示其实际应用。
2. 什么是make_unique?
make_unique是C++14引入的一个函数模板,用于创建并返回一个指向动态分配对象的unique_ptr智能指针。它是为了简化代码,避免手动使用new和delete,以及确保资源的正确释放而设计的。
3. 如何使用make_unique?
使用make_unique非常简单,并且遵循以下步骤:

(1)包含头文件 #include

(2)调用make_unique函数模板,并传入要创建对象的类型和构造对象所需的参数。
3.1 make_unique的函数原型如下:

点击查看代码
template< class T, class... Args >
std::unique_ptr<T> make_unique( Args&&... args );
其中,T代表指向动态对象的指针类型,Args代表构造对象时传递的参数类型,而args则是实际的构造参数。

3.2 示例代码

示例1:
创建一个动态分配的整数对象

点击查看代码
#include <iostream>
#include <memory>
int main() {
    std::unique_ptr<int> ptr = std::make_unique<int>(42);
    std::cout << "Value: " << *ptr << std::endl;
    return 0;
}
输出:

Value: 42

**示例2: **
创建一个动态分配的自定义类型对象

点击查看代码
#include <iostream>
#include <memory>
struct Point {
    int x;
    int y;
    Point(int x, int y) : x(x), y(y) {}
};
int main() {
    std::unique_ptr<Point> ptr = std::make_unique<Point>(10, 20);
    std::cout << "Point: (" << ptr->x << ", " << ptr->y << ")" << std::endl;
    return 0;
}

输出:

Point: (10, 20)
示例3: 创建一个动态分配的数组对象

点击查看代码
#include <iostream>
#include <memory>
int main() {
    std::size_t size = 5;
    std::unique_ptr<int[]> ptr = std::make_unique<int[]>(size);
    for (std::size_t i = 0; i < size; ++i) {
        ptr[i] = i + 1;
    }
    std::cout << "Array: ";
    for (std::size_t i = 0; i < size; ++i) {
        std::cout << ptr[i] << " ";
    }
    std::cout << std::endl;
    return 0;
}
输出:

Array: 1 2 3 4 5

示例4: 创建一个动态分配的自定义类对象数组

点击查看代码
#include<iostream>
#include<memory>
class MyClass {
public:
	//补充默认构造函数
	MyClass() :value_(0) {
		std::cout << "Default Constructor called" << std::endl;
	}
	MyClass(int value) :value_(value) {
		std::cout << "Constructor called with value:" << value_ << std::endl;
	}
	~MyClass() {
		std::cout << "Destructor called with value: " << value_ << std::endl;
	}
	void PrintValue() const {
		std::cout << "Value: " << value_ << std::endl;
	}
private:
	int value_;
};
int main() {
	std::size_t size = 3;
	std::unique_ptr<MyClass[]> ptr = std::make_unique<MyClass[]>(size);
	for (std::size_t i = 0; i < size; ++i)
	{
		//定位new,在已分配的内存上构造对象
		new(&ptr[i])MyClass(10);
	}
	for (std::size_t i = 0; i < size; ++i)
	{
		ptr[i].PrintValue();
	}
	return 0;
}
输出:
点击查看代码
Default Constructor called
Default Constructor called
Default Constructor called
Constructor called with value:10
Constructor called with value:10
Constructor called with value:10
Value: 10
Value: 10
Value: 10
Destructor called with value: 10
Destructor called with value: 10
Destructor called with value: 10
posted @ 2025-12-13 19:27  阳光天气  阅读(23)  评论(0)    收藏  举报