placement new to defer to a different constructor

前端 未结 7 897
滥情空心
滥情空心 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:50

    You wouldn't be safe if you extended another class and that class had a destructor, for example

    class Foo
    {
        int* a;
    public:
        Foo():a(new int)
        {
    
        }
        ~Foo(){delete a;}
    }
    
    class Bar:public Foo
    {
        Bar()
        {
            // initialize things
        }
    
        Bar( int )
        {
             new ( this ) Foo();
        }
    }
    

    First Bar(int) calls Foo(), then it calls Bar() which also calls Foo(). The second time Foo() is called, it overwrites the pointer set up by the first call to Foo(), and the allocated memory is leaked.

提交回复
热议问题