[Issue 21929] delegates capture do not respect scoping
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Tue May 24 16:21:23 UTC 2022
https://issues.dlang.org/show_bug.cgi?id=21929
--- Comment #12 from deadalnix <deadalnix at gmail.com> ---
(In reply to Stanislav Blinov from comment #9)
> (In reply to deadalnix from comment #8)
>
> > You'll not that C++'s std::function will allocate on heap if you capture.
>
> ??? std::function MAY allocate on the heap, and whether it will would depend
> on its implementation and size of lambda's state. A decent implementation of
> std::function surely would not allocate if all you capture is a single
> reference.
>
> > The equivalent code in C++ WILL allocate in a loop too.
>
> Whether std::function would allocate is irrelevant. Equivalent C++ code
> would, generally speaking, print unspecified values for all but the string:
>
> #include <functional>
> #include <vector>
> #include <iostream>
>
> int main(int argc, char** argv) {
> std::vector<std::function<void()>> dgs;
>
> for (int i = 0; i < 10; i++) {
> // Capture by reference, as that's D's semantics
> dgs.emplace_back([&i] () {
> std::cout << i << "\n";
> });
> }
>
> dgs.emplace_back([] () {
> std::cout << "With cached variables" << "\n";
> });
>
> for (int i = 0; i < 10; i++) {
> int index = i;
> // Capture by reference, as that's D's semantics
> dgs.emplace_back([&index] () {
> std::cout << index << "\n";
> });
> }
>
> for (auto& dg: dgs) {
> dg();
> }
>
> return 0;
> }
>
This code is invalid C++, whatever you deduce from it engages only yourself and
does not involve C++ in any way. In fact, this code could format your hard
drive and and would still be within the C++ spec.
--
More information about the Digitalmars-d-bugs
mailing list