c++ singleton initialization order - c++

I have
class Foo
class Bar
Now, I want
Foo* Foo::singleton = new Foo();
Bar* Bar::singleton = new Bar();
to both initialize before
int main()
is called.
Furthermore, I want
Foo::singleton
to initialize before
Bar::singleton
Is there anyway I can ensure that?
Thanks!

Global variables (like the singletons) that are defined in the same translation unit are initialized in the order in which they are defined. So put the definition of both singletons in the same source file, in the correct order.
If they would be defined in different source files the order in which they are initialized would be unspecified (the "static initialization order fiasco").

See also Static variables initialisation order
For gcc use init_priority:
http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
Works across different translation units. So your code would read:
Foo* Foo::singleton __attribute__ ((init_priority (2000))) = new Foo();
Bar* Bar::singleton __attribute__ ((init_priority (3000))) = new Bar();
I don't have gcc handy right now so I can't verify this, but I have used it before.
The other simpler and more portable solution is to avoid static initialization, and explicitly create the singletons in order at some well defined place within main.
// Nothing in static area
void main(void)
{
// Init singletons in explicit order
{
Foo* Foo::singleton = new Foo();
Bar* Bar::singleton = new Bar();
}
// Start program execution
...
}
Remember, things will get just as gnarly with singletons on the way out of the program as well, so its often better to make it explicit.

#include <iostream>
class Foo {
public:
static Foo *singleton ()
{
if (foo == NULL)
foo = new Foo;
return foo;
}
private:
Foo ()
{
std::cout << "Foo()\n";
}
static Foo *foo;
};
Foo *Foo::foo = NULL;
Foo *singleton = Foo::singleton ();
int
main ()
{
std::cout << "main()\n";
return 0;
}
Output:
Foo()
main()

In a nutshell:
// smooth.cpp
#include "foo.h"
#include "bar.h"
Foo* Foo::singleton = new Foo();
Bar* Bar::singleton = new Bar();
A nice syntax, to avoid worrying about that:
Foo& Foo::singleton()
{
static Foo Singleton;
return Singleton;
}
The good thing about this syntax, is that the singleton is initialized at the first call of the method, thus you don't have to worry (usually) when it happens, since when calling the method to access it you get it anyway :)

Related

Calling static methods in constructor

This seems a bit strange to me. Since a static method can have an instance of the class, one naturally expects that the compiler should not allow calling static methods inside the constructor. But I have tested the following code with every compiler and ironically, none of them gave me a single warning. Although in execution time they all throw exceptions. Am I missing something here?
#include <iostream>
class Foo
{
public:
inline Foo()
{
std::cout << "testing: var = " << bar() - 1 << '\n';
}
~Foo(){}
static int bar()
{
Foo f;
f.var = 10;
return f.test();
}
private:
int var;
int test()
{
return var + 1;
}
};
int main()
{
Foo foo;
return 0;
}
Live example
It is not illegal to call static functions from within the constructor. Only, you are getting a stack overflow, if you do it like you do. This results in
Foo() calls bar();
bar() calls Foo();
Foo() calls bar();
bar() calls Foo();
...
Until no stack is left.
This is exactly the same as if you had:
void f1();
void f2()
{
f1();
}
void f1()
{
f2();
}
int main(int, char*[])
{
f1();
return 0;
}
Only two global functions, nothing more. Would have been all the same in C, too (but you have do declare void f(void) there), or Java, C#, perl, python, ...
What warnings are you expecting? What you've written is an infinite recursion which has nothing to do with static member functions. You can do it with any other function inside or outside a class.
Static functions are not much different from the free ones. So free functions should also be banned from constructor? There is no point in forbidding to call static functions from constructors.
There is no reason not to call a static (or in fact a non-static) member function in a constructor (although it is not recommended to call virtual functions).

C++ Equivalent of C# Static Class

