Consider this copy constructor of a template class which has an error:
MyClass( MyClass const& other )
: m_x( other.n_x ) // typo: should be `other.m_x`.
{
// does something
}
Or this copy assignment operator overload which does not return anything (return-type
warning):
MyClass& operator=( MyClass const& other )
{
// does something
// WARNING: with no `return *this`.
}
It has happened several times that GCC compiles the code without any error/warning at first, and later after some changes on other parts of the code, it complains about an issue that it was already there (mostly in constructors or assignment operators as far as I remember).
Does GCC ignores template functions or member function of a template class that are not instantiated throughout the code completely? What is happening under the hood?
I am using GCC 9.3 and GCC 10.1 with -O3 -Wall -Wpedantic -Werror
.
UPDATE As @someprogrammerdude suggested, here is a minimal reproducible example:
template< typename T >
class MyClass {
public:
MyClass( T x ) : m_x( x ) { };
MyClass( MyClass const& other )
: m_x( other.n_x )
{
std::cout << "in copy constructor" << std::endl;
}
MyClass& operator=( MyClass const& other )
{
this->m_x = other.m_x;
}
T m_x;
};
and here is the sample usage which compiles fine as is. But uncommenting some parts gives an error or warning.
int main()
{
MyClass< int > c( 2 );
std::cout << c.m_x << std::endl;
/* Uncommenting these lines gives an error in constructor.
* error: ‘const class MyClass<int>’ has no member named ‘n_x’*/
//MyClass< int > d = c;
//std::cout << d.m_x << std::endl;
/* Uncommenting these lines gives a warning in copy assignment operator.
* error: no return statement in function returning non-void [-Werror=return-type] */
//MyClass< int > d( 3 );
//d = c;
//std::cout << d.m_x << std::endl;
return 0;
}
It is clearer to me now when I created this example. So, there would be no check at all if it is not instantiated?