我有字符串常量,用于在我的应用程序的多个地方使用的字符串:
namespace Common{
static const std::string mystring = "IamAwesum";
}
在发布有关其他内容的问题 ( What happens to a .h file that is not included in a target during compilation? ) 时,另一位用户发表了以下评论:
be aware that your static string are global in this case. So they are could create an exception at anytime and can't be catch. I advise you to use function who return a reference of your string. std::string const &mystring { static std::string const mystring = "IamAwesum"; return mystring} by this way your object is only construct when needed
有人可以解释为什么以我上面的方式使用静态常量字符串会引发抛出异常的风险吗?
最佳答案
N4140 § 3.6.2 [basic.start.init]/ 4
It is implementation-defined whether the dynamic initialization of a non-local variable with static storage duration is done before the first statement of
main
.
N4140 § N4140 15.3 [except.handle]/ 13
Exceptions thrown in destructors of objects with static storage duration or in constructors of namespace-scope objects with static storage duration are not caught by a function-try-block on
main()
.
您根本无法捕获由字符串的构造函数生成的异常 - 例如,
std::bad_alloc
.(意见)话虽如此,对于这么小的字符串,我觉得这种考虑是偏执的。
关于c++ - 为什么创建静态 const std::string 会导致异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68975903/