首页 > 解决方案 > 为什么 libcxx 的 condition_variable 是 constexpr 和 noexcept,但在 The Standard 中却不是?

问题描述

https://github.com/llvm-mirror/libcxx/blob/master/include/__mutex_base#L290

class _LIBCPP_TYPE_VIS condition_variable
{
    __libcpp_condvar_t __cv_ = _LIBCPP_CONDVAR_INITIALIZER;
public:
    _LIBCPP_INLINE_VISIBILITY
    _LIBCPP_CONSTEXPR condition_variable() _NOEXCEPT = default;

但标准将其声明为

class condition_variable {
public:
    condition_variable();
    ~condition_variable();

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/n4849.pdf

并且condition_variable()可能会抛出。

libcxx 与 C++ 标准不兼容,还是我错了?

标签: c++stllanguage-lawyercondition-variable

解决方案


noexcept如果实现不会抛出异常,则允许将实现添加到非虚拟函数,请参阅 C++17 标准(草案 N4659)的[res.on.exception.handling]/5

但是,不允许将实现添加constexpr到函数中。见[constexpr.functions]/1。另见LWG 问题 2013

std::condition_variable::condition_variable()被指定为既不constexpr,也不noexcept,但没有任何情况下它必须抛出异常。请参阅[thread.condition.condvar]

所以,noexcept很好,但constexpr不是。但是,标记constexpr不应该标记的功能是一种常见的不符合项。例如,GCC 故意声明数学函数constexpr,尽管它们不应该是。


推荐阅读