构造函数中出错,此错误在用户代码层面,可以capture,那么,构造函数应该怎么实现?
class A {
public:
A()
{
// some codes here
fd = socket(); // 此处出错,fd为-1
// more codes here
}
};如果不用exception,也不在类A中再增加比如errno之类的成员变量,怎么让类的使用者,第一时间知道出问题了?此处也假定,基于设计需要,fd = socket(),须在构造函数中。
第二个问题,delete到底做了什么?
#include <stdio.h>
class A {
public:
int i;
A(): i(9) // 注意,i在此被初始化为9
{
if (this != NULL) {
printf("this: %p\n", this);
delete this;
// this = NULL;
}
}
};
int main()
{
A *pa = new A;
if (pa == NULL) {
printf("pa is NULL\n");
} else {
printf("pa: %p, i: %d\n", pa, pa->i); // i能够被访问到,其值为0(int的0值)
// delete pa; // corruption for double free occurred
// printf("pa: %p\n", pa);
}
return 0;
}
本文探讨了在构造函数中遇到错误时如何进行处理,以及析构函数的作用和使用场景。通过实例展示了如何在构造函数中捕获错误,并在类的使用者能立即得知错误发生。同时,解释了析构函数的执行过程及其对资源管理的重要性。
5412

被折叠的 条评论
为什么被折叠?



