Search code examples
c++initializationinitializer-listobject-initializers

Call a plain void function from member initialization list?


I have a funky problem here. I benchmark object creation with a few simple timers. My code-base is slowly moving away from being a prototype and more of a complete framework. This requires initializing some simple structs at a top level (out of main). Which means I cannot find a way to benchmark the object initialization and this is crucial.

In an ideal world, I could do something along the lines of :

struct Potato {
    Potato()
        : benchmark::start()
        , some_int(42)
    {
        /* Some more stuffs */

        benchmark::stop();
    }

    int some_int;
};

You get the idea, I wish to benchmark the member initializer list. Does anyone have a tip on how to do so with objects that are global (static) throughout the software? I was experimenting with constexpr functions to no avail. I also get some copy constructor issues (from make_tuple) when returning the object collection from a simple function.

Any tips appreciated, thanks.


Solution

  • Simply create a wrapper struct to your benchmark such that it's constructor only calls benchmark::start(), then you will manually stop it in Patato's constructor body. But you need to make sure the wrapper instance is the first object in Patato (This will take advantage of C++'s member initialization order) . Illustration:

    struct Benchmarker{
        Benchmarker(){ benchmark::start(); }
    };
    
    struct Potato {
        Potato()
            :  //Benchmark's ctor will be implicitly called first
               some_int(42)
        {
            benchmark::stop();
        }
    
        Benchmarker benchmark;    //NOTE: Make sure its the first
        int some_int;
    };