Static Objects

Static variables in C++ are initialised once and then exist for the lifetime of the programme. Once they have been initialised they can be referred to by using the variable name they were initialised with. In the following code we can see a simple example of the use of static variables.

#include <iostream>
#include <list>

class Base
{
public:
    Base() {};
    void foo();
};

std::list<Base*>& thing(Base* bp)
{
    static std::list<Base*> p;
    if(bp) p.push_back(bp);
    return p;
}

class Bar{
public:
    Bar(Base * b){
        thing(b);
    }
};


static Bar my_foo(new Base());


int main() {
    
    auto mods = thing(nullptr);
    std::cout << mods.size() << std::endl; // returns 1
    
    return 0;
}

The first time the function 'thing' is called is via the 'Bar' constructor, in which the static list 'p' is initialised and pushed back to give size 1. Any further calls to 'thing' will append another object of type 'Base' to the list, so long as the argument is non-null. Most importantly, any further calls will retrieve the static list after appending to it (if at all).

Comments

Popular posts from this blog

Using the AVX instruction set to boost performance

The magic behind deep learning : Obtaining gradients using reverse Automatic Differentiation.

Information Entropy