【问题标题】:Can overloaded operator delete have default parameters?重载的操作符删除可以有默认参数吗?
【发布时间】:2016-05-23 23:43:18
【问题描述】:

我正在尝试重载运算符newdelete,并注意到MSVC 和GCC 在operator delete 的实现上似乎有所不同。考虑以下代码:

#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;

此代码可以使用 GCC 正确编译(使用 Ideone 和 TutorialsPoint 在线编译器测试),但不能使用 MSVC 编译(使用 MSVS 2010、MSVS 2015 在线和 Rextester 测试)。

虽然 GCC 似乎按预期编译它,但 MSVC 发出错误 C2831;我检查了 Cppreference,但找不到答案; default parameter 页面没有提到操作符,operator overloading & operator delete 页面没有提到默认参数。同样,SO 的 C++ FAQ 中的 Overloading new and delete 条目也没有提及默认参数。

那么,鉴于此,这些行为(允许默认参数,或将其视为错误)中的哪一个符合 C++ 标准?

链接:

【问题讨论】:

    标签: c++ visual-c++ g++ operator-overloading default-arguments


    【解决方案1】:

    运算符函数不能有默认参数 (8.3.6),除非下面明确说明。

    (C++14标准,[over.oper]/8;C++03标准中出现了相同的句子)。

    允许默认参数的特定情况是函数调用运算符的情况(operator();参见 [over.call]/1)。在所有其他情况下,它们都是不允许的。

    【讨论】:

    • 谢谢,知道这很有用。没想到直接查标准。
    • 如果 OP 在标准模式下编译,这是一个 gcc 错误(编译器应该发出诊断)。
    • @MM 在你提到它之后,我在TutorialsPoint上用g++ -c -std=c++11 main.cppg++ -c -std=c++1y main.cppg++ -c -std=c++1y -Wall -pedantic-errors main.cpp都试过了(在线环境使用gcc version 5.3.1 20151207 (Red Hat 5.3.1-2) (GCC)),它仍然编译.不确定是否有办法强制执行更严格的标准合规性,我对 GCC 不是很熟悉。
    • operator delete 是否可以像 operator new 一样拥有像 operator delete(void*,size_t,A,B) 这样的额外参数?而我们像 delete(a,b) p 一样使用它?
    猜你喜欢
    • 1970-01-01
    • 2011-04-01
    • 2016-03-13
    • 2011-04-18
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    相关资源
    最近更新 更多