【C++编程】C++14新特性【续】

159 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第2天,点击查看活动详情

【C++编程】C++14新特性【续】

constexpr的限制

C++14相较于C++11对constexpr减少了一些限制:

C++11中constexpr函数可以使用递归,在C++14中可以使用局部变量和循环

constexpr int factorial(int n) { // C++14 和 C++11均可
   return n <= 1 ? 1 : (n * factorial(n - 1));
}

在C++14中可以这样做:

constexpr int factorial(int n) { // C++11中不可,C++14中可以
   int ret = 0;
   for (int i = 0; i < n; ++i) {
       ret += i;
  }
   return ret;
}

C++11中constexpr函数必须必须把所有东西都放在一个单独的return语句中,而constexpr则无此限制

constexpr int func(bool flag) { // C++14 和 C++11均可
   return 0;
}

在C++14中可以这样:

constexpr int func(bool flag) { // C++11中不可,C++14中可以
   if (flag) return 1;
   else return 0;
}

[[deprecated]]标记

C++14中增加了deprecated标记,修饰类、变、函数等,当程序中使用到了被其修饰的代码时,编译时被产生警告,用户提示开发者该标记修饰的内容将来可能会被丢弃,尽量不要使用。

struct [[deprecated]] A { };
​
int main() {
    A a;
    return 0;
}

当编译时,会出现如下警告:

~/test$ g++ test.cc -std=c++14
test.cc: In functionint main()’:
test.cc:11:7: warning: ‘Ais deprecated [-Wdeprecated-declarations]
     A a;
       ^
test.cc:6:23: note: declared here
 struct [[deprecated]] A {

二进制字面量与整形字面量分隔符

C++14引入了二进制字面量,也引入了分隔符,防止看起来眼花哈~

int a = 0b0001'0011'1010;
double b = 3.14'1234'1234'1234;

std::make_unique

我们都知道C++11中有std::make_shared,却没有std::make_unique,在C++14已经改善。

struct A {};
std::unique_ptr<A> ptr = std::make_unique<A>();

std::shared_timed_mutex与std::shared_lock

C++14通过std::shared_timed_mutex和std::shared_lock来实现读写锁,保证多个线程可以同时读,但是写线程必须独立运行,写操作不可以同时和读操作一起进行。

实现方式如下:

struct ThreadSafe {
    mutable std::shared_timed_mutex mutex_;
    int value_;
​
    ThreadSafe() {
        value_ = 0;
    }
​
    int get() const {
        std::shared_lock<std::shared_timed_mutex> loc(mutex_);
        return value_;
    }
​
    void increase() {
        std::unique_lock<std::shared_timed_mutex> lock(mutex_);
        value_ += 1;
    }
};