[英]C++ lifetime of objects built into collections
I have the following code 我有以下代码
void my_func() {
std::vector<std::string> all_strings;
for (int i = 0 ; i < 10 ; i++) {
// "loop a"
all_strings.push_back(std::to_string(i));
}
for (const std::string& str : all_strings) {
// "loop b"
std::cout << str << std::endl;
}
}
I created the strings and assigned them into the vector within "loop a". 我创建了字符串,并将其分配给“ loop a”中的向量。 The question is, whether I can access those vector values in "loop b", where the objects created locally and internally in "loop a" are already gone.
问题是,是否可以在“循环b”中访问那些矢量值,而在“循环a”中在本地和内部创建的对象已经消失了。
In other words, are the strings copied by values into the vector in "loop a"? 换句话说,是否将值复制的字符串复制到“循环a”的向量中?
Due to the definition of your variable, you are storing std::string
objects by value 根据变量的定义,您
std::string
值存储std::string
对象
std::vector<std::string> all_strings;
This means the vector
owns copies of the strings, that it will destroy when it falls out of scope. 这意味着
vector
拥有字符串的副本,如果超出范围,它将被销毁。
是的, push_back
将复制std::string
并将其存储在vector
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.