Search code examples
c++visual-c++runtime-erroraccess-violationcompiler-bug

Access violation when calling a function using a global reference


I was testing for multiples ways of storing and using a function reference for a function named foo.

#include <iostream>

using Function = void (&)(void); // Reference to Function

void foo(void)
{
    std::cout << "Foo called succesfully" << std::endl;
}

Firstly, I tried to store a direct reference to foo inside a static member of a Holder class:

class Holder {
public:
    static const Function class_foo;
};

Function Holder::class_foo = foo;

Secondly, I tried to store a direct reference to foo in a global variable:

Function global_foo1 = foo;

Thirdly, I tried to store a reference to its static reference in the Holder class:

const Function& global_foo2 = Holder::class_foo;

Fourthly, I tried to store a copy of its static reference in the Holder class:

Function global_foo3 = Holder::class_foo;

An access violation exception occurs when trying to execute foo using the 3rd (global_foo2) and 4th (global_foo3) cases.

int main(void)
{
    const Function& local_foo = Holder::class_foo;

    local_foo(); // Executes Properly

    Holder::class_foo(); // Executes Properly

    global_foo1(); // Executes Properly

    global_foo2(); // Throws Exception -> Access Violation when Executing

    global_foo3(); // Throws Exception -> Access Violation when Executing

    return 0;
}

Any idea of what I did wrong? Probably because of my lack of knowledge about compilation steps.

Obs: The full code can be executed by just copying each block of code sequentially. My compiler was Microsoft Visual Studio 15.5.2. Also tried the latest version 15.5.6. Still not working in version 15.9.4. Exception proof is here or here.


Solution

  • The code compiles and executes properly using GCC. It must either be a MSVC compiler bug or bad compiler configuration.