Home > database >  Is alias construction of shared_ptr from void safe?
Is alias construction of shared_ptr from void safe?

Time:06-02

This is an entirely hypothetical question about shared_ptr aliasing constructor and UB.

Lets imagine a situation where we store std::shared_ptr<void> in some database. Lets also imagine that we can safely cast a void * pointing to an instance of a parent type A to a pointer of a child type B (ex. via a compile-time generated proxy).

Will the following situation result in UB, or is it safe?

std::shared_ptr<void> sp_v = get_vp(); // sp_v points to an instance of parent type `A`
B *ptr_b = cast_to_b(sp_v.get());      // Safe cast of `void *` aliasing `A *` to `B *` via a proxy.

std::shared_ptr<B> sp_b = std::shared_ptr<B>{sp_v, ptr_b}; // <- Potential UB here?

From what i assume, there should be no UB, as aliasing constructor should only share the control block, however i am not sure if there are any implementation-defined edge cases or STL definition quirks here that might result in UB.

CodePudding user response:

From https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr:

... such as in the typical use cases where ptr is a member of the object managed by r or is an alias (e.g., downcast) of r.get() ...

So this is exactly the envisioned use case.

  • Related