C ++ compiler does not detect error in class template

Consider the following example:

template <class T>
  class C
{
  public:
    C();
    C(C&& rhs);
  private:
    T m_data;
};

template <class T>
C<T>::C()
: m_data(T())
{
}

template <class T>
C<T>::C(C&& rhs)
: m_data(rhs.data)
{
}

int main()
{
    C<int> i;
}

The line : m_data(rhs.data)contains an error because it Cdoes not have a member with a name data. But none of the compilers I tried (gcc 5.2, clang 3.5.1) found this error.

But when I add the following line to the function main, the compiler detects an error:

C<int> j = std::move(i);

Why does the compiler not give an error in the first case?

Even if this particular function is not called, it can understand that it Cdoes not have a member with a name data.

Also, when I change the definition of a move constructor to the following:

template <class T>
C<T>::C(C&& rhs)
: m_data(rhs.data)
{
  data = 0;
}

the compiler gives an error in the string data = 0;, but not on : m_data(rhs.data). Thus, the function is analyzed.

+4
4

, ( , , ). ,

, id , , , -, , , ; .

C , rhs.data - , , ( , C , .. class C : T - ).

, . . , ( ) ++ 03, , . T. ++ 03 , ++ 11 , .

+5

2 .

  • ( )

, .

+8

C(C&& rhs);, ( ). ++ - , .

, .

+4

, . , .

In the general case, it is difficult to find out that there is no Tone for which the code can be compiled. If it just does not work for C<int>and C<float>, but works for C<my_class>, the compiler should not complain (until the function is used for intor float).

+3
source

Source: https://habr.com/ru/post/1605721/


All Articles