Pio*_*ycz 6 c++ tuples unique-ptr c++11
想象一个期望rvalue引用std :: unique_ptr的函数.
void foo(std::unique_ptr<int>&& a);
Run Code Online (Sandbox Code Playgroud)
在我的真实世界示例中,有多个参数,所以我决定使用std::tuple<T&&>rvalue引用将参数转发给它- 所以std::forward_as_tuple:
void forward_to_foo(std::tuple<std::unique_ptr<int>&&>&& t);
int main() {
forward_to_foo(std::forward_as_tuple(std::make_unique<int>(8)));
}
Run Code Online (Sandbox Code Playgroud)
至于现在一切都好.
当我想"解包"这个元组时出现问题
void forward_to_foo(std::tuple<std::unique_ptr<int>&&>&& t)
{
foo(std::get<0>(t));
}
Run Code Online (Sandbox Code Playgroud)
我在gcc4.9上用c ++ 14得到了这个错误:
error: cannot bind 'std::unique_ptr<int>' lvalue to 'std::unique_ptr<int>&&'
foo(std::get<0>(t));
Run Code Online (Sandbox Code Playgroud)
我的问题:这里有什么问题?为什么std::get<I>(t)rvalue引用的元组返回lvalue?
这里有什么问题?
您需要从左值表达式std::move移动:
foo(std::move(std::get<0>(t)));
Run Code Online (Sandbox Code Playgroud)
为什么
std::get<I>(t)rvalue引用的元组返回lvalue?
因为它返回对元组元素的左值引用.通常,返回左值引用的函数的结果是左值,因为它表示现有对象而不是临时对象.