---- 整理自狄泰软件唐佐林老师课程
编写程序判断一个变量是不是指针?
#include
#include
using namespace std;
void test(int i) {
cout << "void test(int i)" << endl;
}
template
<typename T>
void test(T v) {
cout << "void test(T v)" << endl;
}
void test(...) {
cout << "void test(...)" << endl;
}
int main(int argc, char *argv[]) {
int i = 0;
test(i);
return 0;
}

将变量分为两类:指针 VS 非指针

根据参数的匹配,返回true就是指针,变参函数返回false就不是指针。


变参函数无法解析对象参数,可能造成程序崩溃
#include
#include
using namespace std;
class Test
{
public:
Test()
{
}
virtual ~Test()
{
}
};
template
<typename T>
char IsPtr(T* v) // match pointer
{
return 'd';
}
int IsPtr(...) // match non-pointer
{
return 0;
}
#define ISPTR(p) (sizeof(IsPtr(p)) == sizeof(char))
int main(int argc, char *argv[])
{
int i = 0;
int* p = &i;
cout << "p is a pointer: " << ISPTR(p) << endl; // true
cout << "i is a pointer: " << ISPTR(i) << endl; // false
Test t;
Test* pt = &t;
cout << "pt is a pointer: " << ISPTR(pt) << endl; // true
cout << "t is a pointer: " << ISPTR(t) << endl; // false
return 0;
}

如果构造函数中抛出异常会发生什么情况?
不要在构造函数中抛出异常
当构造函数可能产生异常时,使用二阶构造模式
#include
#include
using namespace std;
class Test
{
public:
Test()
{
cout << "Test()" << endl;
throw 0;
}
virtual ~Test()
{
cout << "~Test()" << endl;
}
};
int main(int argc, char *argv[])
{
Test* p = reinterpret_cast<Test*>(1);
try
{
p = new Test();
}
catch(...)
{
cout << "Exception..." << endl;
}
cout << "p = " << p << endl;
return 0;
}

注:reinterpret 是“重新解释”的意思,顾名思义,reinterpret_cast 这种转换仅仅是对二进制位的重新解释,不会借助已有的转换规则对数据进行调整,非常简单粗暴。
http://c.biancheng.net/view/2343.html