[cfe-dev] noexcept and local variables

Howard Hinnant hhinnant at apple.com
Thu May 26 16:53:57 PDT 2011


Is code like this supposed to work?

template <class T>
class A
{
    T t_;
public:
    void swap(A& y) noexcept(noexcept(swap(t_, y.t_)));
};

template <class T>
void
swap(A<T>& x, A<T>& y) noexcept(noexcept(x.swap(y)));

int main()
{
    A<int> i, j;
    swap(i, j);
}

It currently gives errors:

test.cpp:6:49: error: member access into incomplete type 'A<int>'
    void swap(A& y) noexcept(noexcept(swap(t_, y.t_)));
                                                ^
test.cpp:15:12: note: in instantiation of template class 'A<int>' requested here
    A<int> i, j;
           ^
test.cpp:2:7: note: definition of 'A<int>' is not complete until the closing '}'
class A
      ^
test.cpp:11:42: error: reference to local variable 'x' declared in enclosed function 'swap'
swap(A<T>& x, A<T>& y) noexcept(noexcept(x.swap(y)));
                                         ^
test.cpp:11:1: note: in instantiation of function template specialization 'swap<int>' requested here
swap(A<T>& x, A<T>& y) noexcept(noexcept(x.swap(y)));
^
test.cpp:11:12: note: 'x' declared here
swap(A<T>& x, A<T>& y) noexcept(noexcept(x.swap(y)));
           ^
2 errors generated.


I haven't looked at the language side to see if it is supposed to work.  But there's library specs that implies it should work.  I wouldn't be surprised if the library guys (myself included) just didn't understand the language.  And if it isn't supposed to work, I can work around it easily enough.

Here's another variation that works around the first error, but the second remains:

#include <type_traits>

using std::swap;

template <class T>
class A
{
    T t_;
public:
    void swap(A& y) noexcept(noexcept(swap(std::declval<T&>(),
                                           std::declval<T&>())));
};

template <class T>
void
swap(A<T>& x, A<T>& y) noexcept(noexcept(x.swap(y)));

int main()
{
    A<int> i, j;
    swap(i, j);
}

test.cpp:16:42: error: reference to local variable 'x' declared in enclosed function 'swap'
swap(A<T>& x, A<T>& y) noexcept(noexcept(x.swap(y)));
                                         ^
test.cpp:16:1: note: in instantiation of function template specialization 'swap<int>' requested here
swap(A<T>& x, A<T>& y) noexcept(noexcept(x.swap(y)));
^
test.cpp:16:12: note: 'x' declared here
swap(A<T>& x, A<T>& y) noexcept(noexcept(x.swap(y)));
           ^
1 error generated.


Just wanted to check here first in case it was a bug.

Howard




More information about the cfe-dev mailing list