Call destructor and then constructor (resetting an object)

后端 未结 10 1417
悲&欢浪女
悲&欢浪女 2020-12-05 18:09

I want to reset an object. Can I do it in the following way?

anObject->~AnObject();
anObject = new(anObject) AnObject();
// edit: this is not allowed: anO         


        
10条回答
  •  -上瘾入骨i
    2020-12-05 18:27

    Don't get sucked in by the FQA troll. As usual he gets the facts wrong.

    You can certainly call the destructor directly, for all objects whether they are created with placement new or not. Ugly is in the eye of the beholder, it is indeed rarely needed, but the only hard fact is that both memory allocation and object creation must be balanced.

    "Regular" new/delete simplifies this a bit by tying memory allocation and object creation together, and stack allocation simplifies it even further by doing both for you.

    However, the following is perfectly legal:

    int foo() {
        CBar bar;
        (&bar)->~CBar();
        new (&bar) CBar(42);
     }
    

    Both objects are destroyed, and the stack memory is automatically recycled too. yet unlike the FQA claims, the first call of the destructor is not preceded by placement new.

提交回复
热议问题