Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can creating a static const std::string cause an exception?

Tags:

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

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

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 :

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 ?

like image 538
Rahul Iyer Avatar asked Nov 02 '16 10:11

Rahul Iyer


People also ask

What is static const in C++?

“static const” is basically a combination of static(a storage specifier) and const(a type qualifier). The static determines the lifetime and visibility/accessibility of the variable.

How do you make a string constant in C++?

To define a string constant in C++, you have to include the string header library, then create the string constant using this class and the const keyword.

What's the class of a constant string?

Static constant string (class member)

Is const implicitly static?

If you need a field to be a property of a type, and not a property of an instance of that type, use static . A const value is also implicitly static .


Video Answer


1 Answers

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().

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.

like image 97
krzaq Avatar answered Oct 28 '22 02:10

krzaq