有时不想用SEH,主要是考虑到效率上的问题。这时,有两种可行的替代,各有利弊。其中,func2的while(false)还会导致VS2005在Level 4 (/W4)下的一个警告:warning C4127: conditional expression is constant。
#include <iostream>
#include <ctime>
void func1()
{
int *pi = new int(0);
srand((unsigned int)time(NULL));
for (; ;)
{
*pi = rand() % 3;
if (*pi == 2)
{
std::cout << "break from func1..." << std::endl;
// don't return;
break;
}
std::cout << "func1: " << *pi << std::endl;
break;
}
delete pi;
}
void func2()
{
int *pi = new int(0);
srand((unsigned int)time(NULL));
do
{
*pi = rand() % 3;
if (*pi == 2)
{
std::cout << "break from func2..." << std::endl;
// don't return;
break;
}
std::cout << "func2: " << *pi << std::endl;
}
while (false);
delete pi;
}
void func3()
{
int *pi = new int(8);
__try
{
std::cout << "__try: " << *pi << std::endl;
}
__finally
{
std::cout << "__finally" << std::endl;
delete pi;
}
}
int main()
{
func1();
func2();
func3();
return 0;
}
#include <ctime>
void func1()
{
int *pi = new int(0);
srand((unsigned int)time(NULL));
for (; ;)
{
*pi = rand() % 3;
if (*pi == 2)
{
std::cout << "break from func1..." << std::endl;
// don't return;
break;
}
std::cout << "func1: " << *pi << std::endl;
break;
}
delete pi;
}
void func2()
{
int *pi = new int(0);
srand((unsigned int)time(NULL));
do
{
*pi = rand() % 3;
if (*pi == 2)
{
std::cout << "break from func2..." << std::endl;
// don't return;
break;
}
std::cout << "func2: " << *pi << std::endl;
}
while (false);
delete pi;
}
void func3()
{
int *pi = new int(8);
__try
{
std::cout << "__try: " << *pi << std::endl;
}
__finally
{
std::cout << "__finally" << std::endl;
delete pi;
}
}
int main()
{
func1();
func2();
func3();
return 0;
}
测试一下std::vector的插入、遍历效率
std::vector针对结构成员的排序



