Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 217
Walter Avatar asked Aug 09 '20 10:08

Walter


People also ask

Which type of cast is assigned to the variable C?

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.

Why dynamic_cast works only on polymorphic base class?

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.

What is the use of the cast operator in C?

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.

What is the use of construct_at in C++?

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).


1 Answers

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.

like image 112
StoryTeller - Unslander Monica Avatar answered Sep 19 '22 23:09

StoryTeller - Unslander Monica