0
点赞
收藏
分享

微信扫一扫

C++ 智能指针 shared_ptr、make_shared用法


一、使用shared_ptr条件

  1. C++版本11以上
  2. 需引入头文件

#include <memory>

否则编译会报错

error: ‘shared_ptr’ was not declared in this scope

二、用法

 

#include <iostream>
#include <vector>
#include <memory>
using namespace std;

class testClass
{
public:
testClass(){
temp3 = make_shared<vector<int>>();
}
shared_ptr<vector<int>> temp3;
};

int main() {

cout<<"999999"<<endl;

testClass tempObj;
cout<<"temp1的长度: "<<tempObj.temp3->size()<<endl;

tempObj.temp3->push_back(333);
cout<<"temp1的长度: "<<tempObj.temp3->size()<<endl;

return 0;
}

C++ 智能指针 shared_ptr、make_shared用法_算法

三、若是定义在class中,则需要在class的构造函数中

#include <iostream>
#include <vector>
#include <memory>
using namespace std;

class testClass
{
public:
testClass(){
temp3 = make_shared<vector<int>>();
}
shared_ptr<vector<int>> temp3;
};

int main() {

cout<<"999999"<<endl;

testClass tempObj;
cout<<"temp1的长度: "<<tempObj.temp3->size()<<endl;

tempObj.temp3->push_back(333);
cout<<"temp1的长度: "<<tempObj.temp3->size()<<endl;

return 0;
}

C++ 智能指针 shared_ptr、make_shared用法_ios_02


举报

相关推荐

0 条评论