如何处理堆内存垃圾?

How to handle the heap memory garbage?

所以我有这段代码,其中创建了一个 PiggyBank 对象。根据选择,有三个 if 语句。由于关键字new分配了堆中的对象我应该如何正确管理内存垃圾,所以当创建不同类型的构造函数时,旧的存钱罐将消失,在下面的代码中:

while(fChoice!=""){
        showFunctions();
        PiggyBank *pb;

        cin>>fChoice;
        cin.ignore(numeric_limits<streamsize>::max(),'\n');

        if(fChoice=="a") {
            pb = new PiggyBank();
        }
        else if (fChoice=="b"){
            cout<<"ENTER NAME:"<<endl;
            string name = "";
            cin>>name;
            pb = new PiggyBank(name);
        }
        else if (fChoice=="c") {
            cout<<"ENTER NAME:"<<endl;
            string name = "";
            cin>>name;
            cout<<"ENTER STARTING BALANCE:"<<endl;
            int startBalance = 0;
            cin>>startBalance;
            pb = new PiggyBank(name,startBalance);
        }
}

首先不要使用动态内存分配。这里没有明显的原因:

while(fChoice!=""){
        showFunctions();
        PiggyBank pb;

        cin>>fChoice;
        cin.ignore(numeric_limits<streamsize>::max(),'\n');

        if(fChoice=="a") {
            pb = PiggyBank();
        }
        else if (fChoice=="b"){
            cout<<"ENTER NAME:"<<endl;
            string name = "";
            cin>>name;
            pb = PiggyBank(name);
        }
        else if (fChoice=="c") {
            cout<<"ENTER NAME:"<<endl;
            string name = "";
            cin>>name;
            cout<<"ENTER STARTING BALANCE:"<<endl;
            int startBalance = 0;
            cin>>startBalance;
            pb = PiggyBank(name,startBalance);
        }
}

(当然这里对PiggyBank的定义有些依赖)


如果你需要动态分配(你最好有一个很好的理由),使用std::unique_ptr这是一个自动处理删除的智能指针当它超出范围或被分配一个新指针时为您服务。

while(fChoice!=""){
        showFunctions();
        std::unique_ptr<PiggyBank> pb;

        cin>>fChoice;
        cin.ignore(numeric_limits<streamsize>::max(),'\n');

        if(fChoice=="a") {
            pb = new PiggyBank();
        }
        else if (fChoice=="b"){
            cout<<"ENTER NAME:"<<endl;
            string name = "";
            cin>>name;
            pb = new PiggyBank(name);
        }
        else if (fChoice=="c") {
            cout<<"ENTER NAME:"<<endl;
            string name = "";
            cin>>name;
            cout<<"ENTER STARTING BALANCE:"<<endl;
            int startBalance = 0;
            cin>>startBalance;
            pb = new PiggyBank(name,startBalance);
        }
}

(需要 #include<memory>