函数可以在return语句后继续吗?

函数可以在return语句后继续吗?

问题描述:

考虑以下C ++函数:

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);
}

现在,出于这个问题,假定 loadedBMP 是先前声明的全局变量.

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

这是我的问题:
有没有一种方法可以让函数在 return 语句后继续运行?就此功能而言,有没有办法让最后一行 SDL_FreeSurface(loadedBMP)返回 loadedBMP 之后运行?>

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?

否.但是,是的.return语句后将不执行该函数的任何行.但是,return语句也标记了函数的结尾,因此也标志了作用域的结尾.因此,如果您设法在堆栈上放置一个对象(例如局部变量),则会调用该析构函数.

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.

但这不是您想要的.即使在return语句之后,您也不想释放返回的内容.

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