C ++: why convert to void * before running the test

Does anyone know why the two pointers thisand &op2are first converted to void*before you compare them? (This example is taken from C ++ templates: a complete guide by David Vandevoord and Nikolai M. Josuttis)

template<typename T>
template<typename T2>
Stack<T>& operator=(const Stack<T2> & op2){
    if ((void*)this==(void*)&op2){
        return *this;
    }
    // ....
}
+4
source share
1 answer

As @KerrekSB mentioned in the comment, this is a bad coding style.

What the author is trying to do is to avoid compile-time warnings to compare pointers of different types, such as a type Stack<int>*pointer and a type pointer Stack<double>*.

It can be easily avoided by using overloads.

// Assign an object of the same type.
template<typename T>
Stack<T>& operator=(const Stack<T> & op2){
    if (this == &op2){
        return *this;
    }
    // ....
}

// Assign an object of a different type.
template<typename T>
template<typename T2>
Stack<T>& operator=(const Stack<T2> & op2){

    // For objects of different types, this check is not necessary
    // at all. It will always be false.
    // if ((void*)this==(void*)&op2){
    //     return *this;
    /// }

    // ....
}
+3
source

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


All Articles