So in C# when I wanted to make globally available functions/variables, I would make a static class...
// SomeClass.cs
public static class SomeClass
{
private static int bar;
public static int Foo()
{
return bar;
}
}
And if I wanted to do the same in C++, is this basically the same thing?
// SomeClass.h
class SomeClass
{
private:
int bar;
public:
SomeClass();
~SomeClass();
int foo();
};
extern SomeClass gSomeClass;
And in...
// SomeClass.cpp
#include "SomeClass.h"
SomeClass gSomeClass;
SomeClass::SomeClass()
{
bar = 0;
//....
}
SomeClass::~SomeClass()
{
//....
}
int SomeClass::foo()
{
return bar;
}
And in...
#include "SomeClass.h"
int main()
{
return gSomeClass.foo();
// (basically)
}
Would there be any problems with doing this?
It looks like you need a free function. These functions are not implemented in a class, usually they are preferred to be implemented in a namespace.
The status variable can be implemented in an anonymous namespace or as an extern of some sort. A function local static could also be used.
This will vary on how you wish to expose the data associated with the variable, the extern seems most likely in this case.
Sounds like you're trying to implement the singleton pattern. There is much debate as to when this pattern should be used due to the general sentiment that "global variables are bad", but it has its legitimate use-cases in my opinion. The keyword "singleton" should be more than enough to allow you research various C++ implementations of the pattern and find many discussions on the pros and cons of using it.
This class is analogous to your C#:
// SomeClass.h
class SomeClass
{
private:
static int bar;
SomeClass(); // not to be instantiated
public:
static int foo() { return bar; };
};
You can use it like that:
int x = SomeClass::foo();
This is generally how you could do it:
SomeClass.h
class SomeClass
{
static int bar;
public:
static int Foo()
{
return bar;
}
};
SomeClass.cpp
#include "SomeClass.h"
int SomeClass::bar = 0;
This has not been a common pattern in my experience though. Free functions tend to be preferable. Variables and functions don't have to be members of a class in sane languages like C++.
I think an equivalent will look like:
class MyTest
{
public:
static void Test()
{
std::cout << "Test" << std::endl;
}
};
MyTest::Test();

How to wrap another class (c++)

I'm trying to learn to c++ after programming in other OO languages for many years.
I'm trying to create a wrapper class for another class, but having a hard time figuring out how to set this up properly.
For instance, with the following...
main.cpp
#include "foo.cpp"
#include <iostream>
int main() {
Foo foo(42);
std::cout << foo.get_barx() << std::endl;
return 0;
}
foo.cpp
#include "bar.cpp"
class Foo {
public:
// I'm trying to declare the member variable `m_bar` here. I
// don't want to be instantiating an instance of Bar yet,
// but I think that might be exactly what's happening.
Bar m_bar;
Foo(int y) {
// Here's where I really want to instantiate an instance of Bar
// and assign it to m_bar.
Bar m_bar(y*2);
}
int get_barx() {
return m_bar.getx();
}
};
bar.cpp
class Bar {
public:
int m_x;
// I seem to need this default constructor for the declaration
// of `m_bar` above, but I don't think that line should be
// calling any constructors.
Bar() { m_x = 21; };
Bar(int x) {
m_x = x;
}
int getx() {
return m_x;
}
};
When I compile and run this, I get back 21, but I expect 84. I'm pretty sure I'm doing something fundamentally wrong, and I'm pretty sure it's got something to do with how I'm declaring the m_bar member variable in Foo, but I can't figure out what the right way is to accomplish this.
main.cpp
#include "foo.cpp"
#include <iostream>
int main()
{
Foo foo(42);
std::cout << foo.get_barx() << std::endl;
return 0;
}
Here you should be including a header (e.g., rename "foo.cpp" to "foo.h"). In general, the header provides the declaration and the source (e.g., .cpp file) provides the definition/implementation.
Bar.cpp (again this should be a header)
class Bar
{
public:
int m_x;
// A default constructor is not required, however defining any constructor
// prevents auto generation of the default constructor
Bar(int x) : // This starts the initializer list section
m_x(x)
{
// This is assignment not initialization
// m_x = x;
}
// See the trailing 'const', research const correctness
int getx() const
{
return m_x;
}
};
foo.cpp (again this should be a header)
#include "bar.cpp"
class Foo
{
public:
// Just declaring a `Bar` data member
Bar m_bar;
Foo(int y) :
m_bar(y) // Initialize `Bar` data member using the available constructor
{
// First, this declares a new `Bar` instance which is different than
// the class member, regardless of the fact they are named the same
// Bar m_bar(y*2);
// Furthermore, even if you did the following it is assignment not initialization
// m_bar = Bar(y*2);
// Since initialization already occurred before this point an error
// will result if the `Bar` data member isn't instantiated via the
// only available constructor, since there isn't a default constructor as
// explained above
}
// Same comment about const correctness
int get_barx() const
{
return m_bar.getx();
}
};
You need to use initialization lists to construct class members at construction time. The body of the constructor gets called after all members have been constructed. If you don't explicitly call a non-default constructor then the compiler will insert a call to the default constructor for you. For example, your Foo class could look like:
class Foo {
public:
Foo(int y) : m_bar(y*2) {}
...
private:
Bar m_bar;
}

