Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing objects in STL vector - minimal set of methods

What is "minimal framework" (necessary methods) of complex object (with explicitly malloced internal data), which I want to store in STL container, e.g. <vector>?

For my assumptions (example of complex object Doit):

#include <vector>
#include <cstring>
using namespace std;
class Doit {
    private:
        char *a;
    public:
        Doit(){a=(char*)malloc(10);}
        ~Doit(){free(a);}
};

int main(){
    vector<Doit> v(10);
}

gives

*** glibc detected *** ./a.out: double free or corruption (fasttop): 0x0804b008 ***
Aborted

and in valgrind:

malloc/free: 2 allocs, 12 frees, 50 bytes allocated.

UPDATE:

Minimal methods for such object are: (based on sbi answer)

class DoIt{
    private:
        char *a;
    public:
        DoIt() { a=new char[10]; }
        ~DoIt() { delete[] a; }
        DoIt(const DoIt& rhs) { a=new char[10]; std::copy(rhs.a,rhs.a+10,a); }
        DoIt& operator=(const DoIt& rhs) { DoIt tmp(rhs); swap(tmp); return *this;}
        void swap(DoIt& rhs) { std::swap(a,rhs.a); }
};

Thanks, sbi, https://stackoverflow.com/users/140719/sbi

like image 725
osgx Avatar asked Mar 23 '10 15:03

osgx


1 Answers

Note that Charles has answered your question perfectly.

Anyway, as per the Rule of Three, your class, having a destructor, should have a copy constructor and an assignment operator, too.

Here's how I would do it:

class Doit {
    private:
        char *a;
    public:
        Doit()                   : a(new char[10]) {}
        ~Doit()                    {delete[] a;}
        DoIt(const DoIt& rhs)    : a(new char[10]) {std::copy(rhs.a,rhs.a+10,a);}
        void swap(DoIt& rhs)       {std::swap(a,rhs.a);}
        DoIt& operator=(DoIt rhs)  {swap(rhs); return *this;}
};
like image 136
sbi Avatar answered Sep 20 '22 10:09

sbi