在 noexcept 规范中是否允许“this”?

Is `this` allowed inside a noexcept specification?

我有一些代码需要我使用 *this,但我希望它是 noexcept 友好的:

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,但我实际上不知道是 gcc 有错误还是所有其他编译器。

可以在 noexcept 规范中使用关键字 this 吗?

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

If a declaration declares a member function or member function template of a class X, the expression this is a prvalue of type “pointer to cv-qualifier-seq X” between the optional cv-qualifier-seq and the end of the function-definition, [...].

cv-qualifier-seq指的是成员函数的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]

因此,this 是在 noexcept-specifier 中使用的有效表达式。这是一个 DR (cwg1207), which gcc doesn't implement. The bug report.