5

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:

Community
  • 1
  • 1

1 Answers1

8

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.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • Thanks, that's useful to know. I didn't think to check the standard directly. – Justin Time - Reinstate Monica May 24 '16 at 00:05
  • So this is a gcc bug (the compiler should issue a diagnostic), if OP was compiling in standard mode. – M.M May 24 '16 at 01:23
  • @M.M After you mentioned it, I tried it with both `g++ -c -std=c++11 main.cpp`,`g++ -c -std=c++1y main.cpp`, and `g++ -c -std=c++1y -Wall -pedantic-errors main.cpp` on TutorialsPoint (which uses `gcc version 5.3.1 20151207 (Red Hat 5.3.1-2) (GCC)` for the online environment), and it still compiled. Not sure if there's a way to force stricter standard compliance, I'm not all that familiar with GCC. – Justin Time - Reinstate Monica May 24 '16 at 19:14
  • Can `operator delete` has extra paramters like `operator delete(void*,size_t,A,B)` just like the `operator new`?And we use it like `delete(a,b) p` ? – choxsword Feb 25 '18 at 04:47