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

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.