目录
[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 关键字用于明确指示一个成员函数是重写(覆盖)了基类中的虚函数。它主要有两个作用:
- 提高代码可读性:明确告诉其他开发者这个函数是重写基类的虚函数
- 编译时检查:如果该函数并没有实际重写基类中的虚函数(比如函数签名不匹配),编译器会报错
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 限定符等)导致的意外错误,确保确实重写了基类中的虚函数。如果基类中没有对应的虚函数,或者函数签名不匹配,编译器会抛出错误。