0xbadf00d
0xbadf00d

Reputation: 18178

Storing constant string literals in a container

I've got a struct foo bar of the form struct foo { const char* s, ... }; and a std::vector<foo> v; and I want to push_back a few foo's with constant values for the s member field, i.e.

bar.push_back({ "1", /*...*/ });
bar.push_back({ "2", /*...*/ });
bar.push_back({ "3", /*...*/ });
//...

Now, if I'm not totally wrong, this isn't safe, since the life time of the string literals are bounded to the scope of the initializer braces. So, the life time of the string literal "1" should have already been ended at the line of the second push_back.

How can we deal with this? Do we really need to create a second container strong std::string's and passing the corresponding c_str() pointers to bar?

Upvotes: 2

Views: 255

Answers (2)

rep_movsd
rep_movsd

Reputation: 6895

The way to think of string literals is as if they were const pointers to const chars. In fact if you initialize two variables with the same string literal, they will actually point to the same address in most compiler implementations.

You can verify this by printing out the const char* pointers after casting them to integer.

Hence there is no question of "lifetime" of string literals anymore than the constant 99 has a lifetime.

They are literally literals

Upvotes: 1

lubgr
lubgr

Reputation: 38287

This is safe as long as you only ever initialize the const char *s with string literals . They have a lifetime that is identical to the lifetime of your program.

Upvotes: 5

Related Questions