template <typename T>
class ScopedArray {
private:
T* ptr;
public:
explicit ScopedArray(T* p = nullptr) : ptr(p) {}
~ScopedArray() {
delete[] ptr;
}
T& operator[](int index) const { return ptr[index]; }
T* get() const { return ptr; }
void reset(T* p = nullptr) {
if (ptr != p) {
delete[] ptr;
ptr = p;
}
}
// Prevent copy
ScopedArray(const ScopedArray&) = delete;
ScopedArray& operator=(const ScopedArray&) = delete;
};
#include "ScopedPointer.h"
void loadData() {
ScopedArray<char> buffer(new char[1024]);
if (someCondition()) {
return; // no memory leak!
}
// buffer is auto-deleted when going out of scope
}