Can I call a constructor from another constructor (do constructor chaining) in C++?

前端 未结 15 2503
暖寄归人
暖寄归人 2020-11-22 01:27

As a C# developer I\'m used to running through constructors:

class Test {
    public Test() {
        DoSomething();         


        
15条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 01:31

    If you want to be evil, you can use the in-place "new" operator:

    class Foo() {
        Foo() { /* default constructor deliciousness */ }
        Foo(Bar myParam) {
          new (this) Foo();
          /* bar your param all night long */
        } 
    };
    

    Seems to work for me.

    edit

    As @ElvedinHamzagic points out, if Foo contained an object which allocated memory, that object might not be freed. This complicates things further.

    A more general example:

    class Foo() {
    private:
      std::vector Stuff;
    public:
        Foo()
          : Stuff(42)
        {
          /* default constructor deliciousness */
        }
    
        Foo(Bar myParam)
        {
          this->~Foo();
          new (this) Foo();
          /* bar your param all night long */
        } 
    };
    

    Looks a bit less elegant, for sure. @JohnIdol's solution is much better.

提交回复
热议问题