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.
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.
The problem is more general. See C++ FAQ Lite: [10.6] Should my constructors use "initialization lists" or "assignment"?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With