【发布时间】:2014-05-04 12:06:49
【问题描述】:
请考虑此代码。我已经多次看到这种类型的代码。 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;
}
【问题讨论】:
-
返回时被复制。
-
没有人保证......它会死,但在被复制之后。
-
只有在函数返回引用时才会出现问题:
std::vector<std::string>& -
@songyuanyao 不会,会搬家的。
-
@songyuanyao 是的。 C++11 是当前的标准,所以 C++11 就是 C++。
标签: c++ vector stl scope standard-library