Singleton implementation: Is a namespace approach often preferable over a singleton class? - c++

(This questions assumes that a global + unique object is the goal. I would like to clarify that this does not mean it is asking about or advocating the if/why/when of using/not-using singletons or globals.)
I am wondering if there's a technicality about C++ that I'm missing, so my question is:
Is a namespace implementation of the singleton pattern in C++ valid? And if so, is there a reason why it is not often suggested as the better approach?
From Google's style guidelines, we see namespace non-member functions recommended over static member function, but only when not sharing static data:
"Rather than creating classes only to group static member functions
which do not share static data, use namespaces instead."
Why shy away from letting non-member functions share static data, declared in an unnamed namespace? Is there something wrong about this that explains why namespaces aren't generally suggested as a better alternative to writing a singleton class in C++?
Because I can't find recommendations of the namespace approach, but it is very easy to find the class approach despite C++ not enforcing the use of classes:
C++ Singleton design pattern
Can any one provide me a sample of Singleton in c++?
Singleton instance declared as static variable of GetInstance method
http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
Singleton: How should it be used
Using a named namespace with an unnamed namespace in its source file:
You can have 'state' via static data
You can gain the extra privacy of putting things in an unnamed namespace
You can still control the construction order of its static objects by using static pointers, and constructing from function calls.
You don't need to implement a singleton class
Edit - Example of namespace approach I was thinking:
SingleThing.h:
namespace single_thing // The singleton (if this is actually valid)
{
void GrowSomeCats(int amount); // Typical setter
int GetNumCats(); // Typical getter
}
SingleThing.cpp:
#include "Balloon.h"
namespace // Acting like private members and functions
{
int numCats = 4; // POD
Balloon* wilson = NULL; // Not POD (and not a singleton)
// Contrived 'private' function
bool CanGrowCats()
{ return wilson && wilson->LikesCats(); }
// Contrived excuse to instantiate non-POD 'members'
void RandomlyCreateOtherObjects()
{
if (!wilson /* && someRandomiserImTooLazyToType()*/ )
wilson = new Balloon();
}
}
namespace single_thing // 'Public' functions
{
void GrowSomeCats(int amount)
{
RandomlyCreateOtherObjects();
if (CanGrowCats())
numCats += amount;
}
GetNumCats()
{ return numCats; }
}

(I assume we can agree that global state is a dangerous thing that has to be used with special care.)
Technically your singleton namespace is equivalent to a singleton class. However it has one major drawback that makes it a no-go in my opinion: It hides the fact that it is stateful. Ever used std::strtok()? Remember what an atrocious mess it is? That’s because it hides its statefulness, too.
Because global state is inherently dangerous, any piece of functionality that uses it should make that fact abundantly clear at the call site, preferrably by using language constructs – because nobody reads comments or documentation. A Foo::instance()->do_work(); is a known pattern that makes it quite clear that something special is going on; a foo::do_work(); does not.

Singleton design pattern is about creation the only instance of a useful class (there is no need in creation of useless objects). In C++ classes are defined with class and struct keywords. To be useful a singleton class, beside creation and destruction, should also implement some methods that operate with the instance. To ensure singularity, a singleton class should hide its constructors and expose a static method for accessing the instance.
Using only namespaces one would not be able to define useful methods of the singleton. Implementing the instance access method as a function in a namespace instead of the class itself is possible, but would require 'friending' that function, and does not make sense because the class is already defined.
Implementing a non-object singleton (e.g. of a plain data type) would assume that the instance does not require construction and thus there is no need for singleton.

Related

A c++ class include a static member with the same type of itself. Why this pattern?

