【问题标题】:Make ++o++ complain for types with user defined pre- and postfix increment operators使 ++o++ 抱怨具有用户定义的前置和后置增量运算符的类型
【发布时间】:2021-06-21 15:19:12
【问题描述】:

我正在寻找一种方法来阻止 ++x++ 处理具有用户定义的前缀和后缀增量运算符的类型。

对于内置类型,后缀运算符的结果类型不是左值而是纯右值表达式,编译器会抱怨。

我能想到的最简单的事情是为后缀增量运算符返回 const:

struct S {
    int i_;
    S& operator++() {
        ++i_;
        return *this;
    }
    S /*const*/ operator++(int) {
        S result(*this);
        ++(*this);
        return result;
    }
};
int main() {
    S s2{0};
    ++s2++;
}

Here's a godbolt.

这种方法有缺陷吗?

编辑:

感谢答案,我找到了更多信息herehere,当然还有cppreference

【问题讨论】:

  • 按值返回 const 类通常是有缺陷的 - 它禁止从这些值移动。 (并且在由值返回的非类类型上,常量被完全忽略。)

标签: c++ post-increment prvalue least-astonishment


【解决方案1】:

您可能想要S& operator++() &S operator++(int) &。您最后缺少了&,这使得运算符仅适用于左值。

【讨论】:

    【解决方案2】:

    您希望前缀 ++ 运算符仅适用于左值。

    此语法从 C++11 开始有效。

    S& operator++() & {
    //              ^ This & allows only lvalues for *this
        ++i_;
        return *this;
    }
    

    Here's a godbolt.

    【讨论】:

    • 我接受了 Mooing Ducks 的回答,因为他的回答要快一些,并提到将 & 应用于前置和后缀增量运算符。另一方面,我喜欢在您的回答中额外提及历史。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 2016-02-02
    • 2012-03-07
    • 2023-04-09
    • 2012-07-11
    相关资源
    最近更新 更多