在写程序的时候,需要对类数组中的值从数组后面移动到数组前面,但类中成员变量包含vector等容器,因此就写了一个测试程序验证了一下,当类数组在移动的过程中,类容器变量是否发生移动。
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <set>
#include <vector>
using namespace std;
class SET{
public:
int a;
int b;
vector<int> ab;
bool operator == (const SET &B)const {
return a == B.a;
}
bool operator < (const SET &B)const {
if(a == B.a)
return false;
else
return -(a - B.a);
}
SET(){
a = -1;
b = -1;
}
SET(int aa,int bb){
a = aa;
b = bb;
}
SET(int aa,int bb,vector<int> c){
a = aa;
b = bb;
ab = c;
}
void init(SET s){
a = s.a;
b = s.b;
ab = s.ab;
}
};
ostream &operator<<(ostream &os,const SET &s){
os << "a: "<< s.a <<"; vector: ";
int num = 10<s.ab.size()?10:s.ab.size();
for(int i=0;i<num;i++)
os<<s.ab[i]<<' ';
os <<endl;
}
int main ()
{
vector<SET>::iterator itv;
SET *myvector = new SET[20];
// SET *myvector = (SET*)malloc(20*sizeof(SET));
cout <<"sizeof(SET):" <<sizeof(SET)<<endl;
cout << myvector[0];
for(int i=0;i<20;i++)
myvector[i].init(SET(i,i+1,vector<int>(i*1000,i)));
cout << myvector[1];
memcpy(myvector,&myvector[16],sizeof(SET)*4);
cout <<"sizeof(SET):" <<sizeof(SET)<<endl;
cout << myvector[1];
delete [] myvector;
return 0;
}
经测试,当数组中类的位置发生移动时,其包含的容器成员变量也会跟着移动。
另外,当使用new申请类数组空间时,会自动调用默认构造函数,而使用malloc申请时则不会。