C++ make_shared() shared_prt()用法

  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. 1.demo_01.cpp
  2. #include <iostream>
  3. #include <vector>
  4. using namespace std;
  5. class StructA{
  6. public:
  7. int i;
  8. string str;
  9. //StructA(): i(100/*int()*/){//初始化列表
  10. StructA( int i){
  11. this->i = i;
  12. cout<< "StructA(int), line = "<< __LINE__<< endl;
  13. };
  14. StructA( string str){
  15. this->str = str;
  16. cout<< "StructA(string), line = "<< __LINE__<< endl;
  17. };
  18. ~StructA(){ cout << "~StructA "<< endl;};
  19. void show(){
  20. cout << "show() is Called. line = "<< __LINE__<< endl;
  21. }
  22. } ;
  23. int main(int argc, const char * argv[]){
  24. //make_shared自动申请对象及内存,自动释放,不用手动执行new和delete
  25. shared_ptr<StructA> pA = make_shared<StructA>( 123);
  26. cout << "pA->i = " << pA->i << endl;
  27. shared_ptr<StructA> pB = make_shared<StructA>( "Hello Kitty!");
  28. cout << "pB->str = " << pB->str << endl;
  29. pB->show();
  30. auto t = make_shared<StructA>( "Number One!");
  31. cout << "t->str = " << t->str << endl;
  32. t->show();
  33. return 0;
  34. }
  35. 2.demo_02.cpp
  36. #include <iostream>
  37. #include <vector>
  38. #include <map>
  39. using namespace std;
  40. class StructA{
  41. public:
  42. int i;
  43. //StructA(): i(100/*int()*/){//初始化列表
  44. StructA( int i){
  45. this->i = i;
  46. cout<< "StructA(int), line = "<< __LINE__<< endl;
  47. };
  48. ~StructA(){ cout << "~StructA "<< endl;};
  49. void show(){
  50. cout << "show() is Called. line = "<< __LINE__<< endl;
  51. }
  52. template< class T>
  53. T add( T x){
  54. return x;
  55. }
  56. } ;
  57. int main(){
  58. map< int, shared_ptr<StructA>> mStrA;
  59. //插入map映射key-value数据
  60. mStrA[ 0] = make_shared<StructA>( 123);
  61. mStrA[ 1] = make_shared<StructA>( 456);
  62. mStrA.insert(pair< int, shared_ptr<StructA>>( 2,make_shared<StructA>( 789)));
  63. mStrA.insert(pair< int, shared_ptr<StructA>>( 3,make_shared<StructA>( 333)));
  64. mStrA[ 0]->show();
  65. //遍历方式1
  66. for( auto &mA : mStrA){
  67. cout << mA.first << " " << mA.second->i << endl;
  68. //mA.second->show();
  69. }
  70. cout << endl;
  71. //遍历方式2
  72. map< int, shared_ptr<StructA>>::iterator iter;
  73. for(iter = mStrA.begin(); iter != mStrA.end(); iter++){
  74. cout << iter->first << " "<<iter->second->i<< endl;
  75. //iter->second->show();
  76. }
  77. return 0;
  78. }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值