Using the return value of operator* from a "dead" unique_ptr is bad.
The following code compiles but results of course with an Undefined Behavior:
auto& ref = *std::make_unique<int>(7);
std::cout << ref << std::endl;
Why the standard didn't make the return value of operator* for rvalue of std::unique_ptr an rvalue of the internal value, instead of lvalue, like that:
// could have been done inside unique_ptr
T& operator*() & { return *ptr; }
T&& operator*() && { return *ptr; }
In which case this would work fine:
std::cout << *std::make_unique<int>(7) << std::endl;
But the code at the beginning would not compile (cannot bind rvalue to lvalue).
Side note. Of course someone could still write bad code like the below, but it is saying "I'm UB" more verbosely, thus not so relevant:
auto&& ref = *std::make_unique<int>(7);
std::cout << ref << std::endl;
Aucun commentaire:
Enregistrer un commentaire