参考网址:
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);
auto initList = { 10, 20 };
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; 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() { std::unique_ptr<Vec3> v1 = std::make_unique<Vec3>(); std::unique_ptr<Vec3> v2 = std::make_unique<Vec3>(0,1,2); 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'; } }
|