Automate Resource Management with shared_ptr

Automate Resource Management with shared_ptr

td::auto_ptr is the only smart pointer class available in C++98. Alas, since this class is neither assignable nor copy-constructible, creating containers of auto_ptr objects is illegal. This limitation has been a source of frustration and confusion for years. At last, the Library Extensions Technical Report 1 (TR1 for short) rectifies this embarrassment, adding a new smart pointer class called shared_ptr to the standard header . The following sections explain how to use shared_ptr to automate resource management. You will also learn how shared_ptr can simplify programming tasks that I’ve shown here before?such as simulating heterogeneous containers and implementing the Pimpl idiom.


How to combine smart pointers with STL containers and algorithms without risking undefined behavior?


Use the std::tr1::shared_ptr class.

Presenting the Problem
A typical smart pointer wraps a raw pointer to a dynamically allocated object and overloads the operators -> and *. The responsibility for deleting the pointer is delegated to the smart pointer’s destructor, thus freeing you from manual?and bug-prone?memory management. The problem, however, is that auto_ptr, the only smart pointer class available in C++98, has peculiar copy and assignment semantics. When you assign an auto_ptr x to another auto_ptr y, not only is the target object modified (as expected) but so is the source object, which becomes null. This behavior makes auto_ptr incompatible with STL containers and algorithms. Let’s see how shared_ptr solves this problem.

Author’s Note: To use shared_ptr you need to download its sources from Boost. Notice that this Solution adheres to the official TR1 Draft Proposal, which differs slightly from boost::shared_ptr.

Construction and Initialization
shared_ptr‘s default constructor creates what is known as an empty smart pointer, i.e., an object whose pointer is null. You can assign a valid pointer to it later:

