C++ make_shared() shared_prt()用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010164190/article/details/88315709

  shared_ptr很好地消除了显式的delete调用,如果读者掌握了它的用法,可以肯定delete将会在你的编程字典中彻底消失 。但这还不够,因为shared_ptr的构造还需要new调用,这导致了代码中的某种不对称性。虽然shared_ptr很好地包装了new表达式,但过多的显式new操作符也是个问题,用make_shared()来消除显式的new调用。

  make_shared()函数可以接受最多10个参数,然后把它们传递给类型T的构造函数,创建一个shared_ptr<T>的对 象并返回。make_shared()函数要比直接创建shared_ptr对象的方式快且高效,因为它内部仅分配一次内存,消除了shared_ptr 构造时的开销。

make_shared()栗子:

1.demo_01.cpp
#include <iostream>
#include <vector>
using namespace std;
 
class StructA{
public:
  int i;
  string str;
  //StructA(): i(100/*int()*/){//初始化列表
  StructA(int i){
    this->i = i;
    cout<< "StructA(int), line = "<< __LINE__<< endl;
  };

  StructA(string str){
    this->str = str;
    cout<< "StructA(string), line = "<< __LINE__<< endl;
  };
  
  ~StructA(){ cout <<"~StructA "<< endl;};
  
  void show(){
    cout << "show() is Called. line = "<< __LINE__<< endl;
  }
} ;
 
int main(int argc, const char * argv[]){
  //make_shared自动申请对象及内存,自动释放,不用手动执行new和delete
  shared_ptr<StructA> pA = make_shared<StructA>(123);
  cout << "pA->i = " << pA->i << endl;

  shared_ptr<StructA> pB = make_shared<StructA>("Hello Kitty!");
  cout << "pB->str = " << pB->str << endl;
  pB->show();

  auto t = make_shared<StructA>("Number One!");
  cout << "t->str = " << t->str << endl;
  t->show();
  
  return 0;
}

2.demo_02.cpp
#include <iostream>
#include <vector>
#include <map> 
using namespace std;

class StructA{
public:
  int i;
  //StructA(): i(100/*int()*/){//初始化列表
  StructA(int i){
    this->i = i;
    cout<< "StructA(int), line = "<< __LINE__<< endl;
  };
  
  ~StructA(){ cout <<"~StructA "<< endl;};
  
  void show(){
    cout << "show() is Called. line = "<< __LINE__<< endl;
  }
  template<class T>
  T add(T x){
    return x;
  }
} ;

int main(){ 
  map<int, shared_ptr<StructA>> mStrA;
  //插入map映射key-value数据
  mStrA[0] = make_shared<StructA>(123);
  mStrA[1] = make_shared<StructA>(456);
  mStrA.insert(pair<int, shared_ptr<StructA>>(2,make_shared<StructA>(789)));
  mStrA.insert(pair<int, shared_ptr<StructA>>(3,make_shared<StructA>(333)));
  
  mStrA[0]->show();
  //遍历方式1
  for(auto &mA : mStrA){
    cout << mA.first << " " << mA.second->i << endl;
    //mA.second->show();
  }
  cout << endl;
  
  //遍历方式2
  map<int, shared_ptr<StructA>>::iterator iter;
  for(iter = mStrA.begin(); iter != mStrA.end(); iter++){
    cout << iter->first << " "<<iter->second->i<<endl;
    //iter->second->show();
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/u010164190/article/details/88315709