為什么此代碼段無法編譯?
#include <functional>
#include <iostream>
#include <memory>
int main()
{
std::unique_ptr<int> uniq_ptr(new int{6});
auto foo_a = [&uniq_ptr]{std::cout << *uniq_ptr << std::endl;};
std::bind(foo_a)(); //works
foo_a(); //works
auto foo_b = [up = std::move(uniq_ptr)]()mutable{*up = 5; std::cout << *up << std::endl;};
foo_b(); //works;
#ifdef CHOOSE_1
auto foo_b1 = foo_b; //Surprised! I think `up` could be copied.But the compiler complains: Error: use of deleted function 'main()::<lambda()>::<lambda>(const main()::<lambda()>&)'
#else
std::bind(foo_b); //Same error!
#endif
}
對于auto foo_b = [up = std::move(uniq_ptr)]()mutable{//...},我認為foo_b可以從右值復制up,并且可以通過移動建構式復制。
uj5u.com熱心網友回復:
[up = std::move(uniq_ptr)]只是移動uniq_ptr到 lambda 的成員變數。
std::bind將在內部構造foo_b. 由于foo_b包含unique_ptr不可復制的 a,因此foo_b其本身不可復制。
你應該foo_b搬進std::bind:
std::bind(std::move(foo_b));
或foo_b搬入foo_b1
auto foo_b1 = std::move(foo_b);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/460424.html
