/* 智能指針unique_ptr */#include <iostream> #include <string> #include <memory> #include <vector>/*unique_ptr 獨占所指向的對象, 同一時刻只能有一個 unique_ptr 指向給定對象(通過禁止拷貝語義, 只有移動語義來實現), 定義于 memory (非memory.h)中, 命名空間為 std.unique_ptr 不支持拷貝和賦值.*/struct Student { public:Student(std::string name_, int age_) :name(name_), age(age_) {}std::string name;int age;};std::unique_ptr<Student> test_clone() {std::unique_ptr<Student> up1 = std::make_unique<Student>("spaow",65);return up1; }struct STDeleter {void operator() (int* obj){if (obj){for (int i = 0; i < 10; i++){//obj[i] = i + 2;printf("obj[i] = %d\n", obj[i]);}free(obj);obj = NULL;}} };void test() {//初始化方式一std::unique_ptr<Student> up1 = std::make_unique<Student>("tom",11);//error unique_ptr 不支持拷貝構造函數//std::unique_ptr<Student> up2(up1);//error unique_ptr 不支持賦值//std::unique_ptr<Student> up3 = up1;//初始化方式二std::unique_ptr<Student> up4(new Student("jack", 10));//初始化方式三:/*release方法: 放棄內部對象的所有權,將內部指針置為空, 返回所內部對象的指針, 此指針需要手動釋放*/std::unique_ptr<Student> up5(up1.release());//初始化方式四/*reset方法: 銷毀內部對象并接受新的對象的所有權(如果使用缺省參數的話,也就是沒有任何對象的所有權, 此時僅將內部對象釋放, 并置為空)*/std::unique_ptr<Student> up6;up6.reset(new Student("als", 12));//成員函數的使用//可以進行移動構造和移動賦值操作std::unique_ptr<Student> up7;up7 = std::move(up6);std::unique_ptr<Student> up8(std::move(up7));//特殊的拷貝std::unique_ptr<Student> up9 = test_clone();printf("name is [%s] .\n",up9->name.c_str());//在容器中保存指針std::vector<std::unique_ptr<Student> > vec;std::unique_ptr<Student> upTmp(new Student("kld",16));vec.push_back(std::move(upTmp));//unique_ptr 支持管理數組std::unique_ptr<int[]> ups(new int[10]);printf("sizeof(ups) = %d\n", sizeof(ups));//打印4,并非數組實際長度for (int i = 0; i < 10; i++){ups[i] = i;printf("ups[i] = %d\n", ups[i]);}//自定義刪除器定義int *tempArr = (int *)malloc(sizeof(int) * 10);std::unique_ptr<int, STDeleter> usp2(tempArr, STDeleter());int *pcIndex = usp2.get();for (int i = 0; i < 10; i++){pcIndex[i] = i+2;}}int main() {test();getchar();return 0; }
?