Is this correct usage of static when auto deletion is expected in C++?

Viewed 63

The code snippet is from Wikipedia.

void WriteToFile(const std::string& message) {
  // |mutex| is to protect access to |file| (which is shared across threads).
  static std::mutex mutex;

  // Lock |mutex| before accessing |file|.
  std::lock_guard<std::mutex> lock(mutex);

  // Try to open file.
  std::ofstream file("example.txt");
  if (!file.is_open()) {
    throw std::runtime_error("unable to open file");
  }

  // Write |message| to |file|.
  file << message << std::endl;

  // |file| will be closed first when leaving scope (regardless of exception)
  // mutex will be unlocked second (from lock destructor) when leaving scope
  // (regardless of exception).
}

This snippet is to demonstrate RAII. When leaving the WriteToFile scope, mutex will be unlocked. My question is, as mutex is declared as static, it should exist until the whole program exit, right? So why would the mutex destructor be called when leaving the scope? I think the mutex destructor only be called once after the main program exit, as the C++ standard specified.

Is there anyone explain this to me?

1 Answers

it should exist until the whole program exit, right?

yes


So why would the mutex destructor be called when leaving the scope?

mutex destructor will not be called. lock guard destructor will be called and it will unlock the mutex.

from cppreference

When a lock_guard object is created, it attempts to take ownership of the mutex it is given. When control leaves the scope in which the lock_guard object was created, the lock_guard is destructed and the mutex is released.


I think the mutex destructor only be called once after the main program exit

yes

Related