Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constexpr operator new

Tags:

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!

like image 721
Martin Kopecký Avatar asked Nov 21 '18 19:11

Martin Kopecký


People also ask

Is constexpr new?

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.

What is constexpr in C++11?

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.

Is constexpr guaranteed?

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.

Does constexpr improve performance?

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.


1 Answers

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 the constexpr specifier is implicitly an inline function or variable (9.1.6). If any declaration of a function or function template has a constexpr specifier, then all its declarations shall contain the constexpr 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.

like image 68
101010 Avatar answered Nov 15 '22 05:11

101010