Consider this example
#include <iostream>
struct A{
void* operator new(std::size_t N, std::align_val_t){ // #1
return malloc(sizeof(char)* N);
}
};
int main(){
auto ptr = new A; // #2
}
Both GCC and Clang complain that
<source>:9:17: error: no matching function for call to 'operator new'
auto ptr = new A;
^
<source>:4:11: note: candidate function not viable: requires 2 arguments, but 1 was provided
void* operator new(std::size_t N, std::align_val_t){
^
1 error generated.
However, [expr.new] p19 says
Overload resolution is performed on a function call created by assembling an argument list. The first argument is the amount of space requested, and has type std::size_t. If the type of the allocated object has new-extended alignment, the next argument is the type's alignment, and has type std::align_val_t. If the new-placement syntax is used, the initializer-clauses in its expression-list are the succeeding arguments. If no matching function is found then
- if the allocated object type has new-extended alignment, the alignment argument is removed from the argument list;
- otherwise, an argument that is the type's alignment and has type std::align_val_t is added into the argument list immediately after the first argument;
and then overload resolution is performed again.
The found candidate for the allocation function calling in the new expression at #2
is #1
. For the first time, the assembling argument list is sizeof(A)
, which cannot make #1
a matching function, then according to the rule, the assembling arguments will be sizeof(A),std::align_val_t(alignof(A))
, which can make #1
a matching function. Also, it's a typical example recorded in [expr.new] p20
new T
results in one of the following calls:
- operator new(sizeof(T))
- operator new(sizeof(T), std::align_val_t(alignof(T)))
Why do GCC and Clang reject this example? Is this defect of GCC and Clang? Or, Do I misunderstand something?
CodePudding user response:
At present the only major compiler that implements CWG 2282 is MSVC. I'm not aware of any current effort or feature requests for GCC or clang.
Also, I don't believe the __cpp_aligned_new
feature test macro has been updated for CWG 2282, so you'll need to use old-fashioned compiler version checking to determine whether the feature is available.