r值引用返回类型的语义? [英] r-value reference return type semantics?
问题描述
这样的返回类型在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屋!