c++1x

C兼容性

C++ 不是 C 的一个超集

// foo.h
#ifdef __cplusplus
extern "C" {
#endif

int add(int x, int y);

#ifdef __cplusplus
}
#endif

// foo.c
int add(int x, int y) {
    return x+y;
}

// main.cpp
#include "foo.h"
int main() {
    add(1, 2);
    return 0;
}
gcc -c foo.c
g++ main.cpp foo.o -o main

语言的可用性强化

  • C++11 引入了 nullptr 关键字,专门用来区分空指针、0。传统 C++ 会把 NULL、0 视为同一种东西。
  • 类型推导
for (auto itr = vec.cbegin(); itr != vec.cend(); ++itr);
template<typename T, typename U>
auto add(T x, U y) {
   return x+y;
}
//auto 不能用于函数传参,因此下面的做法是无法通过编译的(考虑重载的问题,我们应该使用模板
int add(auto x, auto y); // error
// decltype 关键字是为了解决 auto 关键字只能对变量进行类型推导的缺陷而出现的。它的用法和 sizeof 很相似:
decltype(表达式)
auto x = 1;
auto y = 2;
decltype(x+y) z;
  • 区间迭代
// int array[] = {1,2,3,4,5};
std::vector<int> array(5, 100);
// & 启用了引用, 如果没有则对 arr 中的元素只能读取不能修改
for(auto &x : array) {
    std::cout << x << std::endl;
}
  • 模版增强
// typedef 定义别名的语法是:typedef 原名称 新名称;
// 定义了一个返回类型为 int,参数为 void* 的函数指针类型,名字叫做 process
typedef int (*process)(void *);  
using process = int(*)(void *); // 同上, 更加直观
// 模板参数中能使用 ... 表示不定长模板参数
// 可以使用 sizeof... 来计算参数的个数,
template<typename... Args>
void magic(Args... args) {
    std::cout << sizeof...(args) << std::endl;
}
// 递归模板函数
#include <iostream>
template<typename T>
void printf(T value) {
    std::cout << value << std::endl;
}
template<typename T, typename... Args>
void printf(T value, Args... args) {
    std::cout << value << std::endl;
    printf(args...);
}
int main() {
    printf(1, 2, "123", 1.1);
    return 0;
}
// 初始化列表展开, 编译这个代码需要开启 -std=c++14
template<typename T, typename... Args>
auto print(T value, Args... args) {
    std::cout << value << std::endl;
    return std::initializer_list<T>{([&] {
        std::cout << args << std::endl;
    }(), value)...};
}
int main() {
    print(1, 2.1, "123");
    return 0;
}

语言运行期的强化

  • lambda
