Problem with ctor in C++

来源:互联网 发布:淘宝优惠卷无线链接 编辑:程序博客网 时间:2024/05/16 15:16

 

        Sometimes you've got to admit that you're stupid when you did do something really stupid. I wrote some code that makes myself crashed several days ago. I mark it down now and tt can be simplified like the following:

 

 

 

 

        Don't ask me why I'm too silly to write one ctor to initialize three int -_-!!,  this code is just simple enough to illustrate the problem. It seems fine at the first glance but actually it may ruin your whole life especially when code go far more complicated in inheritance hierarchy. If you do not figure it out, let's look at line 5, in fact A(1, 2); doesn't do anything you expected; Unfortunately it's not a function call to initialize the this object instead it calls A::A() to initialize a temporary, local object (not this), then it immediately destructs that temporary when control flows over the ;(semicolon), this means you left a1 and a2 uninitialized. In C++ one constructor cannot call another constructor of the same class,  and one of the solutions to the problem above can be:

 

 

 

原创粉丝点击