Share via

Lambda capture is deleted too many times

M3 116 Reputation points
2021-10-30T23:44:18.197+00:00

In the following code I get the unexpected output:
s(1)
~s(1)
~s(0)
~s(-1)

I'm using VS 2022 preview 7.0 with /std:c++latest and /experimental:module
I was expecting the constructor and destructor to be called the same number of times.
I get expected output with gcc (godbolt).

#include <iostream>

using namespace std;
struct S {
  S() {
    ++count;
    cout << "\ns(" << count << ")";
  }
  ~S() {
    cout << "\n~s(" << count << ")";
    --count;
  }
  static int count;
};
int S::count = 0;
auto my_test(S const s) {
  return [s](int i) { return true; };
}

int main(int, char **) { auto f = my_test(S()); }
Developer technologies | C++
Developer technologies | C++

A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.

0 comments No comments

Answer accepted by question author

RLWA32 52,571 Reputation points
2021-10-31T00:26:08.803+00:00

And what do you see if you provide a copy constructor that increments the count variable?

Was this answer helpful?

1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.