是否可以在类的函数内使用析构函数来重置值?

Kin*_*g23 3 c++ pointers destructor

在我的讲座中,我没有看到有人使用析构函数将值重置为启动参数,而是在函数中手动执行每个变量.在类函数中使用析构函数进行重置/删除会导致任何问题

我的意思的一个小例子:

    class Test1{
        private:
            int *test;
            bool valid;
        public:
        Test1(int value,bool valid=false){
            test=new int(value); this->valid=valid;
        }
        ~Test1(){
            delete test; test=nullptr; valid=false;
        }

    void ResetStats(int NewValue){
        this->~Test1();
        test1=new int(NewValue);
        valid=false;
    }

    }
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

调用一个非平凡的析构函数会明确地结束对象的生命周期(为什么?).

ResetStats通过将它放在一个单独的私有函数中来共享和析构函数之间的功能:

// Both destructor and ResetStats call Reset
~Test1(){
    Reset(nullptr);
}
void ResetStats(int NewValue) {
    Reset(new int(NewValue));
}
// Shared functionality goes here
private Reset(int *ptr) {
    delete test;
    test=ptr;
    valid=false;
}
Run Code Online (Sandbox Code Playgroud)