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

8.3. Using Constructors and Destructors to Manage Resources (or RAII)

Problem

For a class that represents some resource, you want to use its constructor to acquire it and the destructor to release it. This technique is often referred to as resource acquisition is initialization (RAII).

Solution

Allocate or acquire the resource in the constructor, and free or release the resource in the destructor. This reduces the amount of code a user of the class must write to deal with exceptions. See Example 8-3 for a simple illustration of this technique.

Example 8-3. Using constructors and destructors

#include <iostream>
#include <string>

using namespace std;

class Socket {
public:
   Socket(const string& hostname) {}
};

class HttpRequest {
public:
   HttpRequest (const string& hostname) :
      sock_(new Socket(hostname)) {}
   void send(string soapMsg) {sock_ << soapMsg;}
  ~HttpRequest () {delete sock_;}
private:
   Socket* sock_;
};

void sendMyData(string soapMsg, string host) {
   HttpRequest req(host);
   req.send(soapMsg);
   // Nothing to do here, because when req goes out of scope
   // everything is cleaned up.
}

int main() {
   string s = "xml";
   sendMyData(s, "www.oreilly.com");
}

Discussion

The guarantees made by constructors and destructors offer a nice way to let the compiler clean up after you. Typically, you initialize an object and allocate any resources it uses in the constructor, and clean them up in the destructor. This is normal. But programmers have a tendency to use the create-open-use-close sequence of ...

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