If I try to use std::random_device
in Visual Studio 2022, it gives me this error:
Severity Code Description Project File Line Suppression State Details
Error C2280 'std::random_device::random_device(const std::random_device &)': attempting to reference a deleted function 12x6 C:\Users\User\source\repos\12x6\12x6\12x6.cpp 11
However, in VS Code, it works just fine.
Why won't Visual Studio allow me to use it, even though it works fine elsewhere?
Here's my code:
#include <iostream>
#include <random>
int main() {
auto seed = std::random_device{};
auto gen = std::mt19937{seed()};
auto dist = std::uniform_int_distribution<std::uint16_t>{0, 255};
for (int i = 0; i < 10; i++) {
std::cout << dist(gen) << "\n";
}
return 0;
}
The code you posted will work in Visual Studio – but only if you set the language standard to C++17 (or later). (The default for VS 2022 is to use the C++14 Standard).
This problem was fixed in the transition between C++14 and C++17: See this defect report.
You can change the language standard by right-clicking on the project and then, in the pop-up property sheet, select "C/C++ ... Language" and select C++17 or later in the "C++ Language Standard" drop-down property.
Alternatively, if you want to continue using C++14, you can change your declaration of seed
to avoid encountering the undesirable (and erroneous/defective) call of the deleted copy constructor, like so:
// auto seed = std::random_device{}; // Generates error
std::random_device seed; // Works!
This will (forcibly) use the default constructor rather than trying to use the copy constructor.