【发布时间】:2016-11-02 10:24:17
【问题描述】:
我有字符串常量,用于在我的应用程序的多个位置使用的字符串:
namespace Common{
static const std::string mystring = "IamAwesum";
}
在发布有关其他问题的问题 (What happens to a .h file that is not included in a target during compilation?) 时,另一位用户发表了以下评论:
请注意,在这种情况下,您的静态字符串是全局的。所以他们是 可以随时创建异常并且无法捕获。我劝你 使用返回字符串引用的函数。标准::字符串 const &mystring { 静态 std::string const mystring = "IamAwesum"; return mystring} 通过这种方式,您的对象仅在需要时才构造
有人能解释一下为什么以我上面的方式使用静态 const 字符串会引发异常吗?
【问题讨论】:
-
在制作嵌入式应用程序的过程中,我遇到过类似的事情。动态内存分配可能还不起作用。
标签: c++ static constant-expression