Strange output with static objects

I can't understand what's happening...
Suppose that I have the following code:
// main.cpp
#include "some_header.h"
void bar();
int main()
{
foo();
bar();
}
// file.cpp
#include "some_header.h"
void bar()
{
foo();
}
// some_header.h
#include "foo.h"
inline
void foo()
{
static Foo instance;
}
// foo.h
#include <iostream>
class Foo
{
public:
Foo() { std::cout << "Foo::Foo() \n"; }
~Foo() { std::cout << "Foo::~Foo() \n"; }
};
Output
Foo::Foo()
Foo::~Foo()
The question is: why there's no second "Foo::Foo()" in the output? I think that it should be here because each translation unit (in my case main.cpp and file.cpp) should have its own Foo object (because of static keyword). Am I wrong? Can somebody quote the standard, please?
If i move the definition of Foo object from the function like this
// some_header.h
#include "foo.h"
static Foo instance;
inline
void foo()
{
}
the output will be
Foo::Foo()
Foo::Foo()
Foo::~Foo()
Foo::~Foo()
Is it inline magic or am I missing smth more fundamental?
What I need to do - I need to add boost::mutex object in some function for my header-only library to synchronize some WinAPI function calls like this:
inline
void some_func()
{
static boost::mutex sync;
boost::lock_guard<boost::mutex> lock(sync);
// Call some WinAPI function
}
How can I do it?
MSVC-11.0.
static is a heavily overloaded keyword in C++. At namespace scope, it means "entity has internal linkage, so every translation unit will have its own copy." At function scope, it means "there is only one such entity for the function and it persists across function calls."
So in your case, the funcion foo() simply has one object Foo instance with local scope, but global lifetime.
As for your mutex question, I can't see anything wrong with doing just what you posted in the question. some_func() will have a single instance of the mutex, and all calls to some_fucn() will share that one instance (and since C++11, it will be correctly and thread-safely initialised by the first such call). I'd say that's exactly what you need.

Way To Access A Variable In All Methods Of Class Except Defining As Global Variables

Is there any way to access a variable in all of my methods in a class(except using global varibles that defines above of cpp file)??
TIA
foo.h
class Foo {
static int bar;
void foo ();
};
void foo ();
foo.cpp
int Foo :: bar = 123;
void Foo :: foo () {
++bar; // ok
}
void foo () {
++ bar; // Error! Not in scope.
++ Foo :: bar; // Error! Private.
}
You mean a static data member of the class?
The other answers are correct, but I didn't read your question as meaning it is the same across Foo objects which is what making it as static here will do (as well as making it interesting across multi-threaded code). You can also make it just a private variable such as here:
Header:
class Foo
{
private:
int bar;
void foo ();
public:
Foo();
};
Class:
Foo::Foo() : bar(123) {}
void Foo :: foo ()
{
// Will update its own bar, but not every other Foo object that exists
++bar; // ok
}
But maybe the static way is what you wanted :-)