I need a way to return out of a function without having to return the "return type"
The correct way to signal that a pointer doesn't point to valid memory is with a nullptr
. So your return
statement in the case that the memory allocation fails would simply be:
return nullptr;
Of course, the caller of the function needs to make sure that the returned pointer is not nullptr
before they try to dereference it.
The canonically correct way to do this given that the input parameter must be an int
is either:
char *alloate_memory(int x) { // This will assume you are allocating memory for a C-style string
if (x <= 0)
throw std::bad_alloc();
return new char[x];
}
or
char *alloate_memory(int x) { // This will assume you are allocating memory for a C-style string
if (x <= 0)
return nullptr;
return new(std::nothrow) char[x];
}
Depending on if you want it to throw an exception or return nullptr on error. I recommend you pick one and not mix them for consistency
The common practice would be to return nullptr
:
char *alloate_memory(int x) { // This will assume you are allocating memory for a C-style string
if (x == 0)
return nullptr; // here!
char *mem{ new char[x] };
return mem;
}