Wal*_*ter 8 c++ casting volatile object-construction
根据cppreference,std::construct_at(T*p, Args&&... args)相当于
return ::new (const_cast<void*>(static_cast<const volatile void*>(p)))
T(std::forward<Args>(args)...);
Run Code Online (Sandbox Code Playgroud)
演员“通过”的需要/目的是什么const volatile void*?换句话说,为什么construct_at不简单地等同于
return ::new (static_cast<void*>(p))
T(std::forward<Args>(args)...);
Run Code Online (Sandbox Code Playgroud)
在哪种情况下,后一种代码会导致不良行为?
std::construct_at接受T任何类型...可能有 cv 限定符。
同时,static_cast 也不能抛弃constness。您建议的版本将失败
const foo * ptr = get_mem();
ptr = std::construct_at(ptr); // Error here when naively static casting to void*
Run Code Online (Sandbox Code Playgroud)
但static_cast 可以添加简历限定符。所以为了通用,标准化的版本就避免了这个问题。它静态转换为指针的最符合 cv 限定的版本void,然后删除这些限定符。