Search code examples
c++vectorc-stringsinitializer-liststring-literals

Initializing a vector of c-strings


Is the following code legal C++? And Why? What risk it may have?

std::vector<const char *> v1 = {"a", "b", "c"};

I am thinking about how this works, regarding the lifetime of the string literals. To my understand:

  1. The compiler makes a temporary array of c-strings.
  2. It assign the temporary array to a std::initializer_list<const char*>
  3. Call the constructor vector( std::initializer_list<const char *> init)
  4. Copy construct v1 from the temporary vector.

Well, my concern is that, shouldn't the lifetime of those string literals already expired after step 3? why?

Whether or not the temporary vector exists doesn't matter. My point is if the constructor is implemented like this:

template <typename T>
vector<T>::vector(initializer_list<T> init)
{
  // shallow copy from init to this
}

Shouldn't those string literals expire, when the lifetime of init end after the constructor return?


Solution

  • Well, I realize this is a silly question, once I know the answer. From cppreference.com:

    String literals have static storage duration, and thus exist in memory for the life of the program.

    That explains everything.