在noexcept 规范中是否允许使用"this"?
Is `this` allowed inside a noexcept specification?
我有一些代码需要我使用*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 没有实现。错误报告。
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- 为什么使用 "this" 指针调用派生成员函数?
- C++错误:"error: int aaa::bbb is protected within this context"
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 关于C++中具有多重继承"this"指针的说明
- 在noexcept 规范中是否允许使用"this"?
- 如何修复"error: ‘_1’ was not declared in this scope"?
- C++调用具有 *this 属性的单个帮助程序函数
- Doees the 'this' 指针参与虚函数的多态行为
- 在 c++ 中正确定义"this"关键字?
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- QObject::连接无法将信号连接到*this*对象的插槽
- 析构函数中的"delete this"
- 为什么成员函数内的"this"指针为空?
- 为什么我需要在转换构造函数上引用 this->?
- "this"指针的值在对象的生存期内是否恒定?
- C++ "Invalid use of 'this' in non-member function" ,
- 如何将'this'指针传递给C++ WinAPI 线程?