Calling a constructor to re-initialize object

前端 未结 12 1794
执笔经年
执笔经年 2020-12-04 15:01

is it possible to re-initialize an object of a class using its constructor?

12条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 16:03

    In C++11, you can do this:

    #include 
    
    template 
    void Reconstruct(T& x, Args&&... args)
    {
        static_assert(!std::has_virtual_destructor::value, "Unsafe"); 
        x.~T();
        new (&x) T(std::forward(args)...);
    }
    

    This allows you to use Reconstruct passing arbitrary constructor parameters to any object. This can avoid having to maintain a bunch of Clear methods, and bugs that can easily go unnoticed if at some point the object changes, and the Clear method no longer matches the constructor.

    The above will work fine in most contexts, but fail horribly if the reference is to a base within a derived object that has a virtual destructor. For this reason, the above implementation prevents use with objects that have a virtual destructor.

提交回复
热议问题