Why are mutexes and condition variables trivially copyable?

后端 未结 3 1192
野的像风
野的像风 2021-02-13 20:34

LWG 2424 discusses the undesirable status of atomics, mutexes and condition variables as trivially copyable in C++14. I appreciate that a fix is already lined up, but std::mutex

3条回答
  •  青春惊慌失措
    2021-02-13 21:19

    Not all implementations provide a nontrivial destructor for mutex. See libstdc++ (and assume that __GTHREAD_MUTEX_INIT has been defined):

      // Common base class for std::mutex and std::timed_mutex
      class __mutex_base
      {
      // […]
    #ifdef __GTHREAD_MUTEX_INIT
        __native_type  _M_mutex = __GTHREAD_MUTEX_INIT;
    
        constexpr __mutex_base() noexcept = default;
    #else
      // […]
    
        ~__mutex_base() noexcept { __gthread_mutex_destroy(&_M_mutex); }
    #endif
      // […]
      };
    
      /// The standard mutex type.
      class mutex : private __mutex_base
      {
        // […]
        mutex() noexcept = default;
        ~mutex() = default;
    
        mutex(const mutex&) = delete;
        mutex& operator=(const mutex&) = delete;
      };
    

    This implementation of mutex is both standard conforming and trivially copyable (which can be verified via Coliru). Similarly, nothing stops an implementation from keeping condition_variable trivially destructible (cf. [thread.condition.condvar]/6, although I couldn't find an implementation that does).

    The bottom line is that we need clear, normative guarantees, and not clever, subtle interpretations of what condition_variable does or doesn't have to do (and how it has to accomplish that).

提交回复
热议问题