C++14新特性的所有知识点全在这儿啦!

2023-10-25 13:10

本文主要是介绍C++14新特性的所有知识点全在这儿啦!,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


前面程序喵介绍过C++11的新特性,这篇文章介绍下C++14的新特性。

「函数返回值类型推导」

C++14对函数返回类型推导规则做了优化,先看一段代码:

#include <iostream>using namespace std;auto func(int i) {return i;
}int main() {cout << func(4) << endl;return 0;
}

使用C++11编译:

~/test$ g++ test.cc -std=c++11
test.cc:5:16: error: ‘func’ function uses ‘auto’ type specifier without trailing return type
auto func(int i) {^
test.cc:5:16: note: deduced return type only available with -std=c++14 or -std=gnu++14

上面的代码使用C++11是不能通过编译的,通过编译器输出的信息也可以看见这个特性需要到C++14才被支持。

返回值类型推导也可以用在模板中:

#include <iostream>
using namespace std;template<typename T> auto func(T t) { return t; }int main() {cout << func(4) << endl;cout << func(3.4) << endl;return 0;
}

注意

函数内如果有多个return语句,它们必须返回相同的类型,否则编译失败

auto func(bool flag) {if (flag) return 1;else return 2.3; // error
}
// inconsistent deduction for auto return type: ‘int’ and then ‘double’

如果return语句返回初始化列表,返回值类型推导也会失败

auto func() {return {1, 2, 3}; // error returning initializer list
}

如果函数是虚函数,不能使用返回值类型推导

struct A {
// error: virtual function cannot have deduced return type
virtual auto func() { return 1; }
}

返回类型推导可以用在前向声明中,但是在使用它们之前,翻译单元中必须能够得到函数定义

auto f();               // declared, not yet defined
auto f() { return 42; } // defined, return type is intint main() {
cout << f() << endl;
}

返回类型推导可以用在递归函数中,但是递归调用必须以至少一个返回语句作为先导,以便编译器推导出返回类型。

auto sum(int i) {if (i == 1)return i;              // return intelsereturn sum(i - 1) + i; // ok
}

lambda参数auto

在C++11中,lambda表达式参数需要使用具体的类型声明:

auto f = [] (int a) { return a; }

在C++14中,对此进行优化,lambda表达式参数可以直接是auto:

auto f = [] (auto a) { return a; };
cout << f(1) << endl;
cout << f(2.3f) << endl;

变量模板

C++14支持变量模板:

template<class T>
constexpr T pi = T(3.1415926535897932385L);int main() {cout << pi<int> << endl; // 3cout << pi<double> << endl; // 3.14159return 0;
}

别名模板

C++14也支持别名模板:

template<typename T, typename U>
struct A {T t;U u;
};template<typename T>
using B = A<T, int>;int main() {B<double> b;b.t = 10;b.u = 20;cout << b.t << endl;cout << b.u << endl;return 0;
}

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 function ‘int main()’:
test.cc:11:7: warning: ‘A’ is deprecated [-Wdeprecated-declarations]A a;^
test.cc:6:23: note: declared herestruct [[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;}
};

为什么是timed的锁呢,因为可以带超时时间,具体可以自行查询相关资料哈,网上有很多。

std::integer_sequence

template<typename T, T... ints>
void print_sequence(std::integer_sequence<T, ints...> int_seq)
{std::cout << "The sequence of size " << int_seq.size() << ": ";((std::cout << ints << ' '), ...);std::cout << '\n';
}int main() {print_sequence(std::integer_sequence<int, 9, 2, 5, 1, 9, 1, 6>{});return 0;
}输出:7 9 2 5 1 9 1 6

std::integer_sequence和std::tuple的配合使用:

template <std::size_t... Is, typename F, typename T>
auto map_filter_tuple(F f, T& t) {return std::make_tuple(f(std::get<Is>(t))...);
}template <std::size_t... Is, typename F, typename T>
auto map_filter_tuple(std::index_sequence<Is...>, F f, T& t) {return std::make_tuple(f(std::get<Is>(t))...);
}template <typename S, typename F, typename T>
auto map_filter_tuple(F&& f, T& t) {return map_filter_tuple(S{}, std::forward<F>(f), t);
}

std::exchange

直接看代码吧:

int main() {std::vector<int> v;std::exchange(v, {1,2,3,4});cout << v.size() << endl;for (int a : v) {cout << a << " ";}return 0;
}

看样子貌似和std::swap作用相同,那它俩有什么区别呢?

可以看下exchange的实现:

template<class T, class U = T>
constexpr T exchange(T& obj, U&& new_value) {T old_value = std::move(obj);obj = std::forward<U>(new_value);return old_value;
}

