Skip to content

Instantly share code, notes, and snippets.

@hkuno9000
Created October 1, 2015 17:50
Show Gist options
  • Save hkuno9000/f4e27bb8409ca0cc5867 to your computer and use it in GitHub Desktop.
Save hkuno9000/f4e27bb8409ca0cc5867 to your computer and use it in GitHub Desktop.
smart buffer for C++11
/// smart buffer for C++11
template<typename T, size_t N=256> class auto_buffer {
T mSmallBuf[N];
T* mBuf = mSmallBuf;
size_t mHeapSize = 0;
size_t mBufSize = N;
public:
auto_buffer() = default;
auto_buffer(const auto_buffer&) = delete; // no copy
auto_buffer& operator=(const auto_buffer&) = delete; // no copy
~auto_buffer() {
if (mBuf != mSmallBuf) delete[] mBuf;
}
T* oprator() { return mBuf; }
size_t size() const { return mBufSize; }
void reset() {
if (mBuf != mSmallBuf) delete[] mBuf;
mBuf = mSmallBuf;
mHeapSize = 0;
mBufSize = N;
}
bool resize(size_t n) { ///< resize buffer. buffered data is not kept.
if (n <= N || n <= mHeapSize) { mBufSize = n; return true; }
T* p = new T[n];
if (!p) { reset(); return false; }
if (mBuf != mSmallBuf) delete[] mBuf;
mBuf = p;
mBufSize = mHeapSize = n;
return true;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment