tongko
tongko

Reputation: 149

Will statements after "return" keyword be executed?

I'm C++ beginner, would like to know the impact of this scenario:

PCONSOLE_SCREEN_BUFFER_INFOEX GetConsoleInfo(void) {
    WaitForSingleObject(m_hSync);   // m_hSync is HANDLE to mutex created using CreateMutex()

    return m_pcsbi;    // m_pcsbi is of type PCONSOLE_SCREEN_BUFFER_INFOEX

    ReleaseMutex(m_hSync);      // <== will this line be executed?
}

Wonder will the [ReleaseMutex()] be executed?

Upvotes: 2

Views: 173

Answers (5)

iavr
iavr

Reputation: 7637

This is exactly where RAII is needed, as implemented by std::unique_lock:

PCONSOLE_SCREEN_BUFFER_INFOEX GetConsoleInfo()
{
    static std::mutex m_hSync;
    std::unique_lock<std::mutex> lock{m_hSync};

    return m_pcsbi;    // m_pcsbi is of type PCONSOLE_SCREEN_BUFFER_INFOEX

    // mutex is released implicitly here
}

Releasing a mutex is something that should be done automatically at end of scope, including as well cases where an exception is thrown (during stack unwinding). Only desctructors can be called at that point and std::unique_lock's destructor exactly releases the mutex.

Upvotes: 0

MSalters
MSalters

Reputation: 179907

There's no way to get to that code in your case. If you have a conditional return (e.g. if (ptr==nullptr) return; ) then there are of course conditions in which the return will be skipped. But an unconditional return will be the last of the statements executed.

However, RAII style cleanup does happen after return.

Upvotes: 6

Elfayer
Elfayer

Reputation: 4561

No, after a return statement, the destructors of the scope Objects will be called and the program will exit the function.

int main() { //Step 1
   GetConsoleInfo(); //2

   return (0); //6
}

PCONSOLE_SCREEN_BUFFER_INFOEX GetConsoleInfo(void) { //3
    WaitForSingleObject(m_hSync); //4

    return m_pcsbi; //5

    ReleaseMutex(m_hSync);
}

Maybe you should do something like :

int main() {
   WaitForSingleObject(m_hSync);
   GetConsoleInfo();
   ReleaseMutex(m_hSync);
   return (0);
}

PCONSOLE_SCREEN_BUFFER_INFOEX GetConsoleInfo(void) {
    return m_pcsbi;
}

Upvotes: 2

franklinexpress
franklinexpress

Reputation: 1189

No but you can have exceptions

example with if statement:

   PCONSOLE_SCREEN_BUFFER_INFOEX GetConsoleInfo(void) {
     WaitForSingleObject(m_hSync);   // m_hSync is HANDLE to mutex created using CreateMutex()


     //if(statement)
            return m_pcsbi;    // m_pcsbi is of type PCONSOLE_SCREEN_BUFFER_INFOEX
     //else
          ReleaseMutex(m_hSync);      // if the statement is false, it will skip return and execute this line
}

Upvotes: 0

JMCampos
JMCampos

Reputation: 653

In that specific scenario no. You need to release the mutex before leaving the function.

Upvotes: 2

Related Questions