Why doesn’t this code compile? Reassignment of specific type of struct inside lambda causes error C2512: no appropriate default constructor available

Viewed 146

I have a struct with 2 members, it relies on the first member to calculate the value of the second.

struct SomeStruct
{
   int memberA = 0;
   int memberB = memberA + 5;
};

int main()
{
   auto SomeLambda = []()
   {
      SomeStruct x;
      x = SomeStruct{};
   };

   SomeStruct x;
   x = SomeStruct{};
   return 0;
}

I want to reassign that struct to reinitialise it and reuse the variable name. I can do this in a regular function, HOWEVER if I do it inside a lambda I get the following compilation error.

main.cpp(12): error C2512: 'SomeStruct': no appropriate default constructor available
main.cpp(12): note: Invalid aggregate initialization

If I remove the inter dependency between members the code compiles fine.

struct SomeStruct
{
   int memberA = 0;
   int memberB = 5;
};

If I change the assignment inside the lambda to use parenthesis instead of braces that also allows the code to compile.

SomeStruct x;
x = SomeStruct();

However the assignment outside the lambda is still using braces.

Can anyone tell me why this assignment of a specific type of struct inside a lambda fails to compile on MSVC?

0 Answers
Related