Is it possible to overload the operator new to be constexpr function? Something like:
constexpr void * operator new( std::size_t count );
The reason why would be to execute constexpr function within the overloaded operator body where count argument value would be an input data... As the operator is invoked by:
SomeClass * foo = new SomeClass();
The size of the data type is know at compile time, isn’t it? (count== sizeof(SomeClass)
) So the count can be considered as compile time constant?
constexpr void * operator new( std::size_t count )
{
if constexpr ( count >= 10 ) { /* do some compile-time business */ }
}
Many thanks in advance to anyone willing to help!
There is no constexpr new operator. Since C++20, you can use new operator in constexpr expressions in the condition that you only use a replaceable global allocation function (it means that you don't use a placement new or user-defined allocation function) and that you deallocate the data in the same expression.
The keyword constexpr was introduced in C++11 and improved in C++14. It means constant expression. Like const , it can be applied to variables: A compiler error is raised when any code attempts to modify the value. Unlike const , constexpr can also be applied to functions and class constructors.
A constexpr function that is eligible to be evaluated at compile-time will only be evaluated at compile-time if the return value is used where a constant expression is required. Otherwise, compile-time evaluation is not guaranteed.
Using constexpr to Improve Security, Performance and Encapsulation in C++ constexpr is a new C++11 keyword that rids you of the need to create macros and hardcoded literals. It also guarantees, under certain conditions, that objects undergo static initialization.
You can't overload operator new
to be constexpr
, the main problem is attributed to the C++ standard directive §9.1.5/1 The constexpr
specifier [dcl.constexpr] (Emphasis Mine):
The
constexpr
specifier shall be applied only to the definition of a variable or variable template or the declaration of a function or function template. A function or static data member declared with theconstexpr
specifier is implicitly an inline function or variable (9.1.6). If any declaration of a function or function template has aconstexpr
specifier, then all its declarations shall contain theconstexpr
specifier.
That is, in order to overload operator new
all its previous declarations must also be constexpr
, which they aren't and thus overloading it as constexpr
you get a compile time error.
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