placement new to defer to a different constructor

前端 未结 7 898
滥情空心
滥情空心 2021-01-04 12:28

Is this safe? I\'m not using any virtual functions in my actual implementation, but I\'m tempted to believe that even if I was, it would still be safe.

clas         


        
7条回答
  •  伪装坚强ぢ
    2021-01-04 12:56

    The key problem here is that constructors are special - when you write a construct that calls a constructor (for example use new keyword to create an object) not only the constructor body is executed, instead the whole chain of objects is constructed first.

    So when you use placement-new syntax to run another constructor first C++ automagically reruns all the base class object constructors and all the member variables constructors and only then the other constructor body is invoked. Sometimes you'll be okay, but many times you will run into unexpected behavior.

提交回复
热议问题