I inherited a project from a former colleague, and I found these code snippets (and some similar ones in SO questions: can a c++ class include itself as an member and static member object of a class in the same class)
// Service.h
class Service
{
// ...
public:
static Service sInstance;
void Somememberfunc();
//...
};
// Service.cpp
#include "Service.h"
Service Service::sInstance;
void Service::Somememberfunc()
{
//...
}
// Main.cpp
#include "Service.h"
void Fun()
{
Service &instance = Service::sInstance;
//...
instance.Somememberfunc();
//...
}
However, I did not find any explanation on when to use this pattern. And what are the advantages and disadvantages?
Notice that the member is a static, so it's part of the class, not of instantiated objects. This is important, because otherwise you would be trying to make a recursive member (since the member is part of the object, it also contains the same member and so on...), but this is not the case here.
The best pattern to describe this is: global variable. The static member is initialized before main() and can be accessed from any part of the program by including the header file. This is very convenient while implementing but becomes harder to handle the more complex the program gets and the longer you have to maintain it, so the general idea is to avoid this. Also, because there is no way to control the order of initialization, dependencies between different global variables can cause problems during startup.
Static member is roughly a global variable in the scope of the class.
Static members have also the advantage of visibility access (public/protected/private) to restreint its usage (file scope might be an alternative).
That member might be of type of the class.
Global are "easy" to (mis)use, as they don't require to think about architecture.
BUT (mutable) global are mostly discouraged as harder to reason about.
Acceptable usages IMO are for constants:
as for a matrix class, the null matrix, the diagonal one matrix.
for Temperature class, some specific value (absolute 0 (O Kelvin), temperature of water transformation(0 Celsius, 100 Celsius), ...)
in general NullObject, Default, ...
Singleton pattern. For example, you can use it to store your app configurations. And then you can easily access configurations anywhere(globally) within your app.
This is often used in the singleton design pattern
Visit https://en.wikipedia.org/wiki/Singleton_pattern

Free functions vs singleton vs static class members [duplicate]

