Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

c++ - I need a way to return out of a function without having to return the "return type"

I have a function that allocates memory and then returns the pointer to that memory address. I'm allocating an array of char, the argument that they pass into the function will be the array size. Now the problem is that if they pass 0 as the argument for the size to dynamically allocate, then I want to exit/return out of that function, but the function itself returns a char * so I am not able to do something like return -1;, how would I go around this, while at the same time keeping the function and doing logic to allocate the memory in there? Is there a way?

char *alloate_memory(int x) { // This will assume you are allocating memory for a C-style string
    if (x == 0)
        return ;
    char *mem{ new char[x] };
    return mem;
}
question from:https://stackoverflow.com/questions/65851336/i-need-a-way-to-return-out-of-a-function-without-having-to-return-the-return-ty

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...