class Foo{ int x;public: explicit Foo(int val=0) :x(val) {} void do_something() {/*..*/} int show_x() const {std::cout<< x< //for shared_ptrusing std::tr1::shared_ptr;int main(){ shared_ptr pf; //pf is an empty shared_ptr //bind a "live" pointer to pf pf=new Foo; pf->do_mesomething(); //using shared_ptr's overloaded -> (*pf).show_x();//using shared_ptr's overloaded *}//pf's destructor called here, destroying Foo

shared_ptr defines a conversion operator to bool. This is useful for testing whether the shared_ptr is empty. To access the raw pointer directly, call get():

if (pf) { //ensure that pf isn't empty before calling get Foo *palias = pf.get();}

The second shared_ptr constructor takes a pointer to a dynamically allocated object and an optional deleter. The following example defines a deleter and passes its address to shared_ptr’s constructor:

void my_deleter(Foo *ptr){ delete ptr; std::cout<< "using custom deleter" < pf (new Foo, my_deleter); 

A deleter can be any callable entity: a free function, a function object, etc. When a user-defined deleter d is provided, shared_ptr‘s destructor calls:

d(ptr);

Instead of deleting ptr directly. A custom deleter enables you to bind shared_ptr to a pointer that was allocated in a different DLL, for example.

Certain resources such as file descriptors, synchronization objects, and device contexts require that a special API function be called to release them. Using a custom deleter, shared_ptr can manage such resources elegantly. In the following example, shared_ptr holds a mutex pointer obtained from an API function. When the shared_ptr object is destroyed, the release_mutex() function is called automatically:

//API functions for acquiring and releasing a mutexmutex_t* get_mutex(pid_t pid);int release_mutex(mutex_t* pmx);shared_ptr  pmutex (get_mutex(mypid),                                            release_mutex);

Counting on Reference Counting
Each shared_ptr destructor call decrements the bound pointer’s reference count. When the reference count reaches 0, the pointer is deleted. This property enables you to combine shared_ptr with STL containers and algorithms. The following example of creating a heterogeneous container is based on my September 2000 10-Minute Solution. This version however uses shared_ptr instead of bare pointers.

First, review the class hierarchy:

class mutimedia_file {public: explicit mutimedia_file(const string& filename); virtual ~mutimedia_file(); int virtual play();//..};class wav_file : public mutimedia_file;class mp3_file : public mutimedia_file;class ogg_file : public mutimedia_file;

Here’s how you populate the vector with heterogeneous shared_ptrs:

typedef std::tr1::shared_ptr  Pmm;typedef std::vector   Vpmm;void fill_and_play(Vpmm & v) { Pmm temp(new mp3_file("crazy4u"));//#1 create shared_ptr v.push_back(temp);//#2 store a copy of temp in v    //reuse temp  temp.reset(new wav_file("email_alert")); #3 v.push_back(temp); // insert shared_ptr to v v[0]->play(); // mp3_file::play() v[1]->play(); // wav_file::play());

Notice how fill() recycles the same shared_ptr object by calling the reset() member function. temp.reset(p2) causes temp to replace its existing pointer p with p2 and decrement p‘s reference count. Because a copy of the original shared_ptr has already been stored in the vector (line #2), p‘s reference count is higher than 0, and therefore the reset() call doesn’t delete the original pointer allocated in line #1. When fill() exits, temp is destroyed but the shared_ptrs stored in v keep the reference count of all pointers above 0. These pointers are deleted only when v itself is destroyed.

As far as heterogeneity is concerned, the code works correctly because assigning shared_ptr or T* to shared_ptr is perfectly legal as long as there is an implicit conversion from T* to U*. Furthermore, you can use a shared_ptr to store any pointer type in the container since shared_ptr‘s constructor is templated on the argument’s type:

shared_ptr  pf(new Foo);//fine

When pf is destroyed, it invokes Foo‘s destructor, as expected.

Pimpl Revisited
shared_ptr can eliminate the hassles of manual memory management when implementing the Pimpl idiom, which I presented here last month. In the header file containing the class’ declaration, replace the opaque pointer member with a shared_ptr (the revised code is highlighted):

//++file string.h#include #include //for shared_ptrclass String{public: String (); ~String(); //... size_t length() const; ostream & operator << (ostream& s) const; //...private: struct StringImpl; //fwd declaration of internal struct shared_ptr  pimpl; //instead of opaque ptr };In the .cpp file, remove the destructor://++file string.cpp#include #include "Lock.h"#include "String.h"struct String::StringImpl{ vector  vc; size_t len; Lock lck;};String::String(): pimpl (new String::StringImpl) {}

That’s all!

devx-admin

devx-admin

Share the Post:
Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time

Semiconductor Stock Plummet

Dramatic Downturn in Semiconductor Stocks Looms

Recent events show that the S&P Semiconductors Select Industry Index seems to be experiencing a downturn, which could result in a decline in semiconductor stocks. Known as a key indicator

Anthropic Investment

Amazon’s Bold Anthropic Investment

On Monday, Amazon announced its plan to invest up to $4 billion in the AI firm Anthropic, acquiring a minority stake in the process. This decision demonstrates Amazon’s commitment to

AI Experts Get Hired

Tech Industry Rehiring Wave: AI Experts Wanted

A few months ago, Big Tech companies were downsizing their workforce, but currently, many are considering rehiring some of these employees, especially in popular fields such as artificial intelligence. The

Lagos Migration

Middle-Class Migration: Undermining Democracy?

As the middle class in Lagos, Nigeria, increasingly migrates to private communities, a PhD scholar from a leading technology institute has been investigating the impact of this development on democratic

AI Software Development

ChatGPT is Now Making Video Games

Pietro Schirano’s foray into using ChatGPT, an AI tool for programming, has opened up new vistas in game and software development. As design lead at business finance firm Brex, Schirano

Llama Codebot

Developers! Here’s Your Chatbot

Meta Platforms has recently unveiled Code Llama, a free chatbot designed to aid developers in crafting coding scripts. This large language model (LLM), developed using Meta’s Llama 2 model, serves

Tech Layoffs

Unraveling the Tech Sector’s Historic Job Losses

Throughout 2023, the tech sector has experienced a record-breaking number of job losses, impacting tens of thousands of workers across various companies, including well-established corporations and emerging startups in areas

Chinese 5G Limitation

Germany Considers Limiting Chinese 5G Tech

A recent report has put forth the possibility that Germany’s Federal Ministry of the Interior and Community may consider limiting the use of Chinese 5G technology by local network providers

Modern Warfare

The Barak Tank is Transforming Modern Warfare

The Barak tank is a groundbreaking addition to the Israeli Defense Forces’ arsenal, significantly enhancing their combat capabilities. This AI-powered military vehicle is expected to transform the way modern warfare

AI Cheating Growth

AI Plagiarism Challenges Shake Academic Integrity

As generative AI technologies like ChatGPT become increasingly prevalent among students and raise concerns about widespread cheating, prominent universities have halted their use of AI detection software, such as Turnitin’s

US Commitment

US Approves Sustainable Battery Research

The US Department of Energy has revealed a $325 million commitment in the research of innovative battery types, designed to enable solar and wind power as continuous, 24-hour energy sources.

Netanyahu Musk AI

Netanyahu and Musk Discuss AI Future

On September 22, 2023, Israeli Prime Minister Benjamin Netanyahu met with entrepreneur Elon Musk in San Francisco prior to attending the United Nations. In a live-streamed discussion, Netanyahu lauded Musk

Urban Gardening

Creating Thriving Cities Through Urban Gardening

The rising popularity of urban gardening is receiving increased recognition for its numerous advantages, as demonstrated in a recent study featured in the Environmental Research Letters journal. Carried out by