Pages

boost::scoped_ptr

As a good introduction to some of the most interesting boost libraries you can read "Beyond the C++ Standard Library: An Introduction to Boost", by Björn Karlsson, an Addison Wesley Professional book. That's what I'm actually doing now to refresh the subject. And these are a few notes that I'm jotting down in the meanwhile.

The smart pointer scoped_ptr is close in its meaning to const auto_ptr, the major difference being is that the first has a reset() method that could be used to deleting or replacing the actual pointee, when required.

A scoped_ptr can't be copied, so using it makes clear that we want to use the pointee just in the current scope, and we want it to be deleted when we leave it.

Here is a little nonsensical example:

#include "boost/scoped_ptr.hpp"
#include <string>
#include <iostream>

using std::cout;
using std::endl;
using std::string;
using boost::scoped_ptr;

void scoped() {
// a string is created on the heap and used to initialize the smart pointer
scoped_ptr<string> p(new string("Use scoped_ptr often."));

// it is available an operator unspecified_bool_type()
if(p)
cout << *p << endl;

// smart pointer means we have access to the pointee methods
size_t i=p->size();
cout << "String size is " << i << endl;

*p = "Acts just like a pointer";

cout << "Now string is: " << *p << endl;

// the string on the heap is deleted automatically
}

No comments:

Post a Comment