The general approach here is to throw an exception (and handle it somewhere above).
One of the advantages of the exception mechanism is that it allows you to raise an exception from the constructor of the class. In this case, you will never get to the situation where the pointer returns invalid. You must "get control" in the appropriate catch block. If the pointer was declared only in the try block (or in some other method called by the try block), it will be outside your scope in this catch block.
- .
, (, ), , , .
( Java 10 , ++ , , , , - )
class Myclass
{
public:
Myclass(int length)
{
if(length<=0) throw BadBufferSizeException("Bla bla bla");
this->buffer = (char*)malloc(length*sizeof(char));
}
void doSomething()
{
}
private:
char* buffer;
};
int main()
{
try
{
int len;
len = getLengthFromUser();
MyClass* pMyClass = new MyClass(len);
myClass->doSomething();
} catch(const Exception & e)
{
}
}
, pMyclass null try, try , , , , -(). , doSomething() try-catch, , .
, ++ ( ?) , , . .