共享数组

共享数组的行为类型于共享指针。关键不同在于共享数组在析构时,默认使用delete[]操作符来释放所含的对象。因为这个操作符只能用于数组对象,共享数组必须通过动态分配的数组的地址来初始化。共享数组对应的类型是boost::shared_array,它的定义在boost/shared_array.hpp里。

 

 1 #include <iostream>
 2 #include <boost/shared_array.hpp>
 3 
 4 class runclass
 5 {
 6 public:
 7     int i = 0;
 8 public:
 9     runclass(int num) :i(num)
10     {
11         std::cout << "i creator " << i << std::endl;
12     }
13     runclass()
14     {
15         std::cout << "i creator " << i << std::endl;
16     }
17     ~runclass()
18     {
19         std::cout << "i delete " << i << std::endl;
20     }
21     void print()
22     {
23         std::cout << "i=" << i << std::endl;
24     }
25 };
26 
27 void testfunarray()
28 {
29     boost::shared_array<runclass>p1(new runclass[5]);
30     boost::shared_array<runclass>p2(p1);//浅拷贝,内存共享,没有调用构造函数
31 }
32 
33 void main()
34 {
35     testfunarray();
36 }

 

相关文章:

  • 2022-12-23
  • 2021-08-14
  • 2022-03-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-24
  • 2021-11-01
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案