请考虑这段代码。我已经多次看到这种类型的代码。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;
}
C++11 之前的版本:
该函数不会返回局部变量,而是返回它的副本。然而,您的编译器可能会在不进行实际复制操作的情况下执行优化。
See 这个问题和答案了解更多详情。
C++11:
该函数将移动该值。看这个答案了解更多详情。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)