Call destructor and then constructor (resetting an object)

后端 未结 10 1431
悲&欢浪女
悲&欢浪女 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:26

    Note that they're not malloc and free that are used, but operator new and operator delete. Also, unlike your code, by using new you're guaranteeing exception safety. The nearly equivalent code would be the following.

    AnObject* anObject = ::operator new(sizeof(AnObject));
    try
    {
        anObject = new (anObject) AnObject();
    }
    catch (...)
    {
        ::operator delete(anObject);
        throw;
    }
    
    anObject->~AnObject();
    ::operator delete(anObject)
    

    The reset you're proposing is valid, but not idiomatic. It's difficult to get right and as such is generally frowned upon and discouraged.

提交回复
热议问题