Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page