C++0x delegating constructors
Michael_Wong 120000M1EH Comments (9) Visits (6680)
In fact, it causes a serious problem when people who learn these other language come to C++, and try using it because what looks reasonable, will compile and run, but does not do what they think it does.
And it is more common then you think, because in many cases constructors may differ by the parameter list with common bodies. If the constructor can use default arguments, you could common the bodies. If it can't then you are out of luck today:
So having successfully refactored once, you might decide to try it in another case, turning this code into:
this because this is similar to Java delegating constructors:
This should work. Or should it ?
Well of course it doesn't, and the Mystery#1 of the Week is can someone tell me why not?
So may be we want to try something even more ambitious:
This looks even more promising and in fact it does everything I want it to do. Seems clever as I am using a placement new on the same object. In reality, it is an even worst solution then before. Mystery#2 of the Week is why is this worst?
In fact C++03 had no better solution which is either more cumbersome, or error prone.
C++0x will fix this for the sake of improved teachability and library building. The solution is to simply allow the call to the target constructor in the initializer list of the delegating constructor. We call the caller the delegating constructor and the callee is the target constructor
The final accepted paper is in: