I know if I want to apply call by reference via std::thread, I should wrap passing argument with std::ref as std::reference_wrapper to be copy-able. I met a compile failure when I try to directly pass a named int variable with function accepting int&. This is nice and gives a hint I should wrap it with std::ref.
auto f = [](int&) {};
int obj;
std::thread t(f, obj); // compile failure
std::thread t2(f, std::ref(obj)); // ok
Error message on Visual Studio 2015: pastebin
But in the case with user-defined object, it looks like no such compile error to give the hint. Of course the call by reference does not work, the passed value is not affected after thread completed.
struct MyObject { int i; MyObject(): i(0){} };
auto f = [](MyObject& obj) { obj.i = 100 };
MyObject obj;
std::thread t(f, obj); // compile fine
// obj.i is still 0
Why does compiler allow to compile if type is not built-in type for this wrong usage?
Updated:
After disabled the visaul studio language extension, both user-defined object and built-in types are not allowed to compile.
Aucun commentaire:
Enregistrer un commentaire