std::tie 与 std::make_tuple [英] std::tie vs std::make_tuple
问题描述
此代码编译,但我想知道应该首选哪个版本:
This code compiles but I'm wondering which version should be preferred:
#include <iostream>
#include <tuple>
using namespace std;
tuple<int, int, int> return_tuple1() {
int a = 33;
int b = 22;
int c = 31;
return tie(a, b, c);
}
tuple<int, int, int> return_tuple2() {
int a = 33;
int b = 22;
int c = 31;
return make_tuple(a, b, c);
}
int main() {
auto a = return_tuple1();
auto b = return_tuple2();
return 0;
}
既然函数是按值返回一个元组,那么使用 std::tie
应该没有任何问题吧?(即没有悬空引用)
since the function is returning a tuple by value there shouldn't be any problem in using std::tie
right? (i.e. no dangling references)
推荐答案
使用 std::tie
时要非常小心.返回一个 tie
在逻辑上等同于返回一个引用,以及随之而来的所有警告.
Be very careful with std::tie
. Returning a tie
is logically equivalent to returning a reference, with all of the caveats that come with it.
逻辑上,这三个是等价的:
Logically, these three are equivalent:
int& foo();
std::reference_wrapper<int> foo();
std::tuple<int&> foo();
还有这个:
int a = 10;
return std::tie(a);
相当于:
int a = 10;
return std::ref(a);
因为它产生以下之一:
std::tuple<int&>
在您的示例中,您可以通过返回值的隐式转换来保存.但是,将返回类型替换为 auto
会显示逻辑错误:
In your example you are saved by the return value's implicit conversion. However, replacing the return type with auto
reveals the logic error:
#include <iostream>
#include <tuple>
using namespace std;
auto return_tuple1() { // function name is now lying
int a = 33; // it should be return_chaos()
int b = 22;
int c = 31;
return tie(a, b, c);
}
auto return_tuple2() {
int a = 33;
int b = 22;
int c = 31;
return make_tuple(a, b, c);
}
int main() {
auto a = return_tuple1(); // uh-oh...
auto b = return_tuple2();
std::get<0>(a); // undefined behaviour - if you're lucky you'll get a segfault at some point.
std::get<0>(b); // perfectly ok
return 0;
}
这篇关于std::tie 与 std::make_tuple的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!