Re: Question about destructors
On Feb 7, 6:13 pm, Gus Gassmann wrote:
Some of the code is not written by me, so I am afraid Fred`s solution
does not work. Let me then summarize, just to be absolutely clear:
4. Object **obj = new Object[n];
for (int i=0; i<n; i++) obj[i] = new Object();
for (int i=0; i<n; i++) delete obj[i];
delete[] obj;
5. Object *obj = new Object();
obj->intArray = new int[10];
delete[] obj->intArray;
delete obj;
6. Object **obj = new Object[n];
for (int i=0; i<n; i++) {
obj[i] = new Object();
obj[i]->intArray = new int[10];
}
for (int i=0; i<n; i++) {
delete[] obj[i]->intArray;
delete obj[i];
}
delete[] obj;
Will that do it?
Not really. This is pretty fragile C++ code and doomed to break
eventually. For example, it's not exception-safe. Try to exploit the
strengths of C++. One of the biggest corner stones of modern C++
design is letting objects "own"/take care of other resources. C++
allows you to delegate the responsibility of cleaning up things so you
don't have to do it yourself.
Fragile:
int* p = new int[10];
...
delete[] p;
Good:
vector<int> v (10);
...
To put it differently: If you want memory to be released if a pointer
goes out of scope, the raw pointer type would be a misuse because it
doesn't have the semantics you actually want.
Instead of new[] and delete[], prefer std::vector. Instead of "naked"
new, prefer the use of std::unique_ptr (or std::shared_ptr) so that
every heap-allocated object is "owned" by at least one other object.
This makes "delete" in user code rather obsolete. And even "new"
should be avoided in preference of std::make_shared and
std::make_unique (make_unique is not yet standard but you can write it
yourself
template<class T, class...Args>
std::unique_ptr<T> make_unique(Args&&...args)
{
return {new T(std::forward<Args>(args)...)};
}
). In case you are worried about unnecessary copying with respect to
vectors and functions returning function-local vectors by value,
you'll be pleased to know that C++2011 will make sure this is about as
efficient as returning a raw pointer.
Cheers!
SG