I already read a lot of posts and articles all over the net, but I couldn't find a definite answer about this.
I have some functions with similar purposes that I want to have out of the global scope. Some of them need to be public, others should be private (because they are only helper functions for the "public" ones).
Additionally, I don't have only functions, but also variables. They are only needed by the "private" helper functions and should be private, too.
Now there are the three ways:
making a class with everything being static (contra: potential "Cannot call member function without object" - not everything needs to be static)
making a singleton class (contra: I WILL need the object)
making a namespace (no private keyword - why should I put it in a namespace at all, then?)
What would be the way to take for me? Possible way of combining some of these ways?
I thought of something like:
making a singleton, the static functions use the helper function of the singleton object (is this possible? I'm still within the class, but accessing an object of it's type)
constructor called at programm start, initializes everything (-> making sure the statics can access the functions from the singleton object)
access the public functions only through MyClass::PublicStaticFunction()
Thanks.
As noted, using global variables is generally bad engineering practice, unless absolutely needed of course (mapping hardware for example, but that doesn't happen THAT often).
Stashing everything in a class is something you would do in a Java-like language, but in C++ you don't have to, and in fact using namespaces here is a superior alternative, if only:
because people won't suddenly build instances of your objects: to what end ?
because no introspection information (RTTI) is generated for namespaces
Here is a typical implementation:
// foo.h
#ifndef MYPROJECT_FOO_H_INCLUDED
#define MYPROJECT_FOO_H_INCLUDED
namespace myproject {
void foo();
void foomore();
}
#endif // MYPROJECT_FOO_H_INCLUDED
// foo.cpp
#include "myproject/foo.h"
namespace myproject {
namespace {
typedef XXXX MyHelperType;
void bar(MyHelperType& helper);
} // anonymous
void foo() {
MyHelperType helper = /**/;
bar(helper);
}
void foomore() {
MyHelperType helper = /**/;
bar(helper);
bar(helper);
}
} // myproject
The anonymous namespace neatly tucked in a source file is an enhanced private section: not only the client cannot use what's inside, but he does not even see it at all (since it's in the source file) and thus do not depend on it (which has definite ABI and compile-time advantages!)
Don't make it a singleton
For public helper functions that don't directly depend on these variables, make them non-member functions. There's nothing gained by putting them in a class.
For the rest, put it in a class as normal non-static members. If you need a single globally accessible instance of the class, then create one (but don't make it a singleton, just a global).
Otherwise, instantiate it when needed.
The classic C way of doing this, which seems to be what you want, is to put the public function declarations in a header file, and all the implementation in source file, making the variables and non-public functions static. Otherwise just implement it as a class - I think you are making a bit of a mountain out of a molehill here.
What about using a keyword static at global scope (making stuff local to the file) as a privacy substitute?
From your description it looks like you have methods and data that interact with each other here, in other words it sounds to me like you actually want a non-singleton class to maintain the state and offer operations upon that state. Expose your public functions as the interface and keep everything else private.
Then you can create instance(s) as needed, you don't have to worry about init order or threading issues (if you have one per thread), and only clients that need access will have an object to operate upon. If you really need just one of these for the entire program you could get away say a global pointer that's set in main or possibly an instance method, but those come with their own sets of problems.
Remember that the singleton instance of a singleton class is a valid instance, so it is perfectly able to be the recipient of nonstatic member functions. If you expose your singleton factory as a static function then have all of your public functionality as public nonstatic member functions and your private functionality as private nonstatic member functions, anyone that can get at the class can access the public functionality by simply invoking the singleton factory function.
You don't describe whether all of the functionality you're trying to wrap up is as related as to justify being in the same class, but if it is, this approach might work.
If you take a "C-like" approach and just use top-level functions, you can make them private by declaring them in the .cpp file rather than the publicly-included .h file. You should also make them static (or use an anonymous namespace) if you take that approach.

Using a namespace in place of a static class in C++?

Is it good or okay practice to use a namespace as a static class? For example:
namespace MyStaticFunctions {
void doSomething();
}
Versus:
class MyStaticFunctions {
static void doSomething();
}
There's no such thing as a "static class" in C++, so from a C++ point of view you're not using it "as a static class", you're using it "as a namespace". It's certainly accepted practice to use namespaces to group functions together.
It's up to you, though, how big you want the groups to be. It's not unusual for C++ libraries to use a single namespace for the whole public interface. That might come as a surprise to someone who is used to (say) Java, where classes are often used to group together smaller numbers of static methods. Since C++ was here first, you could say that Java is using classes as namespaces.
So, in C++ you don't tend to see classes similar to java.util.Collections or java.lang.Math, full of static members. If you want groups of functions like that in C++, use namespaces.
The exception (isn't there always a special case in C++?) is traits types like std::numeric_limits<T>, where the template parameter makes the class do something that a namespace can't do. You could define a namespace numeric_limits containing function templates max<T>(), min<T>() etc, but it's not as good. Firstly, it groups things slightly differently, the type T appears "lower down the hierarchy". Secondly it doesn't do everything that a traits type does, because there's no such thing as an "object template" that would let you define a value numeric_limits::digits<T>.
I don't know C# well enough to comment on the practical uses of static classes there, but AFAIK it's just a class restricted to having no non-static members, so it's analogous to those Java classes.
In C++, you are actually encouraged at the language level to use a namespace rather than a class containing only static methods because of Koenig's lookup (aka Argument Dependent Lookup).
Example:
namespace geometry {
struct Point { int x, y; };
double distance_from_center(Point const& p) {
return sqrt(p.x * p.x + p.y + p.y);
}
} // namespace geometry
int main() {
geometry::Point const p{3, 4}; // must qualify
std::cout << distance_from_center(p) << "\n"; // not qualified
}
If distance_from_center is written as a static method in a class, then you need to explicitly qualify it each time.
It's a tough and interesting question for me personally, so decided to share my humble opinion
Considering the difference between "static" class (only static members) and namespace:
a namespace can be scattered over multiple files: additional flexibility but should be used carefully.
a namespace provides argument dependent lookup (see Matthieu M. answer): useful in specific situations
a "static" class can have access modifiers and can form an hierarchy: I think private members declared in class interface and visible to its clients is a C++ feature that was dictated more by technical, not logical reasons. I don't see any benefits of private static members. Protected members for "static" hierarchy? Never seen any.
a "static" class can be a "template", in addition to template members: see Steve Jessop's answer for a great example from STL
From maintenance point of view, sometimes you decide to make a class "static" (like a singleton), but then requirement changed and you need multiple instances. "Static" class would be easier to transform than namespace.
And, finally, to answer your question:
if you don't need special features of "static" class or namespace, use what you like more :)
It depends.
Is the method logically related to a class? If so, make it a member, otherwise place it in a namespace.
Functionally, they're the same, but there's more to code than function, right? For example, consider a method that returns the name of the class:
struct MyClass
{
static std::string getName() { return "MyClass"; }
}
You could obviously place the method outside, in a namespace, and get the same result, but it logically belongs to the class.

c++ when to put method out side the class

i saw that some times in c++ applications using only namespace declarations with header and source file like this :
#ifndef _UT_
#define _UT_
#include <string>
#include <windows.h>
namespace UT
{
void setRootPath(char* program_path, char* file_path);
char * ConvertStringToCharP(std::string str);
};
#endif
//and then in UT.cpp
#include "UT.h"
namespace UT
{
char * ConvertStringToCharP(std::string str)
{
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0';
return writable;
}
void setRootPath(char* program_path, char* file_path)
{
//...
}
}
is it better then defining classic class with static methods?
or just simple class ?
dose this method has something better for the compiler linker ?
the methods in this namespace are called allot of times .
By shear coincidence I happen to read this answer for a slightly different question in Stack Overflow. In that the user rhalbersma had given a nice link to a Dr Dobb's article where the author Scott Meyers explains how methods implemented outside the class (non-friend methods), but inside the same namespace actually improve encapsulation. For me it was a good learning for today. Hope this helps you as well.
Performance-wise, there's no difference between having static class members and free functions in a namespace. It's a matter of logic though. Are your functions related to the class or not?
A good question to ask yourself - are you creating the static member functions inside the class just for better organization (or just so you can group them together)? If the answer is yes, you should probably use a namespace.
You put a method outside all classes when the method's meaning is independent of a class. Static classes in other languages (Java, C#) are a way to compensate for inability to put methods outside classes. Since C++ provides this ability out of the box through namespaces, the use of an additional "static class" would be counterintuitive to the readers of your code.
The primary reasons for using a static class member function is a logical and conceptual relation to the class and its members.
Another reason may be to enable template partial specialisation, which is not allowed for function templates, but for classes.
Otherwise, use a standalone function (defined in an appropriate namespace).
There's no absolute rule, but in general, unless the functions show a
very large degree of coherence, and you want to close the "namespace"
for some reason, so clients can't add functions to it, using namespace
is generally preferable to using class. Unless, of course, the intent
is to make them available to templates: you can instantiate a template
on a class, but not on a namespace. (This technique is often called
"traits"; a class with no non-static members is called a traits class.)
Even if you do use namespaces, you should define the functions:
void UT::setRootPath( char const* programPath, char const* filePath)
{
// ...
}
char* UT::convertStringToCharP( std::string const& str )
{
// ...
}
This way, any typos in the signature of the function will be detected by
the compiler.
By default you should always try to minimise the methods on a class. If you can implement functionality in terms of the class rather than within a class you should. In other words if you can achieve the desired functionality through using the already published public interface then you should. This vastly reduces the dependency of your code on implementation details.
So if you can then implement it outside of the class in an appropriate namespace that naturally seems related to the class.
EDIT: It appears that the OP is really asking about whether to implement a namespace or a static class as a holder object for utility/related functions. In my opinion namespaces are the correct way to do this, because that is what they are there for. A class is not necessary.

C++, static vs. namespace vs. singleton

I already read a lot of posts and articles all over the net, but I couldn't find a definite answer about this.
I have some functions with similar purposes that I want to have out of the global scope. Some of them need to be public, others should be private (because they are only helper functions for the "public" ones).
Additionally, I don't have only functions, but also variables. They are only needed by the "private" helper functions and should be private, too.
Now there are the three ways:
making a class with everything being static (contra: potential "Cannot call member function without object" - not everything needs to be static)
making a singleton class (contra: I WILL need the object)
making a namespace (no private keyword - why should I put it in a namespace at all, then?)
What would be the way to take for me? Possible way of combining some of these ways?
I thought of something like:
making a singleton, the static functions use the helper function of the singleton object (is this possible? I'm still within the class, but accessing an object of it's type)
constructor called at programm start, initializes everything (-> making sure the statics can access the functions from the singleton object)
access the public functions only through MyClass::PublicStaticFunction()
Thanks.
As noted, using global variables is generally bad engineering practice, unless absolutely needed of course (mapping hardware for example, but that doesn't happen THAT often).
Stashing everything in a class is something you would do in a Java-like language, but in C++ you don't have to, and in fact using namespaces here is a superior alternative, if only:
because people won't suddenly build instances of your objects: to what end ?
because no introspection information (RTTI) is generated for namespaces
Here is a typical implementation:
// foo.h
#ifndef MYPROJECT_FOO_H_INCLUDED
#define MYPROJECT_FOO_H_INCLUDED
namespace myproject {
void foo();
void foomore();
}
#endif // MYPROJECT_FOO_H_INCLUDED
// foo.cpp
#include "myproject/foo.h"
namespace myproject {
namespace {
typedef XXXX MyHelperType;
void bar(MyHelperType& helper);
} // anonymous
void foo() {
MyHelperType helper = /**/;
bar(helper);
}
void foomore() {
MyHelperType helper = /**/;
bar(helper);
bar(helper);
}
} // myproject
The anonymous namespace neatly tucked in a source file is an enhanced private section: not only the client cannot use what's inside, but he does not even see it at all (since it's in the source file) and thus do not depend on it (which has definite ABI and compile-time advantages!)
Don't make it a singleton
For public helper functions that don't directly depend on these variables, make them non-member functions. There's nothing gained by putting them in a class.
For the rest, put it in a class as normal non-static members. If you need a single globally accessible instance of the class, then create one (but don't make it a singleton, just a global).
Otherwise, instantiate it when needed.
The classic C way of doing this, which seems to be what you want, is to put the public function declarations in a header file, and all the implementation in source file, making the variables and non-public functions static. Otherwise just implement it as a class - I think you are making a bit of a mountain out of a molehill here.
What about using a keyword static at global scope (making stuff local to the file) as a privacy substitute?
From your description it looks like you have methods and data that interact with each other here, in other words it sounds to me like you actually want a non-singleton class to maintain the state and offer operations upon that state. Expose your public functions as the interface and keep everything else private.
Then you can create instance(s) as needed, you don't have to worry about init order or threading issues (if you have one per thread), and only clients that need access will have an object to operate upon. If you really need just one of these for the entire program you could get away say a global pointer that's set in main or possibly an instance method, but those come with their own sets of problems.
Remember that the singleton instance of a singleton class is a valid instance, so it is perfectly able to be the recipient of nonstatic member functions. If you expose your singleton factory as a static function then have all of your public functionality as public nonstatic member functions and your private functionality as private nonstatic member functions, anyone that can get at the class can access the public functionality by simply invoking the singleton factory function.
You don't describe whether all of the functionality you're trying to wrap up is as related as to justify being in the same class, but if it is, this approach might work.
If you take a "C-like" approach and just use top-level functions, you can make them private by declaring them in the .cpp file rather than the publicly-included .h file. You should also make them static (or use an anonymous namespace) if you take that approach.