I'm trying to make a function that generates a random number with given interval using <random> (the C++ way!). I want to avoid passing by arguments because the code becomes very messy and there isn't performance gain.

I'm currently using this:

namespace random_gen { std::random_device random_number_generator_seed; std::mt19937 random_number_generator(random_number_generator_seed()); std::uniform_int_distribution<unsigned int> random_interval; } // Reponsible for initializing random number generator unsigned short int get_random_number(unsigned short int lower_limit, unsigned short int higher_limit) { random_gen::random_interval.param(std::uniform_int_distribution<unsigned int>::param_type(lower_limit, higher_limit)); return random_gen::random_interval(random_gen::random_number_generator_seed); }

(Globally declaring the things and using one function)

But would this be better?

unsigned short int get_random_number(unsigned short int lower_limit, unsigned short int higher_limit) { static std::random_device random_number_generator_seed; static std::mt19937 random_number_generator(random_number_generator_seed()); static std::uniform_int_distribution<unsigned int> random_interval; random_gen::random_interval.param(std::uniform_int_distribution<unsigned int>::param_type(lower_limit, higher_limit)); return random_gen::random_interval(random_gen::random_number_generator_seed); }

(using one function, declaring the objects as static)

My doubt is: would the static objects call their constructors every time the function is called or would they not? I only know that static prevent reallocation of memory but I don't know these specifics.

Given the answer to the previous question, what would you prefer (the first code snippet or the second)? Or would you prefer passing arguments to function?

(sorry for the long names if it's hard to read)

This post has been edited by **Nwb**: 11 February 2019 - 04:39 AM