Har*_*ake -1 c++ stdvector auto stdtuple c++17
我想返回多个值并使用 声明该函数auto
。
但这效果并不好。无法正确返回值。它被覆盖了。
我尝试执行以下功能f1
〜f3
。这些函数应该返回元组中的向量和字符串。但只是f3
效果很好。
#include <iostream>
#include <vector>
#include <string>
#include <tuple>
auto f1(){
std::vector<double> v(10, 0);
std::string s = "hello";
return std::forward_as_tuple(v, s);
}
auto f2(){
std::vector<double> v(10, 0);
return std::forward_as_tuple(v, "hello");
}
std::tuple<std::vector<double>, std::string> f3(){
std::vector<double> v(10, 0);
std::string s = "hello";
return std::forward_as_tuple(v, s);
}
int main(void){
//change the function
//auto [vec, str] = f1();
//auto [vec, str] = f2();
auto [vec, str] = f2();
for (auto e : vec){
std::cout << "vec : " << e << std::endl;
}
std::cout << "str : " << str << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
您还可以通过此链接在在线编译器 wandbox 上执行该程序。
f1()
导致分段错误。f2()
在 中返回错误值std::vector
。看起来是随机数。f3()
正确返回所有值。为什么会出现这个问题呢?是否不可能返回多个值并使用 声明该函数auto
?
出现此问题的原因是std::forward_as_tuple
返回对局部变量的引用 - 返回类型为tuple<vector<double>&,string&>
。
前两个函数会产生未定义的行为。
第三个方法有效,因为您显式按值返回,但转发不起作用,因为您没有移动左值,因此它们被复制到返回的元组中。
返回元组的正确方法是:
return std::tuple{std::move(vec),std::move(str)};
Run Code Online (Sandbox Code Playgroud)