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:
std::initializer_list<const char*>
vector( std::initializer_list<const char *> init)
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?
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.