c++castingvolatileobject-construction

What is the purpose for std::construct_at to cast through a pointer to volatile when using placement new?


According to cppreference, std::construct_at(T*p, Args&&... args) is equivalent to

return ::new (const_cast<void*>(static_cast<const volatile void*>(p)))
    T(std::forward<Args>(args)...);

What is the need/purpose for the cast 'through' const volatile void*? In other words, why is construct_at not simply equivalent to

return ::new (static_cast<void*>(p))
    T(std::forward<Args>(args)...);

Under which conditions would this latter code cause undesirable behaviour?


Solution

  • std::construct_at accepts as T any type... which may have cv-qualifiers.

    Meanwhile, static_cast may not cast away constness. The version you propose would fail for

    const foo * ptr = get_mem();
    ptr = std::construct_at(ptr); // Error here when naively static casting to void*
    

    But static_cast may add cv-qualifiers. So in order to be generic, the version that is standardized avoids this problem. It static casts to the most cv-qualified version of of a void pointer, and then removes those qualifiers.