5 ms·
There is a big difference between "undefined" and "unspecified" behavior. In this case, the behavior of `unique_ptr(unique_ptr&&)` is in fact specified. [0] Ho
by s28l 4y ago
There is a big difference between "undefined" and "unspecified" behavior. In this case, the behavior of `unique_ptr(unique_ptr&&)` is in fact specified. [0]
However, the bigger issue with that code is that it can easily stop working with a simple refactor. Consider:
void foo(std::unique_ptr<int> ptr) {}
void bar(std::unique_ptr<int>&& ptr) {}
int main()
{
std::unique_ptr<int> p1{new int{1}};
std::unique_ptr<int> p2{new int{2}};
foo(std::move(p1));
assert(p1 == nullptr);
bar(std::move(p2));
assert(p2 != nullptr);
}
Neither of the above asserts will fire, but from the calling site, they look exactly the same. In my opinion, the more explicit option would be to do something like `bar(std::exchange(p2, nullptr))`
[0]: overload (5) https://en.cppreference.com/w/cpp/memory/unique_ptr/unique_ptr https://en.cppreference.com/w/cpp/memory/unique_ptr/unique_p...
- account42 4y agoRight, but changes in some other code potentially silently breaking assumptions at the calling site is exactly why you would want an assert like this in the first place.