日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++ 智能指针六

發(fā)布時(shí)間:2023/12/18 c/c++ 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++ 智能指针六 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
/* 智能指針unique_ptr */#include <iostream> #include <string> #include <memory> #include <vector>/*unique_ptr 獨(dú)占所指向的對(duì)象, 同一時(shí)刻只能有一個(gè) unique_ptr 指向給定對(duì)象(通過禁止拷貝語義, 只有移動(dòng)語義來實(shí)現(xiàn)), 定義于 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 不支持拷貝構(gòu)造函數(shù)//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方法: 放棄內(nèi)部對(duì)象的所有權(quán),將內(nèi)部指針置為空, 返回所內(nèi)部對(duì)象的指針, 此指針需要手動(dòng)釋放*/std::unique_ptr<Student> up5(up1.release());//初始化方式四/*reset方法: 銷毀內(nèi)部對(duì)象并接受新的對(duì)象的所有權(quán)(如果使用缺省參數(shù)的話,也就是沒有任何對(duì)象的所有權(quán), 此時(shí)僅將內(nèi)部對(duì)象釋放, 并置為空)*/std::unique_ptr<Student> up6;up6.reset(new Student("als", 12));//成員函數(shù)的使用//可以進(jìn)行移動(dòng)構(gòu)造和移動(dòng)賦值操作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 支持管理數(shù)組std::unique_ptr<int[]> ups(new int[10]);printf("sizeof(ups) = %d\n", sizeof(ups));//打印4,并非數(shù)組實(shí)際長(zhǎng)度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; }

?

轉(zhuǎn)載于:https://www.cnblogs.com/zhanggaofeng/p/10294513.html

總結(jié)

以上是生活随笔為你收集整理的C++ 智能指针六的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。