可以看见new_value的值给了obj,而没有对new_value赋值,这里相信您已经知道了它和swap的区别了吧!

std::quoted

C++14引入std::quoted用于给字符串添加双引号,直接看代码:

int main() {string str = "hello world";cout << str << endl;cout << std::quoted(str) << endl;return 0;
}

编译&输出:

~/test$ g++ test.cc -std=c++14
~/test$ ./a.out
hello world
"hello world"

关于C++14,我们今天先说到这里。

下期预告:

C++17新特性

请持续关注哈!

欢迎大家点亮在看,点赞与转发~

参考链接

https://en.cppreference.com/w/cpp/14

https://en.cppreference.com/w/cpp/language/function#Return_type_deduction_.28since_C.2B.2B14.29

https://en.cppreference.com/w/cpp/language/lambda

https://en.cppreference.com/w/cpp/language/constexpr

https://en.cppreference.com/w/cpp/io/manip/quoted

这篇关于C++14新特性的所有知识点全在这儿啦!的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/282767

相关文章

C++统计函数执行时间的最佳实践

《C++统计函数执行时间的最佳实践》在软件开发过程中,性能分析是优化程序的重要环节,了解函数的执行时间分布对于识别性能瓶颈至关重要,本文将分享一个C++函数执行时间统计工具,希望对大家有所帮助... 目录前言工具特性核心设计1. 数据结构设计2. 单例模式管理器3. RAII自动计时使用方法基本用法高级用法

深入解析C++ 中std::map内存管理

《深入解析C++中std::map内存管理》文章详解C++std::map内存管理,指出clear()仅删除元素可能不释放底层内存,建议用swap()与空map交换以彻底释放,针对指针类型需手动de... 目录1️、基本清空std::map2️、使用 swap 彻底释放内存3️、map 中存储指针类型的对象

C++ STL-string类底层实现过程

《C++STL-string类底层实现过程》本文实现了一个简易的string类,涵盖动态数组存储、深拷贝机制、迭代器支持、容量调整、字符串修改、运算符重载等功能,模拟标准string核心特性,重点强... 目录实现框架一、默认成员函数1.默认构造函数2.构造函数3.拷贝构造函数(重点)4.赋值运算符重载函数

C++ vector越界问题的完整解决方案

《C++vector越界问题的完整解决方案》在C++开发中,std::vector作为最常用的动态数组容器,其便捷性与性能优势使其成为处理可变长度数据的首选,然而,数组越界访问始终是威胁程序稳定性的... 目录引言一、vector越界的底层原理与危害1.1 越界访问的本质原因1.2 越界访问的实际危害二、基

c++日志库log4cplus快速入门小结

《c++日志库log4cplus快速入门小结》文章浏览阅读1.1w次,点赞9次,收藏44次。本文介绍Log4cplus,一种适用于C++的线程安全日志记录API,提供灵活的日志管理和配置控制。文章涵盖... 目录简介日志等级配置文件使用关于初始化使用示例总结参考资料简介log4j 用于Java,log4c

C++归并排序代码实现示例代码

《C++归并排序代码实现示例代码》归并排序将待排序数组分成两个子数组,分别对这两个子数组进行排序,然后将排序好的子数组合并,得到排序后的数组,:本文主要介绍C++归并排序代码实现的相关资料,需要的... 目录1 算法核心思想2 代码实现3 算法时间复杂度1 算法核心思想归并排序是一种高效的排序方式,需要用

C++11范围for初始化列表auto decltype详解

《C++11范围for初始化列表autodecltype详解》C++11引入auto类型推导、decltype类型推断、统一列表初始化、范围for循环及智能指针,提升代码简洁性、类型安全与资源管理效... 目录C++11新特性1. 自动类型推导auto1.1 基本语法2. decltype3. 列表初始化3

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

C++中detach的作用、使用场景及注意事项

《C++中detach的作用、使用场景及注意事项》关于C++中的detach,它主要涉及多线程编程中的线程管理,理解detach的作用、使用场景以及注意事项,对于写出高效、安全的多线程程序至关重要,下... 目录一、什么是join()?它的作用是什么?类比一下:二、join()的作用总结三、join()怎么

Spring Boot3.0新特性全面解析与应用实战

《SpringBoot3.0新特性全面解析与应用实战》SpringBoot3.0作为Spring生态系统的一个重要里程碑,带来了众多令人兴奋的新特性和改进,本文将深入解析SpringBoot3.0的... 目录核心变化概览Java版本要求提升迁移至Jakarta EE重要新特性详解1. Native Ima