DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

C++11 Smart Pointers are Not Just For Memory

Grigory Javadyan user avatar by
Grigory Javadyan
·
Jan. 25, 13 · Interview
Like (0)
Save
Tweet
Share
5.74K Views

Join the DZone community and get the full member experience.

Join For Free

RAII is a useful idiom. It helps prevent resource leaks by making sure that resources are freed when they are no longer needed, and as such, provides a simple form of garbage collection.

The C++11 standard library provides a number of class templates (shared_ptr, unique_ptr, weak_ptr) to use this idiom for memory management.

However, memory is not the only resource that we have to manage. Sometimes we have to make sure a handle (e.g. a file descriptor, an OpenGL texture object, a HWND, etc.) returned by some library is freed properly.

There is a useful trick that allows you to use the standard smart pointer templates to manage such handles as well.

To accomplish this, we need to do two things:

  • Specify how the resource should be freed;
  • Make sure that internally, the smart pointer stores a handle, not a pointer

All smart pointer templates have an additional template parameter that allows us to specify a custom deleter type. A deleter type is basically just a class that has an overloaded operator() which accepts a pointer (or a handle, in our case), and frees the resource associated with it.

Let’s show this on a simple example. In this example, I’ll write a custom deleter for an OpenGL shader:

struct ShaderDeleter
{
  void operator()(GLuint shader)
  {
    glDeleteShader(shader);
  }
};

We can then use it with a smart pointer to replace the default deleter:

std::unique_ptr<GLuint, ShaderDeleter> smart_shader(glCreateShader());

But we’re not done yet. This unique_ptr will store a pointer to GLuint internally, but we really want it to just store a GLuint, our handle. So how do we accomplish that?

The internal “dumb” pointer of std::unique_ptr<T, D> doesn’t just have the type “T*”. Its type is std::unique_ptr<T,D>::pointer, which is defined by the standard to be std::remove_reference<D>::type::pointer, or, if such type does not exist, T*.

In other words, if you add a typedef named “pointer” to your custom deleter, it will be used by the smart pointer internally. So, to get the desired behavior we just have to do this:

struct ShaderDeleter
{
  typedef GLuint pointer; // Note the added typedef
  void operator()(GLuint shader)
  {
    glDeleteShader(shader);
  }
};

So, now our trick works! We create a new OpenGL shader during initialization and it will be deleted once the smart pointer goes out of scope!

std::unique_ptr<GLuint, ShaderDeleter> smart_shader(glCreateShader());

There still is one caveat. The indirection operator won’t work as expected with this pointer. Writing something like:

glAttachShader(p, *smart_shader);

yields a somewhat cryptic compilation error in Visual Studio 2012. You should use the get() member function instead, like so:

glAttachShader(p, smart_shader.get());

It’s pretty easy to understand why this is happening by taking a look at the implementation of operator* in unique_ptr:

//...
typename add_reference<_Ty>::type operator*() const
{  // return reference to object
	return (*this->_Myptr);
}
//...

It’s trying to apply the indirection operator to a GLuint. Clearly, this should fail.

So why does it work when we don’t invoke the indirection operator on the smart pointer? That’s because the compiler won’t even attempt to generate code for a non-virtual member function of a class template if it’s never used (this behavior is, in fact, enforced by the language standard). Incidentally, code for virtual member functions will ALWAYS be generated (I’ll let you figure out why :) )


Pointer (computer programming) Memory (storage engine) c++

Published at DZone with permission of Grigory Javadyan, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Key Considerations When Implementing Virtual Kubernetes Clusters
  • Top Five Tools for AI-based Test Automation
  • Debugging Threads and Asynchronous Code
  • A Real-Time Supply Chain Control Tower Powered by Kafka

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: