版权声明:本文为博主原创文章,转载请注明出处! https://blog.csdn.net/qq_27513221/article/details/79805813
一、面试问题——指针的判别
编写程序判断一个变量是不是指针?
拾遗:
- C++中仍然支持C语言中的可变参数函数
- C++编译器的匹配调用优先级
- 重载函数
- 函数模板
- 变参函数
思路:
- 将变量分为两类:指针vs非指针
- 编写函数:
- 指针变量调用时返回
true
- 非指针变量调用时返回
false
- 指针变量调用时返回
函数模板与变参函数的化学反应
template <typename T>
bool IsPtr(T* v){ //match pointer
return true;
}
bool IsPtr(...){ //match non-pointer
return false;
}
编程实验:指针判断
#include<iostream>
#include<string>
using namespace std;
class Test{
public:
Test(){
}
virtual ~Test(){
}
};
template <typename T>
char IsPtr(T* v){
return 'd';
}
int IsPtr(...){ //变参函数无法很好地处理对象函数
return 0;
}
//非常灵活的一种测试方法,让编译器精确匹配函数而不用进行实际地调用
#define ISPTR(p) (sizeof(IsPtr(p)) == sizeof(char))
int main(){
int i = 0;
int* p = &i;//单纯的指针判断
cout << "p is a pointer:" << ISPTR(p) << endl;
cout << "i is a pointer:" << ISPTR(i) << endl;
Test t;
Test* pt = &t;//自定义指针判断
cout << "pt is a pointer:" << ISPTR(pt) << endl;
cout << "t is a pointer:" << ISPTR(t) << endl;
return 0;
}
打印结果:
p is a pointer:1
i is a pointer:0
pt is a pointer:1
t is a pointer:0
二、构造中的异常
构造函数中抛出异常
- 构造过程立即停止
- 当前对象无法生成
- 析构函数不会被调用
- 对象所占用的空间立即被收回
工程项目中的建议
- 不要在构造函数中抛出异常
- 当构造函数可能产生异常时,使用二阶构造模式
编程实验:构造中的异常
#include<iostream>
using namespace std;
class Test{
public:
Test(){
cout << "Test()" << endl;
throw 0;
}
virtual ~Test(){ //如无意外务必注明virtual
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;
}
打印结果:
Test()
Exception...
p = 0x1
析构中的异常:
(一定避免在析构函数中抛出异常!!)
析构函数中异常将导致:
对象所使用的资源无法完全释放
三、总结
- C++中依然支持变参函数
- 变参函数无法很好地处理对象参数
- 利用函数模版和变参函数能够判断指针变量
- 构造函数和析构函数中不要抛出异常