初始化有关Google C 样式指南的静态字符串(C-Type或STD :: String)

Initialize static string (either C-type or std::string) with respect to Google C++ Style Guide

本文关键字:C-Type 字符串 STD String 静态 Google 样式 初始化      更新时间:2023-10-16

根据Google C 样式指南,"静态和全局变量"部分声称:"结果,我们只允许静态变量包含POD数据。此规则完全取消std::vector(使用C阵列(或string(使用const char [](。"假设我的程序需要一些存储在配置文件中的静态字符串,并将在运行时加载。那么如何将字符串加载到const char[]

忽略Google的C 样式指南的优点,您可能会将其存储在const char*变量中,该变量通过动态分配获取指针:

static const char *my_static_string = nullptr;
...
void load_static_string()
{
  if(!my_static_string)
  {
    std::string str = //Read string from file.
    my_static_string = new char[str.size() + 1];
    strncpy(my_static_string, str.data(), str.size() + 1);
  }
}

您必须在编译时指定字符串的长度。您将需要知道字符串在执行之前可以的最大长度。

给定长度:

const std::size_t len = 2048;   // can store 2047 characters with null-terminating ''

您可以在C样式中执行此操作

char buffer[len];

或更高,请使用std::array

#include <array>
std::array<char,len> buffer;

然后将文件打开到ifstream中,并适当地解析数据。

您在配置文件中存储一个字符串的事实 nothing 在如何加载它上可以做。您可以将数据加载到const char[]std::string或其他任何内容,具体取决于您在特定情况下的方便。

规则几乎不允许非POD全局/静态变量...就是这样。