C++ 智能指针六
/* 智能指針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++ Ouput Exactly 2