c++ - 为什么创建静态 const std::string 会导致异常?

标签 c++ static constant-expression

我有字符串常量,用于在我的应用程序的多个地方使用的字符串:

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/

相关文章:

c++ - 静态变量链接错误,C++

c++ - 如何构造对象 vector (具有静态成员)

php - PHP 中的 self::vs className::inside static className 方法

c++ - C++ 中的静态常量双重初始化

c++ - C++11 标准中的核心常量表达式是什么?

C++ Opencv - 对 mat 的任何更改,也更改用于初始化 mat 的 vector

c++ - 在公共(public)层次结构中的类之间共享析构函数

java - C++ 中的等效标识符

c++ - `constexpr`、 `static_assert` 和 `if constexpr(...)` 变量之间的模板中 `constexpr` lambda 的评估不一致

c++ - 如何将 XMFLOAT3 转换为 const float *pData?