Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to allocate memory in the C++ constructor?

Which is the right way to allocate memory via new in the C++ constructor. First way in the argument list:

class Boda {
    int *memory;
    public:
        Boda(int length) : memory(new int [length]) {}
        ~Boda() { delete [] memory; }
};

or in the body of constructor:

class Boda {
    int *memory;
    public:
        Boda(int length) {
            memory = new int [length];
        }
        ~Boda() { delete [] memory; }
};

Thanks, Boda Cydo.

like image 918
bodacydo Avatar asked Aug 12 '10 09:08

bodacydo


2 Answers

I think the simplest way to do this would be to use a boost scoped array and let someone else's well tested library code handle it all for you.

So:

class Boda {
    boost::scoped_array<int> memory;
    public:
        Boda(int length) : memory(new int [length]) {}
       ~Boda() {}
};

Moreover, scoped arrays cannot be copied - so you avoid the nasty copy constructor deallocation issue mentioned in another answer.

like image 130
Alex Wilson Avatar answered Oct 03 '22 02:10

Alex Wilson


The problem is more general. See C++ FAQ Lite: [10.6] Should my constructors use "initialization lists" or "assignment"?

like image 42
adf88 Avatar answered Oct 03 '22 00:10

adf88