我玩std::bind
和右值引用,但我還是不弄清楚它是如何工作的,我有以下代碼:的std :: bind()的:綁定拉姆達與右值引用作爲參數
class Dog {
public:
Dog(const string &name) : name_(name) {
cout << "Dog::ctor" << endl;
}
string GetName() {
return name_;
}
private:
string name_;
};
auto bind_fun = bind([](Dog &&d){ cout << d.GetName() << endl; }, Dog("DogABC"));
bind_fun();
註釋掉bind_fun()
時,或者如果lambda採用Dog&
而不是Dog&&
,則代碼可以正常運行,並具有預期的輸出。當bind_fun()
留註釋掉,以下編譯時錯誤:
test3.cpp:109:3: error: no matching function for call to object of type 'std::__1::__bind<<lambda at test3.cpp:108:17>, Dog>'
f();
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/functional:1749:9: note: candidate template ignored: substitution failure [with _Args = <>]: implicit instantiation of undefined template
'std::__1::__bind_return<<lambda at test3.cpp:108:17>, std::__1::tuple<Dog>, std::__1::tuple<>, false>'
operator()(_Args&& ...__args)
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1/functional:1758:9: note: candidate template ignored: substitution failure [with _Args = <>]: implicit instantiation of undefined template
'std::__1::__bind_return<const <lambda at test3.cpp:108:17>, const std::__1::tuple<Dog>, std::__1::tuple<>, false>'
operator()(_Args&& ...__args) const
^
1 error generated.
我的問題是:
- 爲什麼
bind_fun()
不能稱爲(不會編譯)當拉姆達需要右值的參考? - 使用引用和右值引用作爲lambda的參數在這裏有什麼區別?
'std :: bind'將綁定的參數作爲左值傳遞,因此它與右值引用不匹配。 – 2014-10-11 14:25:22