管理字符串文本的最佳做法

Best practice to manage string literals

本文关键字:最佳 字符串 文本 管理      更新时间:2023-10-16

在一个文件中管理字符串而不是多次写出字符串的最佳实践是什么?我的想法是创建一个简单的 string_library.h 文件,该文件包含映射中的所有字符串,并方便地定义以获取名称和 ID。像这样:

#include <string>
#include <map>
#define SENSOR1_ID 0
#define SENSOR2_ID 1
#define SENSOR1_NAME string_library[SENSOR1_ID]
#define SENSOR2_NAME string_library[SENSOR2_ID]
std::map<unsigned int, const std::string> string_library{
std::make_pair(SENSOR1_ID, "Sensor1 Name"),
std::make_pair(SENSOR2_ID, "Sensor2 HI Name")
};

这样,字符串只需写出一次,并且可以通过定义或从映射中轻松抓取。地图对于能够迭代地图可能很有用,但也许其他一些结构更有意义。

您可以简单地使用constexpr变量:

constexpr auto SENSOR1_NAME = "Sensor1 Name";

不需要宏,也不需要昂贵的动态内存开销。