Does a c++ struct have a default constructor?

前端 未结 5 1497
野趣味
野趣味 2020-11-28 08:51

I wrote the following code snippet:

void foo()
{
    struct _bar_ 
    {
        int a;
    } bar; 

    cout << \"Value of a is \" << bar.a;
}
<         


        
5条回答
  •  离开以前
    2020-11-28 09:05

    Not an answer, but you might take it to be... if you want to try it:

    void foo() {
       struct test {
          int value;
       } x;
       std::cout << x.value << std::endl;
       x.value = 1000;
    }
    int main() {
       foo();
       foo();
    }
    

    In your example, the memory already had the 0 value before the variable was created, so you can call it a lucky coincidence (in fact, some OS will zero out all memory before starting a process, which means that 0 is quite a likely value to find in a small short program...), the previous code will call the function twice, and the memory from the first call will be reused in the second one, chances are that the second time around it will print 1000. Note however that the value is still undefined, and that this test might or not show the expected result (i.e. there are many things that the compiler can do and would generate a different result...)

提交回复
热议问题