Come posso proteggermi dall'usare un oggetto che non è completamente creato quando si usano le eccezioni? Devo prendere in costruttore? O forse è una cattiva pratica? Se prenderò in oggetto costruttore verrà creato.C++ che intercetta l'eccezione nel costruttore
#include <stdio.h>
class A
{
public:
A()
{
try {
throw "Something bad happened...";
}
catch(const char* e) {
printf("Handled exception: %s\n", s);
}
// code continues here so our bad/broken object is created then?
}
~A()
{
printf("A:~A()");
}
void Method()
{ // do something
}
};
void main()
{
A object; // constructor will throw... and catch, code continues after catch so basically we've got
// broken object.
//And the question here:
//
//* is it possible to check if this object exists without catching it from main?
// &object still gives me an address of this broken object so it's created but how can I protect myself
// from using this broken object without writing try/catch and using error codes?
object.Method(); // something really bad. (aborting the program)
};
Perché ponete restrizioni completamente arbitrarie su di voi? –