存储用户,错误,异常消息(c ++)

And*_*rew 1 c++ string storage messages

相当简单的问题.我应该在哪里存储错误,异常,用户消息?到目前为止,我总是在函数内部声明本地字符串,它将被调用并且没有打扰.例如

SomeClass::function1(...)
{
std::string str1("message1");
std::string str2("message2");
std::string str3("message3");
...
// some code
...
}
Run Code Online (Sandbox Code Playgroud)

突然间,我意识到每次都会调用构造和初始化,这可能会非常昂贵.将它们作为静态字符串存储在类中甚至是单独的模块中会更好吗?本地化并非如此.

提前致谢.

bdo*_*lan 5

为什么不在需要时使用字符串常量?

SomeClass::function1(...)
{
/* ... */
    throw std::runtime_error("The foo blortched the baz!");
/* ... */
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用static const std::strings.如果您希望将它们复制到许多其他std::string的,并且您的C++实现执行copy-on-write,这是合适的:

SomeClass::function1(...)
{
    static const std::string str_quux("quux"); // initialized once, at program start
    xyz.someMember = str_quux; // might not require an allocation+copy
}
Run Code Online (Sandbox Code Playgroud)

如果您希望制作这些strings的大量副本,并且您没有写入时复制(或者不能依赖它存在),您可能需要考虑使用boost :: flyweight.