我正在尝试编写一个必须检查正确初始化的cpp模块.它需要使用至少一个非NULL指针进行初始化.如果没有,它需要删除自己并返回NULL.以下程序似乎确实破坏了对象,但它似乎没有返回null.
这里发生了什么?
#include <iostream>
using namespace std;
class cmod {
public:
cmod(int *p1=NULL, int *p2=NULL)
{
if( p1 == NULL && p2 == NULL){
delete(this);
}
else
cout << __func__ << ": Initialized" << endl;
if(p1 != NULL)
cout << "*p1 = " << *p1 << endl;
if(p2 !=NULL)
cout << "*p2 = " << *p2 << endl;
}
~cmod()
{
cout << __func__ << ": Destroyed" << endl;
}
};
int main()
{
int a=10, b = 20;
cmod *p = new cmod();
if(p == NULL)
cout << __func__ << ": Unable to initialize" << endl;
cmod *p1 = new cmod(&a, &b);
}
Run Code Online (Sandbox Code Playgroud)
以下是输出:
~cmod: Destroyed
cmod: Initialized
*p1 = 10
*p2 = 2
Run Code Online (Sandbox Code Playgroud)
为什么线Unable to initialize不打印?
更新:看完所有答案后,我想出了以下内容:
#include <iostream>
using namespace std;
class cmod {
private:
int *l1,*l2;
cmod()
{
throw std::runtime_error("Failed to construct object. No arguements");
}
cmod(int *p1=NULL, int *p2=NULL)
{
if( p1 == NULL && p2 == NULL){
throw std::runtime_error("Failed to construct object. Both args NULL");
}
else
cout << __func__ << ": Initialized" << endl;
if(p1 != NULL)
l1 = p1;
if(p2 !=NULL)
l2 = p2;
}
~cmod()
{
cout << __func__ << ": Destroyed" << endl;
}
public:
static cmod * initialize(int *p1=NULL, int *p2 = NULL)
{
if( p1 == NULL && p2 == NULL){
return NULL;
}
else
return new cmod(p1,p2);
}
void dump()
{
cout << __func__ << ": a = " << *l1 << endl;
cout << __func__ << ": b = " << *l2 << endl;
}
int main()
{
int a=10, b = 20;
cmod *p = cmod::initialize(NULL, NULL);
if(p == NULL)
cout << __func__ << ": Unable to initialize" << endl;
cmod *p1 = cmod::initialize(&a, &b);
if(p!=NULL)
p->dump();
if(p1!=NULL)
p1->dump();
}
Run Code Online (Sandbox Code Playgroud)
这是一个正确的方法吗?
har*_*ald 10
构造函数将始终返回其类的对象,除非它抛出异常.所以你要做的就是这样:
cmod(int *p1=NULL, int *p2=NULL)
{
if( p1 == NULL && p2 == NULL)
throw std::runtime_error("Failed to construct object.");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
712 次 |
| 最近记录: |