C_str () thread security in C ++

I created a class, SettingsClass, which contains static strings containing db connection strings that will be used by the MySQL C ++ connector library (for example, hostname, dbname, username, password).

Whenever a function needs to connect to a database, it calls the .c_str () function for these static strings. For instance:

Class SettingsClass { public: static string hostname; ... }SettingsClass; string SettingsClass::hostname; //A function that needs to connect to the DB uses: driver = get_griver_instance(); driver->connect(SettingsClass.hostname.c_str(),...); 

Static lines are filled once in the process of life. Its value is read from the configuration file.

My application is multithreaded. Am I using c_str () in a safe way?

+4
source share
4 answers

C_str () itself must be thread safe. However, if you have another thread that accesses (writes) to the line you take c_str (), then you play with matches sitting in the pool with gasoline.

Typically, c_str () is implemented by adding a null value (the null character is 0x00, not a character for zero, which is 0x30) at the end of the existing line (if it is already gone) and passes back the address where the string is stored.

Anyone can read the libstdC ++ code here: libstdC ++, basic_string.h The interesting lines are 1802, and 294 - 1802 is the c_str () function, and 294 is the function that c_str () calls.

+5
source

Theoretically, at least the standard allows you to implement which would not be thread safe. In practice, I don’t think you are at risk (although formally there may be undefined behavior), but if you want to be sure, just call .c_str() once on all lines during initialization (before the threads were started). The standard guarantees the fairness of the returned pointer until the next non-constant function is called (even if you do not save a copy of it), which means that the implementation cannot modify the data.

+2
source

Since the string type is constant (so suppose it is immutable), it never changes. Any function that only reads it must be thread safe.

So, I think .c_str() is thread safe.

0
source

Until the std::string variables are initialized correctly before your threads are started and changed later, using the const char* representation via c_str() should be thread safe.

0
source

All Articles