When are special member functions (in particular, copy / move constructors and copy / move assignment operators) of an instance of a template class used? As soon as an instance of the class is created, or only when they are needed?
This happens in the following situation:
template <class T, class U> struct pair { T first; U second; pair() : first(), second() {} pair(const pair&) = default; }; struct S { S() {} S(const S&) = delete; S(S&&) = default; }; int main() { pair<int, S> p; }
Clang refuses to compile this code with the following errors:
test.cpp:9:5: error: the parameter for this explicitly-defaulted copy constructor is const, but a member or base requires it to be non-const pair(const pair&) = default; ^ test.cpp:21:18: note: in instantiation of template class 'pair<int, S>' requested here pair<int, S> p; ^
assuming he is trying to instantiate the copy constructor immediately after creating the class instance.
GCC, however, compiles the code just fine, assuming that it will try to instantiate the copy constructor if it is really needed.
Which compiler behavior is correct?
(A similar mismatch is displayed for assignment operators.)
UPDATE This is because the copy constructor pair in this example is default ed, because if I changed its definition to
pair(const pair& p) : first(p.first), second(p.second) {}
then the code also goes into clang.
c ++ copy-constructor c ++ 11 templates clang
Highcommander4
source share