9.4. Making Member Functions Exception-Safe

Problem

You are writing a member function and you need it to uphold the basic and strong exception-safety guarantees, namely that it won’t leak resources and it won’t leave the object in an invalid state if an exception is thrown.

Solution

Be aware of what operations can throw exceptions and do them first, usually in a try/catch block. Once the code that can throw exceptions is done executing, then you can update the object state. Example 9-4 offers one way to make a member function exception-safe.

Example 9-4. An exception-safe member function

class Message { public: Message(int bufSize = DEFAULT_BUF_SIZE) : bufSize_(bufSize), initBufSize_(bufSize), msgSize_(0), buf_(NULL) { buf_ = new char[bufSize]; } ~Message() { delete[] buf_; } // Append character data void appendData(int len, const char* data) { if (msgSize_+len > MAX_SIZE) { throw out_of_range("Data size exceeds maximum size."); } if (msgSize_+len > bufSize_) { int newBufSize = bufSize_; while ((newBufSize *= 2) < msgSize_+len); char* p = new char[newBufSize]; // Allocate memory // for new buffer copy(buf_, buf_+msgSize_, p); // Copy old data copy(data, data+len, p+msgSize_); // Copy new data msgSize_ += len; bufSize_ = newBufSize; delete[] buf_; // Get rid of old buffer and point to new buf_ = p; } else { copy(data, data+len, buf_+msgSize_); msgSize_ += len; } } // Copy the data out to the caller's buffer int getData(int maxLen, char* data) { if (maxLen < msgSize_) { throw out_of_range("This ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.