Skip to content

<random>: distribution::operator() is erroneously const #1912

@stevenwdv

Description

@stevenwdv

Describe the bug
std::uniform_int_distribution::operator() and operator() of other distributions like uniform_real_distribution and geometric_distribution are all const, while the standard does not specify that these are const. This poses a portability problem for code marking the distribution as const to other standard libraries in which the operator is not const.

I'm not sure if this problem is already known and just not fixed for compatibility with wrong code.
I'm also not sure if it is really forbidden by the standard, or just not required, but as mentioned it causes problems when switching to another STL.

Command-line test case
This should not compile, but it does:

C:\Temp>type repro.cpp
#include <random>

int main() {
        std::default_random_engine random;
        const /*<-*/ std::uniform_int_distribution<int> dist;
        return dist(random);
}

C:\Temp>cl /EHsc /W4 /WX .\repro.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 19.29.30031 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

repro.cpp
Microsoft (R) Incremental Linker Version 14.29.30031.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:repro.exe
repro.obj

C:\Temp>.\repro.exe

C:\Temp>echo %errorlevel%
1351727964

Compare this with e.g.:

C:\Temp>clang -stdlib=libstdc++ repro.cpp
repro.cpp:6:9: error: no matching function for call to object of type 'const std::uniform_int_distribution<int>'
        return dist(random);
               ^~~~
C:\prog\msys64\mingw64\include\c++\10.2.0\bits/uniform_int_dist.h:188:2: note: candidate function template not viable:
      'this' argument has type 'const std::uniform_int_distribution<int>', but method is not marked const
        operator()(_UniformRandomNumberGenerator& __urng)
        ^
C:\prog\msys64\mingw64\include\c++\10.2.0\bits/uniform_int_dist.h:193:2: note: candidate function template not viable:
      requires 2 arguments, but 1 was provided
        operator()(_UniformRandomNumberGenerator& __urng,
        ^
1 error generated.

Expected behavior
operator() should be const, so the code above should not compile.

STL version

Microsoft Visual Studio Community 2019 Preview
Version 16.10.0 Preview 2.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementSomething can be improvedfixedSomething works now, yay!

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions