Làm cách nào để bảo vệ bản thân khỏi việc sử dụng đối tượng không được tạo hoàn toàn khi sử dụng ngoại lệ? Tôi có nên bắt người xây dựng không? Hoặc có thể đó là thực hành xấu? Nếu tôi bắt được đối tượng constructor sẽ được tạo.C++ bắt ngoại lệ trong hàm tạo
#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)
};
Tại sao bạn đặt các hạn chế hoàn toàn tùy ý cho chính mình? –