We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
正因如此,闭包按值捕获([=])的变量,其生命周期和 Lambda 对象相同。
[=]
当 Lambda 对象被拷贝时,其按值捕获的所有变量也会被重新拷贝一份。
当 Lambda 对象被移动时,其按值捕获的所有变量也会随之一起移动。
struct C { C() { fmt::println("C 默认构造"); } C(C const &) { fmt::println("C 拷贝构造"); } C(C &&) { fmt::println("C 移动构造"); } C &operator=(C const &) { fmt::println("C 拷贝赋值"); } C &operator=(C &&) { fmt::println("C 移动赋值"); } ~C() { fmt::println("C 析构"); } }; C c; fmt::println("构造 lambda"); auto lambda = [c] {}; fmt::println("拷贝 lambda 到 lambda2"); auto lambda2 = lambda; fmt::println("移动 lambda 到 lambda3"); auto lambda3 = lambda;
输出:
C 默认构造 构造 lambda C 拷贝构造 拷贝 lambda 到 lambda2 C 拷贝构造 移动 lambda 到 lambda3 C 移动构造 C 析构 C 析构 C 析构 C 析构
如果按照代码,第7行输出应为"C 拷贝构造"。 按照输出,代码最后一行应为auto lambda3 = std::move(lambda);
auto lambda3 = std::move(lambda);
The text was updated successfully, but these errors were encountered:
No branches or pull requests
闭包捕获变量的生命周期问题
正因如此,闭包按值捕获(
[=]
)的变量,其生命周期和 Lambda 对象相同。当 Lambda 对象被拷贝时,其按值捕获的所有变量也会被重新拷贝一份。
当 Lambda 对象被移动时,其按值捕获的所有变量也会随之一起移动。
输出:
问题
如果按照代码,第7行输出应为"C 拷贝构造"。
按照输出,代码最后一行应为
auto lambda3 = std::move(lambda);
The text was updated successfully, but these errors were encountered: