skip to content

In C++, what does std::shared_ptr's aliasing constructor do, and when would you hand out a pointer created with it?

level: seniorimportance: nice to knowfreq 25%

answer

  1. two pointers, chosen separately
  2. owns one thing, points at another
  3. a member keeps its parent alive
  4. how the pointer casts work
  5. empty yet not null

basics

~20 s

std::shared_ptr<U>(owner, ptr) shares owner's control block but stores ptr, usually a member of the owned object. Holding the member pointer keeps the whole parent alive, so a caller can keep a part safely without knowing about the parent.

solid answer

~40 s

The constructor `template<class Y> shared_ptr(const shared_ptr<Y>& r, element_type* p) noexcept` builds a `shared_ptr` that **shares ownership with `r`** but whose `get()` returns `p`. Since each `shared_ptr` stores the object pointer and the control-block pointer separately, the two can name different things. The usual use is handing out a part of a shared object: `std::shared_ptr<Stats>(session, &session->stats)` gives a monitoring thread a pointer to one member that keeps the whole `Session` alive, so the member can never dangle while held. The standard's casts are built on it: `std::static_pointer_cast` returns `shared_ptr<T>(r, static_cast<...>(r.get()))`. The responsibility is yours: `p` must stay valid as long as the owner group lives, and the alias keeps the entire parent and its memory alive. C++20 added an overload that takes `r` by rvalue and leaves it empty.

code

cpp · 21 lines
cpp
#include <cstdio>
#include <memory>
#include <string>

struct Stats { long messages = 0; };
struct Session {
    std::string user;
    Stats stats;
    ~Session() { std::printf("~Session %s\n", user.c_str()); }
};

int main() {
    auto session = std::make_shared<Session>();
    session->user = "ann";
    // Shares session's control block but points at one member.
    std::shared_ptr<Stats> stats(session, &session->stats);
    std::printf("owners: %ld\n", session.use_count());
    session.reset();                                   // Session stays alive through stats
    stats->messages = 42;
    std::printf("messages: %ld, owners: %ld\n", stats->messages, stats.use_count());
}                                                      // stats destroyed: ~Session runs

go deeper

for a junior

Recall that a shared_ptr can point at a member while keeping its whole parent object alive.

for a middle

Explain the stored pointer versus the control block, and how the aliasing constructor sets them independently.

for a senior

Use aliases to hand out parts of shared objects safely, and spot the ones that pin large parents or point into reallocating containers.

for a principal

Weigh encapsulation through aliases against hidden lifetime extension when shared objects expose their parts to other subsystems.

## Two pointers that can name different things A `std::shared_ptr<T>` in libc++ and libstdc++ holds two pointers: the **stored pointer**, returned by `get()` and used by `*` and `->`, and the pointer to the **control block** that decides when something is destroyed. Usually both refer to the same object. The aliasing constructor separates them on purpose: ```cpp template<class Y> shared_ptr(const shared_ptr<Y>& r, element_type* p) noexcept; template<class Y> shared_ptr(shared_ptr<Y>&& r, element_type* p) noexcept; // C++20 ``` The standard says it constructs a `shared_ptr` that **stores `p` and shares ownership with the initial value of `r`**, with the postcondition `get() == p`; the rvalue overload, added in C++20, also leaves `r` empty. ## Handing out a part of a shared object In a chat server each `Session` is shared by a registry and by I/O callbacks. A metrics thread wants only the session's `Stats` member. Options: - a raw `Stats*` dangles when the session is destroyed while metrics still holds it; - a `std::shared_ptr<Session>` exposes the whole session to code that should see only counters; - an aliasing `std::shared_ptr<Stats>(session, &session->stats)` points at the member and **keeps the session alive** while it is held. The example on this page resets the last `Session` owner and still writes through the `Stats` alias; `~Session` runs only when the alias is destroyed. ## Where else it appears 1. **The pointer casts.** The standard specifies `std::static_pointer_cast<T>(r)` as returning `shared_ptr<T>(r, static_cast<typename shared_ptr<T>::element_type*>(r.get()))`; `dynamic_pointer_cast`, `const_pointer_cast` and `reinterpret_pointer_cast` follow the same pattern. Every cast result shares the original control block. 2. **Elements of an owned container.** A `shared_ptr<Message>` to one element of a `std::vector<Message>` owned by a shared `History` keeps the history alive — but the element address is invalidated if the vector reallocates, so the alias is only as stable as the container. 3. **Implementation-internal uses.** `enable_shared_from_this` is specified with an aliasing-style assignment that points the hidden `weak_ptr` at the derived object. ## The obligations it puts on you The standard's own notes spell them out: - Use of the constructor leads to a **dangling pointer unless `p` remains valid at least until the ownership group of `r` is destroyed**. A pointer into an object the group does not own, or into a container that may reallocate, breaks that. - It allows creating an **empty `shared_ptr` with a non-null stored pointer** (when `r` is empty): `use_count()` is 0, `get()` is non-null, and `if (sp)` tests the stored pointer, so it reads as true. That state is legal but surprising, and code that treats "non-null" as "owned" will be wrong. ## When a simpler tool fits The aliasing constructor is the right answer only when the caller must **hold** the part beyond the current call. If it only reads the part during a call, pass `const Stats&` from code that already owns the session. If it needs a value, copy the `Stats`. If it should observe the part without keeping the session alive, create the alias and then a `std::weak_ptr<Stats>` from it: the weak pointer shares the session's control block, so `lock()` succeeds exactly while the session lives. Reaching for an alias by default spreads hidden owners of the parent across the program. ## Costs and trade-offs | aspect | effect of an aliasing shared_ptr | |---|---| | lifetime | the whole parent stays alive while any alias is held | | memory | the parent's storage, and with `make_shared` its control block, stays allocated | | counting | the alias shares the parent's strong count; copies cost the usual atomic updates | | encapsulation | callers see only the member type, not the parent | A long-lived alias to a small member can therefore pin a large parent — the same retention problem as a long-lived owner, only harder to spot because the type does not mention the parent. ## Common mistakes - Expecting the alias to own only the member, so the rest of the parent could be destroyed. - Aliasing into a `std::vector` that later reallocates. - Assuming `use_count() > 0` whenever `get() != nullptr`.

  • How are std::static_pointer_cast and dynamic_pointer_cast related to the aliasing constructor?
    The standard specifies their results with it: `static_pointer_cast<T>(r)` returns `shared_ptr<T>(r, static_cast<...>(r.get()))`, and `dynamic_pointer_cast` does the same with `dynamic_cast`, returning an empty `shared_ptr` if the cast yields null. The result therefore shares the original control block rather than creating a new owner group.
  • What is an empty std::shared_ptr with a non-null stored pointer, and how can one arise?
    Calling the aliasing constructor with an empty `r` and a non-null `p` creates it: it owns nothing, so `use_count()` is 0, yet `get()` returns `p` and `if (sp)` is true because it tests the stored pointer. The standard allows it explicitly. Code that reads non-null as owned will be wrong for such a pointer.

  • An aliasing shared_ptr owns only the member it points to
  • The aliasing constructor creates a new control block for the member
  • A shared_ptr with a non-null get() always has use_count() above zero
  • Aliasing into a vector element is safe while the vector's owner lives

Assumes C++20 or later for the rvalue overload of the aliasing constructor; the const-reference form has existed since C++11.