C++20 sections · 1024 units
Open in Course

Creating shared_ptr

Factory function

Create with make_shared: auto p = make_shared(args);. This is more efficient than shared_ptr(new MyClass(args)) because it allocates the object and control block together.

The control block holds the reference count and other metadata. make_shared does one allocation for both, while the two-step version does two. Prefer make_shared for performance. Access works like unique_ptr: *p dereferences, p->method() calls methods.

The shared_ptr behaves like a pointer but with shared ownership semantics and automatic deletion.