Jump to content
  • Advertisement
Sign in to follow this  
Jaiminho

Static inside a struct or global in a namespace or neither?

This topic is 3929 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

[C++]
struct LibraryLoader  // global access
{
    static bool load_library(const std::string &path) { ... }

    // et caetera
    // more static methods for getting that library's functions
};


or
struct LibraryLoader  // must have an object, but can still be created anywhere
{
    bool load_library(const std::string &path) { ... }

    // et caetera
    // more static methods for getting that library's functions
};


or
namespace LibraryLoader  // global access
{
    bool load_library(const std::string &path) { ... }

    // et caetera
    // more static methods for getting that library's functions
};


or none of the above? I am trying to avoid having to instantiate an object without any data for getting some library's functions in any part of my code, for that seems to be unecessary for this kind of thing, as in creating an empty object only for the purpouse of doing things that have no relation to any specific object.

Share this post


Link to post
Share on other sites
Advertisement
#2 is confusing to say the least.
#1 won't allow you tu use "using ..." things (right?)

#3, besides being what a namespace is for, is indeed the best option imho.

Share this post


Link to post
Share on other sites
You are correct in that if you don't need an object to perform a function ... you shouldn't have to instantiate one to perform the function. Don't use #2.

Case #3 is what you're looking for.

Case #1 is essentially equivalent to case #3 as far as the compiler is concerned. You get the "using" keyword in case #3 though, as janta said.

When you might want case #1 over #3 is when you already have a class "LibraryLoader" with members, and it makes sense to add a function coupled with the class, but which doesn't depend on any particular instance of the class.

Example:


struct foo
{
static foo* CreateNewFoo(); // This could also be non-static and in a separate namespace, but makes sense design-wise to put it in 'foo'

float ComputeSomething();
// ...

private:
float member;
// ...
};




Even if this example is not so good, hopefully it gets the point across.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!