我有一些代码要求我使用 *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 expressionthis
is a prvalue of type “pointer to cv-qualifier-seqX
” 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),gcc 没有实现。 bug report .
关于c++ - noexcept 规范中是否允许使用 `this`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53120106/