常用c++新特性

171 阅读1分钟

auto和decltype

解决什么问题

主要是为了解决泛型编程中某些类型由模板参数决定难以表示的问题

keywords

  • auto在编译器通过=右边的类型推导出变量的类型
  • decltype在编译器推导表达式的类型
  • auto和decltype会在推导函数返回值的类型问题上配合使用
template<typename T, typename U>
//return_value add(T t, U u) { // t和v类型不确定,无法推导出return_value类型
//    return t + u;
//}

/*返回值后置类型语法*/
auto add(T t, U u) -> decltype(t + u) {
    return t + u;
}

智能指针

解决什么问题

使用RAII(资源获取即初始化)解决由于编码导致的内存问题,比如内存泄漏,double free等

keywords

c++11引入了三种智能指针:

  • std::shared_ptr 多个对象同时指向一块儿内存
  • std::weak_ptr 作为一个旁观者监视shared_ptr中管理的资源是否存在,解决循环引用问题
  • std::unique_ptr 一个对象独占一块儿内存

std::lock相关