gpt4 book ai didi

c++ - 为什么可以从函数返回 'vector'?

转载 作者:IT老高 更新时间:2023-10-28 11:53:29 24 4
gpt4 key购买 nike

请考虑此代码。我已经多次看到这种类型的代码。 words 是一个局部 vector 。如何从函数中返回它?

我们能保证它不会死吗?

 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 前:

该函数不会返回局部变量,而是返回它的拷贝。但是,您的编译器可能会在没有进行实际复制操作的情况下执行优化。

this question & answer了解更多详情。

C++11:

函数将移动值。见 this answer了解更多详情。

关于c++ - 为什么可以从函数返回 'vector'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22655059/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com