为什么创建静态 const std::string 会导致异常? [英] Why can creating a static const std::string cause an exception?

查看:30
本文介绍了为什么创建静态 const std::string 会导致异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have string constants, for strings that I use in multiple places in my app:

namespace Common{
    static const std::string mystring = "IamAwesum";
}

发布有关其他内容的问题时 (编译期间未包含在目标中的 .h 文件会发生什么情况?),另一位用户发表了以下评论:

When posting a question about something else (What happens to a .h file that is not included in a target during compilation?), another user made the following comment :

请注意,在这种情况下,您的静态字符串是全局的.所以他们是可以随时创建异常并且无法被捕获.我劝你使用返回字符串引用的函数.标准::字符串const &mystring { static std::string const mystring = "IamAwesum";以这种方式返回 mystring} 您的对象仅在需要时构造

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

有人能解释一下为什么像我上面那样使用静态常量字符串会引发异常吗?

Can someone explain why using static const strings in the manner that I do so above, risks throwing exceptions ?

推荐答案

N4140 § 3.6.2 [basic.start.init]/4

N4140 § 3.6.2 [basic.start.init]/ 4

是否动态初始化是实现定义的具有静态存储持续时间的非局部变量在main 的第一条语句.

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

N4140 § N4140 15.3 [except.handle]/ 13

在具有静态存储的对象的析构函数中抛出的异常持续时间或在具有静态的命名空间范围对象的构造函数中存储持续时间不会被 main() 上的 function-try-block 捕获.

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.

You simply cannot catch an exception generated by the string's constructor - say, std::bad_alloc.

(意见)话虽如此,对于这么小的字符串,我觉得这种考虑是偏执的.

(opinion) That being said, for such small strings I find this kind of consideration to be paranoid.

这篇关于为什么创建静态 const std::string 会导致异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