I thought that the value generated by the c++11 random distribution (uniform_int_distribution
, for instance), depends only on the state of the generator which is passed to the operator()
. However, for some reason there is no const
specifier in the signature of operator()
. What does that mean, and how should I pass the distribution as a function parameter? I thought I had to pass it as any non-mutual parameter: by const reference, but now I'm not sure.
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
I misunderstood the question at first, however, now that I understand, it's a good question. Some digging into the source of the implementation of
<random>
for g++ gives the following (with a few bits left out for clarity):If we squint past all the
_
, we can see that it has only a single member parameter,param_type _M_param
, which itself is simply a nested struct holding 2 integral values - in effect, a range.operator()
is only declared here, not defined. Some more digging brings us to the definition. In lieu of posting all the code here, which is pretty ugly (and rather long), it suffices to say that nothing is mutated inside this function. In fact, addingconst
to definition and declaration will happily compile.The question then becomes, is this true for every other distribution? The answer is no. If we look to the implementation for
std::normal_distribution
, we find:This is all just theorizing, but I imagine the reason it is not restricted to
const
is to allow implementers to mutate their implementation if required. Further, it keeps a more uniform interface - if someoperator()
areconst
and some are non-const
, it all becomes a bit messy.However, why they didn't simply make them const and let the implementers utilizemutable
I'm not sure. Likely, unless someone around here was involved with this part of the standardization effort, you may not get a good answer to this.Edit: As MattieuM pointed out,
mutable
and multiple threads do not play nicely together.Just as a minorly interesting aside,
std::normal_distribution
generates two values at once, caching one (hence the_M_saved
). Theoperator<<
that it defines actually lets you see this value before the next call tooperator()
:Here, the output format is
mu sigma nextval
.