首页 > 解决方案 > C++ 命名空间中的字符串声明

问题描述

我想在我的命名空间中添加一些字符串常量,如下所示:

namespace myNamespace
{
    //Some string constants.
    const string str1 = "str1";
    const string str2 = "str2";
    ...
}

所有这些常量都是最多 20 个字符的字符串。Clang-Tidy 给了我以下警告:Initialization of str1 with static storage duration may throw an exception that cannot be caught,以及我所有的字符串常量的相同警告。据我了解,此代码可以在 main() 之前执行,如果内存不足,可能会导致初始化 thses 字符串出现问题。

所以,我的问题是我应该如何在我的代码中声明字符串常量?我应该创建一个只有这些字符串作为成员的类吗?或者也许有更好的解决方案?

标签: c++stringmemory-managementnamespaces

解决方案


推荐阅读