小编Rox*_*nne的帖子

noexcept 的不同用途

在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?我看到两种可能性:

  1. 调用f()在编译时被评估,因为它被标记constexpr,它返回true并作为结果g()被标记noexcept。
  2. 编译器无法确定f()无法抛出异常,因为f()未标记noexcept。结果g()没有被标记noexcept。

哪一种会发生?如何为 选择一种或其他行为noexcept?

c++ noexcept c++11

4
推荐指数
1
解决办法
59
查看次数

多线程双缓冲区

我有一个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 …

c++ multithreading locking

2
推荐指数
1
解决办法
4470
查看次数

标签 统计

c++ ×2

c++11 ×1

locking ×1

multithreading ×1

noexcept ×1