valuable
A header-only C++ library providing value_ptr — a smart-pointer with value semantics that fills the gap left by unique_ptr, shared_ptr, and weak_ptr.
valuable is a header-only C++ library that provides value_ptr — the missing smart-pointer with value semantics.
The Problem
The C++ standard library provides unique_ptr, shared_ptr, and weak_ptr, but none of them offer value semantics. When you copy a unique_ptr it is forbidden; when you copy a shared_ptr you share ownership by reference.
Sometimes you want a heap resource that behaves like a value — where copying the container copies the resource. This is particularly useful for:
- Recursive data types (trees, linked lists) — which require pointer indirection for memory layout, but benefit from value semantics
- PImpl pattern — where you want the outer class to be copyable without writing a copy constructor by hand
- Thread safety — because
value_ptrshares no memory, it is inherently thread-safe
Quick Comparison
| Name | Ownership | Copyable | Semantics |
|---|---|---|---|
unique_ptr | Unique | ❌ | Reference |
shared_ptr | Shared | ✅ | Reference |
weak_ptr | None | ✅ | Optional-reference |
value_ptr | Unique | ✅ | Value |
Usage
Recursive Data Types
#include <value_ptr.hpp>
struct Tree {
std::string name;
value_ptr<Tree> left;
value_ptr<Tree> right;
};
int main() {
Tree root{"root", Tree{"left"}, Tree{"right"}};
root.left = root; // deep copy — no cyclic references
}PImpl Pattern
struct Foo {
Foo(int x);
// value_ptr gives value semantics for free — no hand-written copy constructor
Foo(Foo const&) = default;
Foo& operator=(Foo const&) = default;
~Foo() = default;
struct Pimpl;
value_ptr<Pimpl> ptr;
};How It Works
value_ptr is implemented as a unique_ptr with a custom copy constructor. Whilst copying a unique_ptr is forbidden, copying a value_ptr constructs a new value_ptr pointing to its own deep copy of the resource. The destructor is handled by the underlying unique_ptr.
Installation
valuable is header-only. Clone and add the include path:
git clone https://github.com/LoopPerfect/valuableRelated
- value_ptr — The Missing C++ Smart-Pointer — In-depth article with motivating examples and implementation details.
- Experimenting with Small-Buffer Optimization — More C++ memory management and type-erasure patterns.