I was experimenting with overloading operators new
and delete
, and noticed that MSVC and GCC appear to differ in their implementation of operator delete
. Consider the following code:
#include <cstddef>
struct CL {
// The bool does nothing, other than making these placement overloads.
void* operator new(size_t s, bool b = true);
void operator delete(void* o, bool b = true);
};
// Functions are simple wrappers for the normal operators.
void* CL::operator new(size_t s, bool b) { return ::operator new(s); }
void CL::operator delete(void* o, bool b) { return ::operator delete(o); }
auto aut = new (false) CL;
This code will compile properly with GCC (tested with both Ideone and TutorialsPoint online compilers), but not with MSVC (tested with MSVS 2010, MSVS 2015 online, and Rextester).
While it appears that GCC compiles it as one would expect, MSVC emits error C2831; I checked Cppreference, but couldn't find an answer; the default parameter page doesn't mention operators, and the operator overloading & operator delete pages don't mention default parameters. Similarly, the Overloading new
and delete
entry in SO's C++ FAQ doesn't mention default parameters.
So, in light of this, which of these behaviours (allowing default parameters, or treating them as an error) is compliant with the C++ standard?
Links:
No you cannot overload functions on basis of value of the argument being passed, So overloading on the basis of value of default argument is not allowed either. You can only overload functions only on the basis of: Type of arguments. Number of arguments.
New and Delete operators can be overloaded globally or they can be overloaded for specific classes. If these operators are overloaded using member function for a class, it means that these operators are overloaded only for that specific class.
Dot (.) operator can't be overloaded, so it will generate an error.
Which of the following operators are overloaded by default by the compiler in every user defined classes even if user has not written? Explanation: Assign operator is by default available in all user defined classes even if user has not implemented.
An operator function cannot have default arguments (8.3.6), except where explicitly stated below.
(C++14 standard, [over.oper]/8; an identical sentence appears in the C++03 standard).
The specific case where default arguments are allowed is the case of the function call operator (operator()
; see [over.call]/1). In all other cases they are disallowed.
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