简体   繁体   English

初始化C字符串向量

[英]Initializing a vector of c-strings

Is the following code legal C++? 以下代码是否合法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. 编译器制作一个临时的c字符串数组。
  2. It assign the temporary array to a std::initializer_list<const char*> 它将临时数组分配给std::initializer_list<const char*>
  3. Call the constructor vector( std::initializer_list<const char *> init) 调用构造函数vector( std::initializer_list<const char *> init)
  4. Copy construct v1 from the temporary vector. 从临时向量复制构造v1

Well, my concern is that, shouldn't the lifetime of those string literals already expired after step 3? 好吧,我担心的是,这些字符串文字的生存期是否应该在第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? 当构造函数返回后init的生存期结束时,这些字符串文字不应该过期吗?

Well, I realize this is a silly question, once I know the answer. 好吧,一旦知道答案,我就知道这是一个愚蠢的问题。 From cppreference.com : 来自cppreference.com

String literals have static storage duration, and thus exist in memory for the life of the program. 字符串文字具有静态的存储持续时间,因此在程序的生命周期内存在内存中。

That explains everything. 这说明了一切。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM