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;
}

三、若是定义在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用法 

猜你喜欢

转载自blog.csdn.net/u013288190/article/details/127175366