Jump to content

  • Log In with Google      Sign In   
  • Create Account

14 years ago on June 15th Gamedev.net was first launched! We want to thank all of you for being part of our community and hope the best years are ahead of us. Happy birthday Gamedev.net!

#ActualMrOMGWTF

Posted 20 October 2012 - 06:09 AM

A value type will never act polymorphically, its type is set in stone at compile time. Only through using a pointer or reference can a given piece of code be passed different types at runtime.

You can expose the value as a reference too, which is slightly safer:

// Renderer.h

Renderer &getGlobalRenderer();

// Main.cpp

namespace {
    Renderer *globalRenderer = 0;
}

Renderer &getGlobalRenderer() {
    assert(globalRenderer);
    return *globalRenderer;
}

int main() {
    Renderer renderer;
    globalRenderer = &renderer;

    // Rest of program

    globalRenderer = 0;
}
This mechanism allows you to hide the dangerous raw pointer in main(), but yet still expose the global value. Note that this approach avoids dynamically allocating the renderer - but doesn't prevent you from doing so either. This also simplifies cleanup - the renderer will naturally be destroyed at the end of main(), or if you return early, or if an exception is thrown.


Damn, I'll use it in my code, it's a nice way for allocating important global variables :D
I should re-read my C++ book...
Thanks for the help

#1MrOMGWTF

Posted 20 October 2012 - 06:08 AM

A value type will never act polymorphically, its type is set in stone at compile time. Only through using a pointer or reference can a given piece of code be passed different types at runtime.

You can expose the value as a reference too, which is slightly safer:

// Renderer.h

Renderer &getGlobalRenderer();

// Main.cpp

namespace {
    Renderer *globalRenderer = 0;
}

Renderer &getGlobalRenderer() {
    assert(globalRenderer);
    return *globalRenderer;
}

int main() {
    Renderer renderer;
    globalRenderer = &renderer;

    // Rest of program

    globalRenderer = 0;
}
This mechanism allows you to hide the dangerous raw pointer in main(), but yet still expose the global value. Note that this approach avoids dynamically allocating the renderer - but doesn't prevent you from doing so either. This also simplifies cleanup - the renderer will naturally be destroyed at the end of main(), or if you return early, or if an exception is thrown.


Damn, I'll use it in my code, it's a nice way for allocating important global variables :D
I should re-read my C++ book...

PARTNERS