1、智能指针
智能指针,无需手动释放内存
#include <iostream> // 1.导入包 <iostream>
#include <memory>
using namespace std;
class Student2;
class Student {
public:
shared_ptr<Student2> student2;
Student() {
}
~Student() {
cout << "Student xigou" << endl;
}
};
class Student2 {
public:
shared_ptr<Student> student;
Student2() {
}
~Student2() {
cout << "Student2 xigou" << endl;
}
};
int main() {
//堆中开辟
Student *student = new Student();
Student2 *student2 = new Student2();
//释放内存空间
//delete student;
cout<<"main 函数弹栈"<<endl;
//使用智能指针智能回收,无需手动 delete ,原理为引入计数法。智能指针类封装了传入的对象,和引用数量。
//传入对象的时候,内部引入计数+1,当main函数弹栈的时候,智能指针类会调用析构函数,此时会对应用进行-1,
//通过引用计数释放为0 ,内部判断是否要delete内部的对象
//1、shared_ptr,会存在引入依赖问题
//引入变成1
// shared_ptr<Student> sharedPtr(student);
// shared_ptr<Student2> sharedPtr2(student2);
// student->student2 = sharedPtr2;
// student2->student = sharedPtr;
//2、
unique_ptr<Student> uniquePtr(student);
unique_ptr<Student2> uniquePtr2(student2);
// cout<<"引入数量:"<<uniquePtr.use_count()<<endl;
//
// cout<<"引入数量sharedPtr:"<<sharedPtr.use_count()<<endl;
// cout<<"引入数量sharedPtr2:"<<sharedPtr2.use_count()<<endl;
return 0;
}
2、C++中的四种转换
const_cast
转换常量
const Person *p = new Person();
//无常量指针 法转换
//p->name = "hello world";
Person* p2 = const_cast<Person*>(p);
p2->name = "hello world2";
cout<<p->name<<endl;
static_cast
静态转换,编译期转换
(1)指针类型转换
// static_cast转换指针
int number = 88;
void * p = &number;
int * pInt = static_cast<int *>(p);
cout<<*pInt<<endl;
(2)子父类转换
class Parent {
public:
void show() {
cout << "Parent show" << endl;
}
};
class Child:public Parent {
public:
void show() {
cout << "Child show" << endl;
}
};
Parent * p = new Parent();
Child * c = static_cast<Child*>(p);
c->show();
dynamic_cast
动态类型转换,运行期转换,可能会转换失败。编译器无法检测。
//动态转换,多态
Parent * p = new Child();
Child * c = dynamic_cast<Child*>(p);
if(c){
c->show();
}
reinterpret_cast
强制转换
class Parent {
public:
void show() {
cout << "Parent show" << endl;
}
};
//强制转换
Parent * p = new Parent();
//指针转换成数字
long number = reinterpret_cast<long>(p);
cout<<number<<endl;
//数字转换成指针
Parent * p2 = reinterpret_cast<Parent*>(number);
p2->show();
网友评论