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

Is `this` allowed inside a noexcept specification?

本文关键字:quot this 许使用 noexcept 范中 是否      更新时间:2023-10-16

我有一些代码需要我使用*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拒绝了这一点:

<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 会再次抱怨:

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)))

我尝试过的所有其他编译器都接受在 noexcept 规范中使用this,但我实际上不知道是 gcc 有错误还是所有其他编译器。

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

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

如果声明声明了类X的成员函数或成员函数模板,则表达式this是可选的cv-限定符-seq函数定义末尾 [...] 之间的类型为 "指向cv-qualifier-seqX的指针" 的 prvalue。

cv-qualifier-seq是指成员函数的 cv 限定符,它们出现在 noexcept 说明符之前:

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(,gcc 没有实现。错误报告。