Call destructor and then constructor (resetting an object)

后端 未结 10 1445
悲&欢浪女
悲&欢浪女 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条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 18:33

    Yes, what you are doing is valid most of the time. [basic.life]p8 says:

    If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if:

    • the storage for the new object exactly overlays the storage location which the original object occupied, and

    • the new object is of the same type as the original object (ignoring the top-level cv-qualifiers), and

    • the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type, and

    • neither the original object nor the new object is a potentially-overlapping subobject ([intro.object]).

    So it is legal if you don't have a const or reference member.

    If you don't have this guarantee, you need to use std::launder or use the pointer returned by placement new (like you're doing anyways) if you want to use the new object:

    // no const/ref members
    anObject->~AnObject(); // destroy object
    new (anObject) AnObject(); // create new object in same storage, ok
    
    anObject->f(); // ok
    
    // const/ref members
    anObject->~AnObject();
    auto newObject = new (anObject) AnObject();
    
    anObject->f(); // UB
    newObject->f(); // ok
    std::launder(anObject)->f(); // ok
    

提交回复
热议问题