Can a function continue after a return statement?

一世执手 提交于 2019-12-14 04:14:49

问题


Consider the following C++ function:

SDL_Surface* loadBMP(std::string path, SDL_Surface* loadedBMP){
    //Load bitmap
    SDL_Surface* loadedBMP = SDL_LoadBMP(path);
    if (loadedBMP == NULL){
        printf("Unable to load image %s! SDL Error: %s\n", path.c_str(), SDL_GetError());
    }

    return loadedBMP;

    //Magic
    SDL_FreeSurface(loadedBMP);
}

Now, for the sake of this question, assume that loadedBMP is a previously declared global variable.

Here is my question: Is there a way to let a function continue running after a return statement? In terms of this function, is there a way to have the final line, SDL_FreeSurface(loadedBMP), run after returning loadedBMP?


回答1:


No. But yes. No line of the function will be executed after the return statement. However, the return statement also marks the end of the function and therefor the end of the scope. So if you manage to have an object on the stack (like a local variable), it's destructor will be called.

But that's not what you want. You don't want to free what you return, not even after the return statement.




回答2:


No, since at assembly level the return instruction gives the control back to the caller so it inherently exits the scope.

In addition to this, freeing an SDL_Surface which you are returning leaves you with a dangling surface which could not be used so I don't see the purpose of doing it.




回答3:


what you think you want: To run code after the return statement.

what you probably want: To prevent memory leak by ensuring a resource is always released.

For that, use a std::unique_ptr. roughly(pseudocode):

std::unique_ptr<SDL_Surface,SDL_FreeSurface> loadBMP(std::string path){
    //Load bitmap

    std::unique_ptr<SDL_Surface,SDL_FreeSurface> loadedBMP{SDL_LoadBMP(path)};
    if (!loadedBMP){
        printf("Unable to load image %s! SDL Error: %s\n", path.c_str(), SDL_GetError());
    }

    return loadedBMP;
}



回答4:


It executes next statements after return, as i have faced similar situation in postgres with language as C, i sent a data set then i wanted to delete all records after returning the set. it did well for me.

For Clarification keep print statements.




回答5:


No. The reason is that after return the value your data type then next statement not work.The compiler ignore it.



来源:https://stackoverflow.com/questions/28352254/can-a-function-continue-after-a-return-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!