[捕获列表](参数列表) mutable(可选) 异常属性 -> 返回类型 {
    // 函数体
}
// 1.值捕获
void learn_lambda_func_1() {
    int value_1 = 1;
    auto copy_value_1 = [value_1] {
        return value_1;
    };
    value_1 = 100;
    auto stored_value_1 = copy_value_1();
    // 这时, stored_value_1 == 1, 而 value_1 == 100.
    // 因为 copy_value_1 在创建时就保存了一份 value_1 的拷贝
    cout << "value_1 = " << value_1 << endl;
    cout << "stored_value_1 = " << stored_value_1 << endl;
}
// 2.引用捕获
...
	auto copy_value_2 = [&value_2] { ...
// stored_value_2 == 100, value_1 == 100.
// 3.隐式捕获
* [] 空捕获列表
* [name1, name2, ...] 捕获一系列变量
* [&] 引用捕获, 让编译器自行推导捕获列表
* [=] 值捕获, 让编译器执行推导应用列表
// 4.表达式捕获(C++14), 右值
#include <utility>
void learn_lambda_func_3(){
    auto important = std::make_unique<int>(1);
    auto add = [v1 = 1, v2 = std::move(important)](int x, int y) -> int {
        return x+y+v1+(*v2);
    };
    std::cout << "add(3, 4) = " << add(3, 4) << std::endl; // 9
}
// 在上面的代码中,important 是一个独占指针,是不能够被捕获到的,这时候我们需要将其转移为右值,在表达式中初始化。
// std::move 并不会真正地移动对象,真正的移动操作是在移动构造函数、移动赋值函数等完成的,std::move 只是将参数转换为右值引用而已(相当于一个static_cast)
// 泛型 Lambda (C++14)
void learn_lambda_func_4(){
    auto generic = [](auto x, auto y) {
        return x+y;
    };
    std::cout << "generic(1,2) = " << generic(1, 2) << std::endl;
    std::cout << "generic(1.1,2.2) = " << generic(1.1, 2.2) << std::endl;
}
  • 函数对象包装器
// 函数的容器之后便能够更加方便的将函数、函数指针作为对象进行处理
#include <functional>
#include <iostream>

int foo(int para) {
    return para;
}

int main() {
    // std::function 包装了一个返回值为 int, 参数为 int 的函数
    std::function<int(int)> func = foo;

    int important = 10;
    std::function<int(int)> func2 = [&](int value) -> int {
        return 1+value+important;
    };
    std::cout << func(10) << std::endl;
    std::cout << func2(10) << std::endl;
}
// bind()
int foo(int a, int b, int c) {
    ;
}
int main() {
    // 将参数1,2绑定到函数 foo 上,但是使用 std::placeholders::_1 来对第一个参数进行占位
    auto bindFoo = std::bind(foo, std::placeholders::_1, 1,2);
    // 这时调用 bindFoo 时,只需要提供第一个参数即可
    bindFoo(1);
}

新增容器

  • std::array

std::array 保存在栈内存中,std::vector保存在堆内存中。可以使用std:sort()。

void foo(int *p, int len) {
    return;
}

std::array<int 4> arr = {1,2,3,4};

// C 风格接口传参
// foo(arr, arr.size());           // 非法, 无法隐式转换
foo(&arr[0], arr.size());
foo(arr.data(), arr.size());

// 使用 `std::sort`
std::sort(arr.begin(), arr.end());
  • std::forward_list

单向链表,相比list,效率高,提供了 O(1) 复杂度的元素插入。

  • std::unordered_set和std::unordered_map

内部通过 Hash 表实现

  • std::tuple
    • std::make_tuple: 构造元组
    • std::get: 获得元组某个位置的值
    • std::tie: 元组拆包
#include <tuple>
#include <iostream>

auto get_student(int id)
{
    // 返回类型被推断为 std::tuple<double, char, std::string>

    if (id == 0)
        return std::make_tuple(3.8, 'A', "张三");
    if (id == 1)
        return std::make_tuple(2.9, 'C', "李四");
    if (id == 2)
        return std::make_tuple(1.7, 'D', "王五");
    return std::make_tuple(0.0, 'D', "null");   
    // 如果只写 0 会出现推断错误, 编译失败
}

int main()
{
    auto student = get_student(0);
    std::cout << "ID: 0, "
    << "GPA: " << std::get<0>(student) << ", "
    << "成绩: " << std::get<1>(student) << ", "
    << "姓名: " << std::get<2>(student) << '\n';

    double gpa;
    char grade;
    std::string name;

    // 元组进行拆包
    std::tie(gpa, grade, name) = get_student(1);
    std::cout << "ID: 1, "
    << "GPA: " << gpa << ", "
    << "成绩: " << grade << ", "
    << "姓名: " << name << '\n';
}
  • std::regex
#include <iostream>
#include <string>
#include <regex>

int main() {
    std::string fnames[] = {"foo.txt", "bar.txt", "test", "a0.txt", "AAA.txt"};
    // 在 C++ 中 `\` 会被作为字符串内的转义符,为使 `\.` 作为正则表达式传递进去生效,需要对 `\` 进行二次转义,从而有 `\\.`
    std::regex txt_regex("[a-z]+\\.txt");
    for (const auto &fname: fnames)
        std::cout << fname << ": " << std::regex_match(fname, txt_regex) << std::endl;
}
/*
foo.txt: 1
bar.txt: 1
test: 0
a0.txt: 0
AAA.txt: 0
*/

智能指针

#include <memory>

  • std::shared_ptr

std::shared_ptr 是一种智能指针,它能够记录多少个 shared_ptr 共同指向一个对象,从而消除显示的调用 delete,当引用计数变为零的时候就会将对象自动删除。

auto pointer = std::make_shared<int>(10);
auto pointer2 = pointer;    // 引用计数+1
auto pointer3 = pointer;    // 引用计数+1
int *p = pointer.get();             // get() 方法来获取原始指针,这样不会增加引用计数
// get_count()来查看一个对象的引用计数
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;      // 3
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;    // 3
std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl;    // 3
// reset() 来减少一个引用计数
pointer2.reset();
std::cout << "reset pointer2:" << std::endl;
std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl;      // 2
std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl;    // 0, pointer2 已 reset
  • std::unique_ptr

std::unique_ptr 是一种独占的智能指针,它禁止其他智能指针与其共享同一个对象,从而保证了代码的安全:

std::unique_ptr<int> pointer = std::make_unique<int>(10);   // make_unique 从 C++14 引入
std::unique_ptr<int> pointer2 = pointer;    // 非法
  • std::weak_ptr

解决std::shared_ptr 依然存在着资源无法释放的问题。

运行结果是 A, B 都不会被销毁,这是因为 a,b 内部的 pointer 同时又引用了 a,b,这使得 a,b 的引用计数均变为了 2,而离开作用域时,a,b 智能指针被析构,却智能造成这块区域的引用计数减一,这样就导致了 a,b 对象指向的内存区域引用计数不为零,而外部已经没有办法找到这块区域了,也就造成了内存泄露,

#include <iostream>
#include <memory>

class A;
class B;

class A {
public:
    // A 或 B 中至少有一个使用 weak_ptr,弱引用不会引起引用计数增加
    // std::weak_ptr<B> pointer; // 正确
    std::shared_ptr<B> pointer; // 错误
    ~A() {
        std::cout << "A 被销毁" << std::endl;
    }
};
class B {
public:
    std::shared_ptr<A> pointer;
    ~B() {
        std::cout << "B 被销毁" << std::endl;
    }
};
int main() {
    std::shared_ptr<A> a = std::make_shared<A>();
    std::shared_ptr<B> b = std::make_shared<B>();
    a->pointer = b;
    b->pointer = a;

    return 0;
}

线程

g++ main.cpp -std=c++14 -pthread

  • std::thread

std::thread 用于创建一个执行的线程实例

#include <iostream>
#include <thread>
void foo() {
    // get_id()来获取所创建线程的线程 ID
    std::cout << "hello " << std::this_thread::get_id() << std::endl;
}
int main() {
    std::thread t(foo);
    t.join(); // join() 来加入一个线程
    return 0;
}
  • std::mutex/std::unique_lock
#include <iostream>
#include <thread>
#include <mutex>

// RAII
void some_operation(const std::string &message) {
    static std::mutex mutex;
    std::lock_guard<std::mutex> lock(mutex);

    // ...操作

    // 当离开这个作用域的时候,互斥锁会被析构,同时unlock互斥锁
    // 因此这个函数内部的可以认为是临界区
}
// std::unique_lock 更加灵活,std::unique_lock 的对象会以独占所有权(没有其他的 unique_lock 对象同时拥有某个 mutex 对象的所有权)的方式管理 mutex 对象上的上锁和解锁的操作。

std::mutex mtx;
void block_area() {
    std::unique_lock<std::mutex> lock(mtx);
    //...临界区
}

  • std::future/std::packaged_task 参考

std::future 则是提供了一个访问异步操作结果的途径,
std::packaged_task 可以用来封装任何可以调用的目标,从而用于实现异步的调用。

  • std::condition_variable

std::condition_variable 是为了解决死锁而生的

参考

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值