本文主要是介绍C++14智能指针make_unique(八十一),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.代码示例
#include <iostream>
#include <memory>
struct Vec3{int x, y, z;Vec3() : x(0), y(0), z(0) { }Vec3(int x, int y, int z) :x(x), y(y), z(z) { }friend std::ostream& operator<<(std::ostream& os, 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 argumentsstd::unique_ptr<Vec3> v2 = std::make_unique<Vec3>(0, 1, 2);// Create a unique_ptr to an array of 5 elementsstd::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): " << '\n';for (int i = 0; i < 5; i++) {std::cout << " " << v3[i] << '\n';}
}
这篇关于C++14智能指针make_unique(八十一)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!