1
class A {
public:
    void foo()
    {
        char *buf = new char[10];
        vec.push_back(buf);
    }

private:
    vector<char *> vec;
};

int main()
{
    A a;
    a.foo();
    a.foo();
}

ではclass Afoo()メモリが割り当てられ、ポインタが に保存されvecます。main()終了すると、解体aされ、解体a.vecされますが、割り当てられたメモリは解放されますか?

4

2 に答える 2

4

メモリは解放されません。解放するには、unique_ptr または shared_ptr に配置する必要があります。

class A {
   public:
     void foo()
     {
        unique_ptr<char[]> buf(new char[10]);
        vec.push_back(buf);
     }
   private:
     vector<unique_ptr<char[]>> vec;
};
于 2012-07-27T04:04:44.550 に答える
2

または、デストラクタを作成できます

 ~A()
{
    for(unsigned int i =0; i < vec.size(); ++i)
         delete [] vec[i];
}

編集

指摘したように、コピーと割り当ても行う必要があります(それらを使用する場合)

class A
{
public:

    A& operator=(const A& other)
    {
        if(&other == this)
             return *this;

        DeepCopyFrom(other);

        return *this;
    }

    A(const A& other)
    {
        DeepCopyFrom(other);
    }


private:
    void DeepCopyFrom(const A& other) 
    {
        for(unsigned int i = 0; i < other.vec.size(); ++i) 
        {
            char* buff = new char[strlen(other.vec[i])];
            memcpy(buff, other.vec[i], strlen(other.vec[i]));
        }
    }

    std::vector<char*> vec;
};

ディープ コピーの詳細と、それが必要な理由についてはこちら

http://www.learncpp.com/cpp-tutorial/912-shallow-vs-deep-copying/

于 2012-07-27T05:41:14.943 に答える