Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointer static, constructor

Tags:

c++

In this code we have static class variable and i need someone to explain what happens here and how i can use it.It is a static class variable and a function that gets the variable with a reference.

class Constructor 
{
private:
static Constructor constructor;
public:
static Constructor* constructor();

};
Constructor Constructor::constructor;
Constructor* constructor::constructor()
{
    return &constructor;
}
like image 227
Realkia Avatar asked Feb 26 '26 02:02

Realkia


1 Answers

Once you remove the errors so that it compiles

class Constructor 
{
private:
static Constructor constructor_;
public:
static Constructor* constructor();

};
Constructor Constructor::constructor_;
Constructor* Constructor::constructor()
{
    return &constructor_;
}

you end up with a single private instance of Constructor in the static variable Constructor::constructor_ that can only be accessed through its static public Constructor::constructor() method. This type of construction which allows only the creation of a single instance of a class is called a singleton. It is used like this:

int main(){   
    auto* s1 = Constructor::constructor();
    auto* s2 = Constructor::constructor();

    std::cout << (s1 == s2);
}

See working version here.

See Thread-Safe Initialization of a Singleton for additional information.

like image 88
Thomas Avatar answered Mar 02 '26 00:03

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!