0

Consider the following code

#include <iostream>

class my_class {
    public:
    static my_class& factory(int val) {
        static my_class instance{val};
        return instance;
    }
    private:
    my_class(int value) {
        std::cout<<value<<std::endl;
    };
};


int main() {
    auto& i77 = my_class::factory(77); // call #1
    auto& i1 = my_class::factory(1);  // call #2
    return 0;
}

The output is 77. On the call #2 constructor isn't called.

I understand what happens in call #1. Compiler allocates memory for instance at compile time and calls constructor on enetering my_class::factory(77);

But what happens on call #2? Why constructor isn't called? Is this behavior standard?

  • 3
    Because it is static. You answered your own question – RoQuOTriX Sep 07 '22 at 06:58
  • 1
    Static objects are instantiated only once. Your factory simply returns a reference to the same object each time. – jkb Sep 07 '22 at 06:58
  • Yes, it works as intended: on the second call, the same instance is reused. – HolyBlackCat Sep 07 '22 at 06:58
  • This is expected behavior. Static local variables are created and initialized on the first call to the function. Then they have a life-time of the remaining program, and exists for all calls to the function. – Some programmer dude Sep 07 '22 at 06:59
  • 1
    It's not a factory, it's a singleton similar to one described by https://stackoverflow.com/questions/17712001/how-is-meyers-implementation-of-a-singleton-actually-a-singleton – Swift - Friday Pie Sep 07 '22 at 07:12
  • because static object (in a function) is somehow the same as a global object, it is stored the "rw--" segment of the module, and they are initialized at loading time just before give the control to your user code. compiler will ignore the declaration and initialization for static object when compile the function. – Exlife Sep 07 '22 at 08:39

0 Answers0