首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用循环的delete[]样式得到向量元素的C11误差

用循环的delete[]样式得到向量元素的C11误差
EN

Stack Overflow用户
提问于 2015-11-09 20:32:24
回答 1查看 51关注 0票数 0
代码语言:javascript
复制
#include <iostream>
#include <vector>
using namespace std;

// Shows Factor Design Pattern
class Stooge{
    public:
        static Stooge* makeStooge(int choice); // static class function
        virtual void slapStick() = 0; // implemented by derived
        virtual ~Stooge(){}
};

class Larry : public Stooge{
    public:
        void slapStick(){
           cout << "Larry: poke eyes" << endl; 
        }

        ~Larry(){}
};

class Moe : public Stooge{
    public:
        void slapStick(){
           cout << "Moe: slap head" << endl; 
        }
        ~Moe(){}
};

class Curly : public Stooge{
    public:
        void slapStick(){
           cout << "Curly: suffer abuse" << endl; 
        }
        ~Curly(){}
};

Stooge* Stooge::makeStooge(int choice){
    switch(choice){
        case 1: return new Larry;
                break;
        case 2: return new Moe;
                break;
        case 3: return new Curly;
                break;
        default:{
                    cout << "Enter valid choice next time!!";
                    return NULL;
                }
    }
}

int main(){

    vector<Stooge*> roles;
    int choice;

    while(true){
        cout << "Larry(1) Moe(2) Curly(3) Exit(0)" << endl;
        cin >> choice;

        if(choice==0)
            break;

        Stooge *s = Stooge::makeStooge(choice);

        if(s)
            roles.push_back(s);
    }

    for(auto r : roles)
        r->slapStick();

    // this will fail
    for(auto x : roles)
        delete[] x;

    // this works 
    #if 0
    for(int i=0; i<roles.size(); i++)
        delete roles[i];
    #endif

    return 0;
}

当我运行上面的片段时,我会看到一个带有以下错误消息的崩溃:

a.out(48873,0x7fff75912000) malloc:*对象0x7fab72500058:指针未分配

delete[]的调用堆栈中,我看到了一个有效的(malloc‘’ed)地址,用于'x‘,但我无法理解为什么实际空闲的情况与正则for循环(没有C11特性的情况下可以正常工作)存在问题。这意味着我不完全理解如何使用自动循环功能-谁能解释一下吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-09 20:37:00

xroles中的单个元素。因为它是用new分配的,所以应该用delete (就像第二个块那样)释放它,而不是用delete[]

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33617724

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档