在The C++ Programming Language一书中写道,您可以将函数声明为有条件的noexcept。例如:
template<typename T>
void my_fct(T& x) noexcept(std::is_pod<T>::value);
Run Code Online (Sandbox Code Playgroud)
noexcept采用一个必须是常量表达式的谓词(在示例中std::is_pod<T>::value)。
然而,书中也写到:
该
noexcept()运营商需要一个表达式作为其参数和返回true如果编译器知道它不能乱扔和false其他。
考虑到这一点,请考虑:
constexpr bool f() { return true; }
void g() noexcept(f())
{
f();
}
Run Code Online (Sandbox Code Playgroud)
是否g()标记为noexcept?我看到两种可能性:
f()在编译时被评估,因为它被标记constexpr,它返回true并作为结果g()被标记noexcept。f()无法抛出异常,因为f()未标记noexcept。结果g()没有被标记noexcept。哪一种会发生?如何为 选择一种或其他行为noexcept?
我有一个Buffer类实现了考虑多线程设计的双缓冲区模式:
class Buffer {
public:
void write(size_t idx, float value) {
std::lock_guard<std::mutex> lk(mut);
(*next)[idx] = value; // write to next buffer
}
float read(size_t idx) const {
std::lock_guard<std::mutex> lk(mut);
return (*current)[idx]; // read from current buffer
}
void swap() noexcept {
std::lock_guard<std::mutex> lk(mut);
std::swap(current, next); // swap pointers
}
Buffer() : buf0(32), buf1(32), current(&buf0), next(&buf1) { }
private:
std::vector<float> buf0, buf1; // two buffers
std::vector<float> *current, *next;
mutable std::mutex mut;
};
Run Code Online (Sandbox Code Playgroud)
此类包含两个缓冲区。缓冲区始终通过指针访问:
current指针指定。next …