Skip to content
New issue

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 - 闭包捕获变量的生命周期问题 存在笔误 #73

Open
Moujuruo opened this issue Dec 25, 2024 · 0 comments
Open

lambda - 闭包捕获变量的生命周期问题 存在笔误 #73

Moujuruo opened this issue Dec 25, 2024 · 0 comments

Comments

@Moujuruo
Copy link

闭包捕获变量的生命周期问题

正因如此,闭包按值捕获([=])的变量,其生命周期和 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);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant