C++11特性

目录

[1. 自动类型推导auto](#1. 自动类型推导auto)

[2. std::tie()](#2. std::tie())

[3. override关键字](#3. override关键字)


1. 自动类型推导auto

cpp 复制代码
auto map_builder =
      cartographer::mapping::CreateMapBuilder(node_options.map_builder_options);

std::unique_ptr<MapBuilderInterface> CreateMapBuilder(
    const proto::MapBuilderOptions& options) {
  return absl::make_unique<MapBuilder>(options);
}

使用auto定义的变量/对象必须被初始化,编译器推导出类型。map_builder的类型为std::unique_ptr<MapBuilderInterface>。

2. std::tie()

cpp 复制代码
  std::tuple<NodeOptions, TrajectoryOptions> LoadOptions(
    const std::string& configuration_directory,
    const std::string& configuration_basename);
 
  std::tie(node_options, trajectory_options) =
      LoadOptions(FLAGS_configuration_directory, FLAGS_configuration_basename);

std::tie() 是 C++11 标准引入的新特性。std::tie() 定义在 <tuple> 头文件中,它可以将多个变量 "打包" 成一个 tuple 右值引用,主要用于接收函数返回的 std::tuple 并解包到多个变量中,方便进行多变量赋值操作。

在 C++11 之前,没有 std::tie() 函数,处理多返回值通常需要使用结构体或指针参数,相比之下 std::tie() 提供了更简洁的语法。

3. override关键字

在 C++ 中,override 关键字用于明确指示一个成员函数是重写(覆盖)了基类中的虚函数。它主要有两个作用:

  1. 提高代码可读性:明确告诉其他开发者这个函数是重写基类的虚函数
  2. 编译时检查:如果该函数并没有实际重写基类中的虚函数(比如函数签名不匹配),编译器会报错
cpp 复制代码
class ScopedRosLogSink : public ::google::LogSink {
 public:
  ScopedRosLogSink();
  ~ScopedRosLogSink() override;  // 重写基类的析构函数

  // 重写基类的 send 函数
  void send(::google::LogSeverity severity, const char* filename,
            const char* base_filename, int line, const struct std::tm* tm_time,
            const char* message, size_t message_len) override;

  // 重写基类的 WaitTillSent 函数
  void WaitTillSent() override;

 private:
  bool will_die_;
};

这里的 override 关键字表明:

  • ~ScopedRosLogSink() 析构函数重写了基类 ::google::LogSink 的析构函数
  • send() 方法重写了基类中的同名虚函数
  • WaitTillSent() 方法重写了基类中的同名虚函数

使用 override 可以避免因函数签名细微差异(如参数类型、 const 限定符等)导致的意外错误,确保确实重写了基类中的虚函数。如果基类中没有对应的虚函数,或者函数签名不匹配,编译器会抛出错误。

相关推荐
山登绝顶我为峰 3(^v^)31 天前
C/C++ 交叉编译方法
java·c语言·c++
郝学胜-神的一滴1 天前
中级OpenGL教程 013:渲染器类架构设计与逐帧渲染流程详解
开发语言·c++·unity·游戏引擎·图形渲染·opengl·unreal
小小龙学IT1 天前
C++ 并发编程深度解析:从内存模型到无锁数据结构
数据结构·c++
凯瑟琳.奥古斯特1 天前
力扣1013三等分解法与C++实现
开发语言·c++·算法·leetcode·职场和发展
一拳一个呆瓜1 天前
【STL】iostream 编程:缓冲区的作用
c++·stl
我不是懒洋洋1 天前
从零实现一个分布式任务调度器:XXL-JOB的核心设计
c++
凯瑟琳.奥古斯特1 天前
力扣1012数位DP解法详解
开发语言·c++·算法·leetcode·职场和发展
chh5631 天前
C++--string
java·开发语言·网络·c++·学习
J_yyy1 天前
基于Reactor的文件管理服务开发笔记
c++·笔记·reactor·多线程编程·muduo