Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::weak_ptr not have a move constructor or move assignment operator?

Looking through boost's 1.53 headers for weak_ptr, I was surprised to see that move assignment and move constructors were implemented even though they weren't documented. From this documentation, there isn't any requirement for std::weak_ptr to provide move functionality.

Looking through Visual Studio 2012's implementation of weak_ptr, I don't notice any obvious move operations declared in weak_ptr, though they may be hidden behind inheritance. However, this code results in the watch window reporting one shared reference and two weak references for the pointers, which leads me to believe that weak_ptr isn't move enabled:

std::shared_ptr<int> ptr(std::make_shared<int>(5));
std::weak_ptr<int> weakptr(ptr);
std::weak_ptr<int> movedWeakPtr(std::move(weakptr));

Is there a good reason that std::weak_ptr doesn't provide move functionality? If not, should weak_ptr be treated as a movable type?

like image 849
masrtis Avatar asked Aug 29 '26 09:08

masrtis


1 Answers

Every type that is copyable is by definition moveable. weak_ptr is copyable, and therefore it is moveable.

weak_ptr could have a move constructor, certainly. But it would only be for a relatively minor bit of optimization. It was probably a standards committee oversight.

like image 100
Nicol Bolas Avatar answered Aug 31 '26 23:08

Nicol Bolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!