MSVS2010 下将左值绑定到右值引用
#include<iostream>
template<class T>
struct Foo
{
T v_;
Foo(T&& v):v_(std::forward<T>(v))
{
std::cout << "building Foo..\n";
}
};
int main()
{
int v;
Foo<int> foo(v);
std::cin.ignore();
}
Visual C++ 2010 输出:
错误 C2664:
'Foo
: 无法将参数 1 从::Foo(T &&)' 'int'
转换为'int &&'
我无法将左值绑定到右值引用,这正常吗?
编辑:
对于函数来说也是如此:
void f(int && v)
{
}
int v;
f(v); //won't compile
我有点困惑,因为我认为 std::forward 对于检测是否使用左值或右值引用调用方法很有用。 但似乎我们无法将任何左值绑定到右值引用中......至少没有模板参数,但我不太理解它
#include<iostream>
template<class T>
struct Foo
{
T v_;
Foo(T&& v):v_(std::forward<T>(v))
{
std::cout << "building Foo..\n";
}
};
int main()
{
int v;
Foo<int> foo(v);
std::cin.ignore();
}
visual c++ 2010 output :
error C2664:
'Foo<T>::Foo(T &&)'
: cannot convert parameter 1 from'int'
to'int &&'
Is it normal that I can't bind a lvalue to a rvalue reference ?
EDIT:
same thing for a function :
void f(int && v)
{
}
int v;
f(v); //won't compile
I'm a little bit confused because I think std::forward is usefull to detect if a method is called with a lvalue or a rvalue reference.
But it seems that we can't bind any lvalue into rvalue reference... at least without template parameter but I don't understand it very well
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
调用移动构造函数需要右值而不是左值是正常的,因为左值可以在移动构造函数运行后命名,并且使用移出值会引发意外行为。
It's normal that calling a move constructor requires an r-value, not an l-value, since an l-value could be named after the move constructor runs, and using a moved-from value would evoke unintended behavior.