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?
Explanation: Now, the variable c is 3.5, because in the above expression first a is converted into float therefore a/b is also float type. 7.0/2 is 3.5. Then that is assigned to the variable c. 2. Dynamic Cast 3. Const Cast 4. Reinterpret Cast Static Cast: This is the simplest type of cast that can be used. It is a compile-time cast.
A dynamic_cast works only polymorphic base class because it uses this information to decide safe downcasting. Downcasting: Casting a base class pointer (or reference) to a derived class pointer (or reference) is known as downcasting.
Casting is a technique by which one data type to another data type. The operator used for this purpose is known as the cast operator. It is a unary operator which forces one data type to be converted into another data type.
Note that C++20 added std::construct_at. But it did so for reasons other than consistency. They're there to support compile-time memory allocation and construction. You can call the "replaceable" global new operators in a constant expression (so long as you haven't actually replaced it).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With