-
Constructor failure
Is there any way you can have a constructor fail so that the class isn't created? i.e.
Code:
Socket::Socket(char *addr, int port)
{
if (connect(addr, port) == FAIL) {
fail;
}
}
Code:
int main()
{
Socket *sock = new Socket("google.com", 80);
if (sock == NULL) {
printf("It didn't work\n");
return 0;
}
}
-
You could throw an exception.
Also in your example code new won't return a NULL if it fails. It'll throw an exception.
Another option is to just put the object into a failed state.
-
Or make an empty constructor and use a Create() member function which returns a bool.
-
throwing an exception is a easy way
or you can use safe_bool
Code:
class A
{
struct dummy{ void non_null(){} };
typedef void (dummy::*safe_bool)();
bool init();
public:
A():is_failed_(false) { is_failed_ = init(); }
bool failed() const { return is_failed_; }
operator safe_bool() const
{
return (this->failed())? 0 : &dummy::non_null;
}
private:
bool is_failed_;
};
int main()
{
A a;
if(a) cout<<"yes"<<endl; else cout<<"no"<<endl;
}
-
oh cause i picked up the topic...
in case that construction fails how can the memory be cleaned up?
afaik the memory remains - especially when creation of an member fails it cannot free memory of the "parent" object.
i think i read something that the member new and delete functions are used to clean such mess up again...
-