参考网址:

C++自学24:唯一智能指针

尽量使用std::make_unique和std::make_shared而不直接使用new(总结)

使用

1
2
3
4
5
6
std::unique_ptr<int> a = std::make_unique<int>(666); // 智能指针具有唯一性
std::unique_ptr<int> b = std::make_shared<int>(666);
// create std::initializer_list
auto initList = { 10, 20 };
// create std::vector using std::initializer_list ctor
auto spv = std::make_shared<std::vector<int>>(initList);

make_queue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <iomanip>
#include <memory>

struct Vec3
{
int x, y, z;

// following constructor is no longer needed since C++20
Vec3(int x = 0, int y = 0, int z = 0) noexcept : x(x), y(y), z(z) { }

friend std::ostream& operator<<(std::ostream& os, const Vec3& v) {
return os << "{ x=" << v.x << ", y=" << v.y << ", z=" << v.z << " }";
}
};

int main()
{
// Use the default constructor.
std::unique_ptr<Vec3> v1 = std::make_unique<Vec3>();
// Use the constructor that matches these arguments
std::unique_ptr<Vec3> v2 = std::make_unique<Vec3>(0,1,2);
// Create a unique_ptr to an array of 5 elements
std::unique_ptr<Vec3[]> v3 = std::make_unique<Vec3[]>(5);

std::cout << "make_unique<Vec3>(): " << *v1 << '\n'
<< "make_unique<Vec3>(0,1,2): " << *v2 << '\n'
<< "make_unique<Vec3[]>(5): ";
for (int i = 0; i < 5; i++) {
std::cout << std::setw(i ? 30 : 0) << v3[i] << '\n';
}
}