c++智能指针
1:shared_ptr
shared_ptr可以用于管理简单的数据,int,double,char等
eg:
shared_ptr<int> sp (new int);
*sp = 100;
std::cout<<*sp<<std::endl;
shared_ptr可以用于管理用户自定义的类
eg:
class Sample {
public:
Sample() { cout << "Sample Constructor" << endl; }
~Sample() { cout << "Sample Destructor" << endl; }
void publicFn() { cout << "This is public function of class" << endl; }
};
int main() {
shared_ptr<Sample> sp(new Sample{});
sp->publicFn();
return 0;
}
shared_ptr管理数组需要自定义删除方法
eg:
bool del(int *p){
delete [] p;
}
shared_ptr<int> shared(new int[100],del);//使用函数
shared_ptr<int> ptr(new int[100],
[](int *p){delete [] p;});//使用lambda表达式
若是要对与其中的数据进行管理,则可以使用get,同时以下代码对比unique_ptr的使用
std::unique_ptr<int[]> uniPtr (new int [100]);
uniPtr[0] = 100;
std::cout<<uniPtr[0]<<std::endl;
std::shared_ptr<int> spi (new int[100],[](int *p){
delete []p;
});
spi.get()[20]=50;