Two ways to call the default constructor

I have the following code:

struct B
{
 //B() {}
 int x;
 int y;
};

void print(const B &b) 
{
 std::cout<<"x:"<<b.x<<std::endl;
 std::cout<<"y:"<<b.y<<std::endl;
 std::cout<<"--------"<<std::endl;
}

int main()
{
 B b1 = B(); //init1
 B b2; //init2

 print(b1);
 print(b2);

 return 0;
}

When I run the program (vs2008, debug), I have the following output:

x:0
y:0
--------
x:-858993460
y:-858993460
--------

As you can see, the values ​​b1.x and b1.y have a value of 0. Why? What is the difference between init1 and init2?

When I uncomment constructor B, I have the following output:

x:-858993460
y:-858993460
--------
x:-858993460
y:-858993460
--------

Can someone explain the reason for this behavior? Tnx in advance.

+5
source share
5 answers

The default constructor for POD types fills it with zeros. When you explicitly define your own constructor, you do not initialize xand y, and you get random values ​​(in VS debugging, they are filled with exact values, but in the release they will be random).

++ 03 Standard 8.5/5:

<... > T: - T - ( 9) (12.1), T ( , T ),
- T - , , T ;
- T - , ; - .

B() - , - b1.

B b2 , ++ 03 Standard 8.5/9:

, (, cv-) -POD ( ), ; const-type, . , , , , ; - const-specific, .

b2, B b2 = {};.

+10

b1 B.

B b1 = B();

B , , B , , int, .

B , , . x y , .

B b2;

POD- . B, POD, , b2.x b2.y .

, POD, , , , .

+5

.

B b1 = B();

" " - B(). - ( ) . . , , .

B b1;

- ( B).

. . 8.5 "" ++.

+3

O

: -858993460 - 0xCCCCCCCC, VC.

0xCDCDCDCD. , , .

, , , c'tor , ! , ...

+2

I tried on vc6 and Visual Studio 2005, I get below result in both: Could you send the dismantled code generated, As below I published the disassembly code for 2005

x: -858993460

at: -858993460


x: -858993460

at: -858993460


 B b1 = B(); //init1
0043DEDE  lea         ecx,[b1] 
0043DEE1  call        B::B (43ADD9h) 
 B b2; //init2
0043DEE6  lea         ecx,[b2] 
0043DEE9  call        B::B (43ADD9h) 

 print(b1);
0043DEEE  lea         eax,[b1] 
0043DEF1  push        eax  
0043DEF2  call        print (43A302h) 
0043DEF7  add         esp,4 
 print(b2);
0043DEFA  lea         eax,[b2] 
0043DEFD  push        eax  
0043DEFE  call        print (43A302h) 
0043DF03  add         esp,4 
0
source

All Articles