来自 void 的 shared_ptr 的别名构造是否安全?
Is alias construction of shared_ptr from void safe?
这是一个关于 shared_ptr
别名构造函数和 UB 的完全假设性问题。
让我们想象一下我们将 std::shared_ptr<void>
存储在某个数据库中的情况。让我们想象一下,我们可以安全地将指向父类型 A
实例的 void *
转换为子类型 B
的指针(例如,通过编译时生成的代理) .
以下情况会导致UB吗,还是安全的?
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?
根据我的假设,应该没有 UB,因为别名构造函数应该只共享控制块,但是我不确定这里是否存在任何可能导致 UB 的实现定义的边缘情况或 STL 定义怪癖.
来自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() ...
所以这正是设想的用例。
这是一个关于 shared_ptr
别名构造函数和 UB 的完全假设性问题。
让我们想象一下我们将 std::shared_ptr<void>
存储在某个数据库中的情况。让我们想象一下,我们可以安全地将指向父类型 A
实例的 void *
转换为子类型 B
的指针(例如,通过编译时生成的代理) .
以下情况会导致UB吗,还是安全的?
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?
根据我的假设,应该没有 UB,因为别名构造函数应该只共享控制块,但是我不确定这里是否存在任何可能导致 UB 的实现定义的边缘情况或 STL 定义怪癖.
来自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() ...
所以这正是设想的用例。