Darth Zaloj
Darth Zaloj

Reputation: 153

C++ False Function Pointer Equivalence

So the problem I have is quite convoluted yet important. I can't tell if this is a feature of C++ or a compiler feature. But what's happening is that two different function from different classes are getting the same address:

//-- My Code --//
class A {
public:
    int myFunc() {
        return 3;
    }
};


//-- Other Code --//
namespace glm{
namespace detail
{
    template <typename T>
    GLM_FUNC_QUALIFIER typename tvec3<T>::size_type tvec3<T>::length() const
    {
        return 3;
    }

    //... Omitted
}
}

//-- Test --//
TypelessMember::Func<int> funcOverridenA = TypelessMember::func(&A::myFunc); // The original function pointer (pretending to be a member function of a "typeless" class)
auto equivalenceFunc = &glm::detail::tvec3<unsigned char>::length; // Get the false equivalence member function pointer
auto equivalence = *(TypelessMember::Func<int>*)&equivalenceFunc; // Pretend that this is a different type of function
if (equivalence == funcOverridenA) {
    puts("False function equivalence"); // This block of code is hit
    return false;
}


//-- Other test --//
A valueA = {};
TypelessMember* typelessA = typeless(&valueA);
int v = (typelessA->*funcOverridenA)(); // This calls the glm function (I guess because it was produced in the PCH first)

Obviously, I do not want a function pointer to A::myFunc to be equivalent to a function pointer to glm's length function. So what do I do? Can this be avoided somehow? I am mainly concerned because I want to be able to have two unique function pointers.

Upvotes: 0

Views: 107

Answers (1)

Bo Persson
Bo Persson

Reputation: 92261

This is a known problem with the MS compiler. When they remove "unneded" copies of functions, like instantiated templates, they look at what the function contains, not their names.

You have two functions taking no parameters and returning the value 3. They will of course generate exactly the same code. And the linker will just keep one copy, believing that nobody wants identical copies of some code.

Upvotes: 3

Related Questions