Can we refer to member variables in a noexcept specification?

旧城冷巷雨未停 提交于 2019-12-18 04:07:10

问题


Please consider the following code snippet:

template<class Tuple>
class vector
{
public:
    typename Tuple::size_type size() const noexcept(noexcept(m_elements.size())) {
        return m_elements.size();
    }

private:
    Tuple m_elements;
};

class tuple
{
public:
    using size_type = std::size_t;

    size_type size() const { return 0; }
    size_type size() noexcept { return 0; }
};    

int main()
{
    vector<tuple> x;
    static_assert(noexcept(x.size()), "x.size() might throw");

    return 0;
}

Is the use of the member variable m_elements inside the noexcept specifier legal? GCC 5.2 (C++17) yields the compiler error m_elements was not declared in this scope. while clang 3.6 (C++17) compiles without any error.

Both compilers yield no error if I use noexcept(std::declval<Tuple const&>().size()) instead. However, as you can see, I've created a simple example class tuple where it's crucial whether or not Tuple has qualified overloads of size.

From my point of view, it's more intuitive to write noexcept(m_elements.size()) cause it's exactly the call in the function body and it takes into account that the size method of vector is const qualified (which makes m_elements a const object in the scope of the function).

So, what's the legal usage? If both are equivalent, which should I use? Should I use noexcept qualifiers at all in this scenario? The problem is that whether or not the vector functions will throw depends in all most every case on Tuple.


回答1:


Clang is correct here, this is gcc bug 52869. According to [basic.scope.class], emphasis mine:

The potential scope of a name declared in a class consists not only of the declarative region following the name’s point of declaration, but also of all function bodies, default arguments, exception-specifications, and brace-or-equal-initializers of non-static data members in that class (including such things in nested classes).

The scope of m_elements includes the noexcept-specification for size().



来源:https://stackoverflow.com/questions/35872045/can-we-refer-to-member-variables-in-a-noexcept-specification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!