r值引用返回类型的语义? [英] r-value reference return type semantics?

查看:81
本文介绍了r值引用返回类型的语义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样的返回类型在c ++ 11中表示有意义吗?

  template< typename R> 
R&& grabStuff();

T实例= grabStuff< T>();

我希望 grabStuff 应该扔一个如果 R 没有移动构造函数,则会发生编译时错误,因为这似乎不允许返回类型使用复制构造函数

  T global_thing; 

T&& get(){return std :: move(global_thing); }

结构Foo {Foo(T&); / * ... * /};

int main()
{
global_thing.reset();
Foo a(get());
global_thing.reset();
Foo b(get());
}

返回右值引用的更典型示例是但是,std :: move 本身会返回对您将传递给它的东西的引用(因此,提供有效输入的内容是调用者的责任)。


Does a return type like this represent something meaningful in c++11?

template <typename R>
R&& grabStuff();

T instance = grabStuff<T>();

I would hope that grabStuff should throw a compile-time error if R does not have a move constructor, since this would seem to disallow the return type to use a copy constructor

解决方案

As always, when returning references you must return a reference to something that's still alive after the function returns. How you do that is up to you. Example:

T global_thing;

T && get() { return std::move(global_thing); }

struct Foo { Foo(T &&); /* ... */ };

int main()
{
    global_thing.reset();
    Foo a(get());
    global_thing.reset();
    Foo b(get());
}

The more typical example for returning an rvalue reference is std::move itself, though, which returns a reference to the thing you pass into it (and thus it's the caller's responsibility to provide a valid input).

这篇关于r值引用返回类型的语义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