O'Reilly logo

C++ Cookbook by Jeff Cogswell, Jonathan Turkanis, Christopher Diggins, D. Ryan Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required