paint-brush
value_ptr — The Missing C++ Smart-pointerby@buckaroo.pm
12,504 reads
12,504 reads

value_ptr — The Missing C++ Smart-pointer

by Buckaroo - C/C++ PackageMay 25th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Use the <code class="markup--code markup--p-code">value_ptr</code> smart-pointer to get value semantics on a heap resource. At the cost of some extra copying, your code will be simpler and easier to reason about.

Company Mentioned

Mention Thumbnail
featured image - value_ptr — The Missing C++ Smart-pointer
Buckaroo - C/C++ Package HackerNoon profile picture

TL;DR

Use the value_ptr smart-pointer to get value semantics on a heap resource. At the cost of some extra copying, your code will be simpler and easier to reason about.

Choose which smart-pointer to use with this cheat-sheet.

A implementation of value_ptr can be found on GitHub.

Introduction

Language features like templates, lambdas and lexically-scoped destructors empower C++ programmers to write higher-order containers to handle an object’s lifetime and side-effects, documenting them in an understandable way in the type-system.

With smart-pointers, encoding ownership semantics and managing resources has never been easier. We can find smart-pointers in the standard library for the most common use-cases, however none of these smart-pointers provides value semantics. This article will introduce the value_ptr, alongside some motivating examples.

But first, let’s take a look at the functionality that the C++ 11 standard library already offers:

(Dumb) Raw Pointers

Yes, raw pointers can be still used, but you should avoid them if a smart-pointer is applicable. This is because raw pointers do not convey any information about a resource’s ownership model.

Furthermore, allocation and deallocation must be managed by the programmer, which may lead to bugs like double-delete or memory-leaks.

Take a look at this code:

From just three lines, there are so many unanswered questions:

  • Can x be nullptr and do I have to check?
  • Is x managed? Can I delete x? Must I delete x?
  • If I delete y before foo, is foo still valid?
  • If foo gets destroyed, will y be deleted?

Used correctly, a smart-pointer makes these clear.

unique_ptr

unique_ptr manages the lifetime of an resource by taking sole ownership of it and binding that to its lexical scope. While copying is not possible, the ownership can be transferred via std::move.

Use unique_ptr when:

  • You want to tie the lifetime of a heap resource to a lexical scope
  • You want to enforce that the resource only has one owner at a time

Example

shared_ptr

shared_ptr allows for multiple resource owners by counting the number of references under management. The container’s copy-constructor increments the counter and decrements it on destruction. If the counter hits zero, then the resource will be disposed.

Use shared_ptr when:

  • You want to share ownership between multiple references
  • You want to dispose of a resource automatically when it is no longer used
  • You don’t have cyclic dependencies
  • The overhead of reference counting is acceptable

Example

weak_ptr

We saw that we can use shared_ptr with multiple owners, but what happens if we have cycles in the ownership graph? In this case, we would leak memory as the reference counter would never hit zero! The owners in the cycle would keep each-other alive.

This is where weak_ptr comes into play. weak_ptr is like shared_ptr but it does not increment the reference counter. If you replace the cycle-branch in your ownership graph with a weak_ptr, then reference counting will work correctly.

Example

Use weak_ptr when:

  • You absolutely must have a cyclic ownership graph

Introducing value_ptr

Value semantics make your code easier to reason about because unlike pointers, ownership must be strictly hierarchical and exclusive.

value_ptr allows us to enforce those semantics on a copyable resource on the heap.

How it Works

  • value_ptr has exclusive ownership of a resource on the heap.
  • When you assign one value_ptr to another, a new value_ptr object is constructed that points to its own copy of the previous value_ptr’s resource.
  • The resource is destroyed when the value_ptr leaves its lexical scope.
  • No memory is shared, so value_ptr is inherently thread-safe.
  • A modern compiler is smart enough to remove most redundant copies.

Example 1 — Recursive Data Types

Recursive types like trees must be implemented via a pointer in C++ so the layout in memory can be computed at compile-time. However, despite using a pointer, we might still want the simplicity of value-semantics:

Example 2 — The PImpl Pattern

Sometimes we want to separate the interface of a class from its implementation. This might be to hide code behind a compiled library, or to enforce a constant stack-size.

Since the lifetime is bound to the owner, a smart-pointer is appropriate here, but what semantics do we want to have? Unlike shared_ptr and unique_ptr, value_ptr gives us value semantics.

Header

Translation-unit

More Resources About the PImpl Pattern

Implementing value_ptr

You might have noticed that value_ptr is similar to unique_ptr, but with a different copy-constructor. Whilst copying a unique_ptr is forbidden, copying a value_ptr will create a copy of the resource. Thus, we can implement value_ptr by leveraging unique_ptr and a copy function.

This is what we have done; take a look on GitHub, or test-drive our implementation with Buckaroo:

buckaroo install loopperfect/valuable

Summary

Value semantics are easy to reason about, and are often useful even for heap objects. The C++ standard library does not provide a smart-pointer with value semantics, but C++ has the features to allow us to roll-our-own.

Can’t decide which smart-pointer to use? Here’s a quick chart: