首先我定义了一个结构体
typedef struct st_BarSeriesInfo
{
QString type;
QVector<double> value;
QStringList categories;
double maxHeight;
st_BarSeriesInfo(QString type)
{
this->type = type;
}
st_BarSeriesInfo( )
{
type ="";
maxHeight =0;
}
void clear()
{
memset(this, 0x00, sizeof(st_BarSeriesInfo));
}
}BarSeriesInfo;
需要一个清空结构体的函数,网上给出的答案都是:
void clear()
{
memset(this, 0x00, sizeof(st_Defect));
}
扩展:
如果是结构体数组:struct sample_struct TEST[10];
memset(TEST,0,sizeof(struct sample_struct)*10);
调用的时候就报错了
m_totalInfo = BarSeriesInfo();
......
m_totalInfo.clear();
//这里报错
m_totalInfo.categories << type;
报错原因:
为什么有些类型无法使用memset初始化?
关于struct 结构体与memset的狗血教训
总结:
0. POD对象:A Plain Old Data Structure in C++ is an aggregate class that contains only PODS as members, has no user-defined destructor, no user-defined copy assignment operator, and no nonstatic members of pointer-to-member type.
1、memset只适用于POD类型结构。对非POD类型,用构造函数来初始化。
2、memset让非POD崩溃的根本原因,是把里面的数据(例如虚函数表),即指向虚函数表的指针置null,导致后续的一些函数调用会访问到非法内存,这才是崩溃的根本原因。
所以
不要用memset处理非POD对象!!!!!
修改代码如下:
typedef struct st_BarSeriesInfo
{
QString type;
QVector<double> value;
QStringList categories;
double maxHeight;
st_BarSeriesInfo(QString type)
{
this->type = type;
}
st_BarSeriesInfo( )
{
type ="";
maxHeight =0;
}
void clear()
{
//memset(this, 0x00, sizeof(st_BarSeriesInfo));
value.clear();
QVector<double>().swap(value);
maxHeight = 0.0;
categories.clear();
type = "";
}
}BarSeriesInfo;