#include

时间:2023-03-10 05:17:09
#include <boost/shared_array.hpp>

共享数组

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

 #include <iostream>
#include <boost/shared_array.hpp> class runclass
{
public:
int i = ;
public:
runclass(int num) :i(num)
{
std::cout << "i creator " << i << std::endl;
}
runclass()
{
std::cout << "i creator " << i << std::endl;
}
~runclass()
{
std::cout << "i delete " << i << std::endl;
}
void print()
{
std::cout << "i=" << i << std::endl;
}
}; void testfunarray()
{
boost::shared_array<runclass>p1(new runclass[]);
boost::shared_array<runclass>p2(p1);//浅拷贝,内存共享,没有调用构造函数
} void main()
{
testfunarray();
}