c++ - noexcept 规范中是否允许使用 `this`?

标签 c++ this language-lawyer noexcept

我有一些代码要求我使用 *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),gcc 没有实现。 bug report .

关于c++ - noexcept 规范中是否允许使用 `this`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53120106/

相关文章:

c++ - 在 windows shell 命名空间扩展下使用 _wopen()

c++ - const 引用的正确语法

c++ - recursive_mutex 的最大所有权级别的下限?

c++ - 为什么 double 可转换为看似任何原始类型的 const 引用?

c++ - 使用 C++ 在 Windows 寄存器中插入值

c++ - 使用 switch 语句进行范围检查

c++ - 使用 C++ 在 Linux 中创建定时器队列

方法调用模式中的 Javascript "this"指针未指向对象

jquery - 如何将 'this' jquery 选择器与 Angular 2 一起使用

javascript - 即使使用箭头函数,React 也无法读取 .then() 中未定义的属性 setState