1.该例题出自于6.7节的While的循环的使用(P178页):
int arr1[5]={0,1,2,3,4};
int *source=arr1;
size_t sz = sizeof(arr1)/sizeof(*arry1);
int *dest=new int[sz](0);
while(source != arr1+sz)
{
*dest++=*source++;
}
delete []dest;
注意,最后一句调用将会出现运行时错误,因为现在dest指针指向的是dest[5],即第6个不存在的元素,如果现在使用delete删除dest指向的数组的话,将会删除未知的内存位置,解决办法是使用一个临时变量来保存dest指针的初始位置。
int arr1[5]={0,1,2,3,4};
int *source=arr1;
size_t sz = sizeof(arr1)/sizeof(*arry1);
int *dest=new int[sz](0);
int *temp=dest;
while(source != arr1+sz)
{
*dest++=*source++;
}
delete []temp;
dest=null;
2.这一个例题出现在8.2的P248页:
int val;
while(cin>>val,!cin.eof())
{
if(cin.bad())
{
throw runtime_error("IO stream corruped!");
}
if(cin.fail())
{
cerr<<"bad data,try agin!";
cin,clear(istream::failbit);
cin.ignore(numeric_limits<streamsize>::max(),'\n');
continue;
}
}
如果输入一个无效的整形数据流,将会造成无线循环,问题的根源是clear的解释,clear跟setstate的作用相似,这里是设置流的failbit标志位为1,则就是说该流出现了一个fail错误,而不是书上所说的清除failbit的状态位。
void stream::clear( iostate flags = ios::goodbit );The function clear() does two things:
it clears all io_stream_state_flags associated with the current stream,
and sets the flags denoted by flags
int val;
while(cin>>val,!cin.eof())
{
if(cin.bad())
{
throw runtime_error("IO stream corruped!");
}
if(cin.fail())
{
cerr<<"bad data,try agin!";
cin,clear(istream::goodbit);
cin.ignore(numeric_limits<streamsize>::max(),'\n');
continue;
}
}