Motivated by this not very well asked duplicate, I believe the problem deserves a new standalone clearly titled question. The following code triggers a compilation error with GCC 8.1.0 and Clang 6.0.0, but not with MSVC 19.00:
class X {
public:
X() /* noexcept */ { }
private:
static void operator delete(void*) { }
};
int main() {
X* x = new X{};
}
From expr.new:
If any part of the object initialization described above terminates by throwing an exception and a suitable deallocation function can be found, the deallocation function is called to free the memory in which the object was being constructed, after which the exception continues to propagate in the context of the new-expression. If no unambiguous matching deallocation function can be found, propagating the exception does not cause the object's memory to be freed. [ Note: This is appropriate when the called allocation function does not allocate memory; otherwise, it is likely to result in a memory leak. — end note ]
In fact, this does not imply that the compilation error should be triggered if the matching deallocation function ::operator delete
cannot be found. Or, does making it private just results in something like can be found but cannot be accessed? Which compilers are right?
There are two questions here:
operator delete
found even though it's private?C++ first tries to find a name anywhere; checking access protection is a later phase.
Thus, your
operator delete
is found, but inaccessible.operator delete
be accessible when the constructor isnoexcept
?The wording "If any part of the object initialization [...] terminates by throwing an exception" suggests that the rest of the paragraph doesn't apply because of the
noexcept
.However, as suggested by "any part of...", there may be exceptions inbetween the allocation and entering the constructor (while evaluating initialisers), or after exiting the constructor (while destroying initialisers).
Consider
where the
Y
copy constructor throws before you enterX
's constructor, but after allocation, so the memory needs to be released.So I think Visual C++ is wrong (again).
Visual studio is being weird with the
noexcept
specifier. On paper, it shouldn't build. The reason is that the decllocation function is looked up independently from the allocation function.According to p20, the deallocation function has to be looked up since we are creating a class object. Then the deallcoation function is found successfully, and is unambiguous (it's the member). Since access specifiers are checked only after name lookup, this should cause an error. GCC and Clang are correct.