Cik
Cik

Reputation: 381

Thread safety of c_str() in C++

I have created a class, SettingsClass that contains static strings that hold db connection strings to be used by the MySQL C++ connector library (for e.g. hostname, dbname, username, password).

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

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

The static strings are populated once in the process lifetime. Its value is read from a configuration file.

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

Upvotes: 5

Views: 2267

Answers (4)

Mats Petersson
Mats Petersson

Reputation: 129504

The c_str() in itself should be threadsafe. However, if you have another thread that accesses (writes to) the string that you are taking c_str() of, then you're playing with matches sitting in a pool of petrol.

Typically c_str() is implemented by adding a zero value (the null character 0x00, not the character for zero which is 0x30) on the end of the existing string (if there isn't one there already) and passes back the address of where the string is stored.

Anyone interested 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.

Upvotes: 7

James Kanze
James Kanze

Reputation: 154007

In theoretically at least, the standard allows implementations which wouldn't be thread safe. In practice, I don't think you'll run any risk (although formally, there could be undefined behavior), but if you want to be sure, just call .c_str() once on all of the strings during initialization (before threads have been started). The standard guarantees the validity of the returned pointer until the next non-const function is called (even if you don't keep a copy of it), which means that the implementation cannot mutate any data.

Upvotes: 2

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

As long the std::string variables are initialized correctly before your threads are started and aren't changed afterwards using the const char* representation via c_str() should be thread safe.

Upvotes: 0

user1284631
user1284631

Reputation: 4616

Since the string type is constant (so, assume, it is immutable), it is never modified. Any function only reading it should be thread-safe.

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

Upvotes: 0

Related Questions