请考虑此代码。我已经看过几次这种类型的代码。words
是局部向量。如何从函数返回它?
我们可以保证它不会死吗?
std::vector<std::string> read_file(const std::string& path)
{
std::ifstream file("E:\\names.txt");
if (!file.is_open())
{
std::cerr << "Unable to open file" << "\n";
std::exit(-1);
}
std::vector<string> words;//this vector will be returned
std::string token;
while (std::getline(file, token, ','))
{
words.push_back(token);
}
return words;
}
我们可以保证它不会死吗?
只要没有引用返回,这样做就很好了。words
将被移至接收结果的变量。
局部变量将超出范围。移动(或复制)之后。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句