lundi 27 février 2017

Reusing objects in functions defined in C++ header

I have a function library in a header file, which includes the following function:

// Get a normally distributed float value in the range [0,1].
inline float GetNormDistrFloat()
{
    std::random_device _RandomDevice;
    std::normal_distribution<float> _NormalDistr(0.5, 2.0);

    float val = -1;
    do { val = _NormalDistr(_RandomDevice); } while(val < 0.0f || val > 1.0f);

    return val;
}

This works well, however, I don't want to create the std::random_device and std::normal_distribution objects every time I call this function GetNormDistrFloat().

What is the "best" (correct) way in C++ to deal with this? I tried to just move those two object definitions outside the function, but that led to linker errors. Do I have to create a .cpp file for this header and initialize the objects there?

Aucun commentaire:

Enregistrer un commentaire