代码之家  ›  专栏  ›  技术社区  ›  Justin

noexcept规范中是否允许使用'this'?

  •  9
  • Justin  · 技术社区  · 7 年前

    *this ,但我希望它是友好的:

    struct foo;
    
    // Would actually be something with conditional noexcept
    void do_something(foo&);
    
    struct foo {
        void fn()
            noexcept(noexcept(::do_something(*this)))
        {
            ::do_something(*this);
        }
    };
    

    然而, gcc rejects this

    <source>:7:43: error: invalid use of 'this' at top level
             noexcept(noexcept(::do_something(*this)))
    

    如果我只访问一个成员,gcc就可以了:

    void do_something(int);
    
    struct bar {
        int x;
    
        void fn()
            noexcept(noexcept(::do_something(x)))
        {
            ::do_something(x);
        }
    };
    

    但是,如果我通过 this 指针, gcc complains again

    struct baz {
        int x;
    
        void fn()
            noexcept(noexcept(::do_something(this->x)))
        {
            ::do_something(this->x);
        }
    };
    

    诊断的:

    <source>:7:42: error: invalid use of 'this' at top level
             noexcept(noexcept(::do_something(this->x)))
    

    accepts using this inside the noexcept specification

    可以输入关键字吗 是否在无异常规范中使用?

    1 回复  |  直到 7 年前
        1
  •  10
  •   Rakete1111    7 年前

    是的,这是允许的。 [expr.prim.this]p2

    如果声明声明类的成员函数或成员函数模板 X ,表达式 this 是指针类型的prvalue cv限定符序列 在可选的 最后一刻 函数定义

    这个 cv限定符序列 引用成员函数的cv限定符 appear before the noexcept specifier :

    parameters-and-qualifiers:
        ( parameter-declaration-clause ) cv-qualifier-seq[opt] ref-qualifier[opt] 
          noexcept-specifier[opt] attribute-specifier-seq[opt]
    

    所以, 是要在中使用的有效表达式 noexcept说明符 . 这是一个医生( cwg1207 ),gcc没有实现。这个 bug report .