是否可以在noexcept规范中使用`this`? [英] Is `this` allowed inside a noexcept specification?
问题描述
我有一些代码要求我使用*this
,但我希望它不友好:
I have some code which requires me to use *this
, but I want it to be noexcept friendly:
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可以:
If I just access a member, gcc is fine:
void do_something(int);
struct bar {
int x;
void fn()
noexcept(noexcept(::do_something(x)))
{
::do_something(x);
}
};
但是,如果我通过this
指针访问该成员,则 gcc再次抱怨:>
However, if I access the member through the this
pointer, 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)))
我尝试过的所有其他编译器在noexcept规范内使用this
接受,但是我没有实际上知道是gcc出现了错误还是所有其他编译器.
Every other compiler I tried accepts using this
inside the noexcept specification, but I don't actually know if it's gcc that has the bug or all the other compilers.
可以在noexcept规范内使用关键字this
吗?
Can the keyword this
be used inside a noexcept specification?
推荐答案
是的,它是允许的. [expr.prim.this] p2 说:
Yes, it is allowed. [expr.prim.this]p2 says:
如果声明声明了类
X
的成员函数或成员函数模板,则表达式this
是类型为指向 cv-qualifier-seqX
的指针"的prvalue.在可选的 cv-qualifier-seq 和功能定义的末尾之间,[...].
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限定词,
The cv-qualifier-seq refers to the cv qualifiers of the member function, which 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 中使用的有效表达式.这是gcc未实现的DR( cwg1207 ). 错误报告.
So, this
is a valid expression to use in the noexcept-specifier. This was a DR (cwg1207), which gcc doesn't implement. The bug report.
这篇关于是否可以在noexcept规范中使用`this`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!