1) to avoid matches. 2) reduce the overhead associated with bouncing around a set of common pointers.
The former will be serviced no less, and the latter will be better served by implementing weak_ptr.get (), so why doesn't it exist? Moreover, would weak_ptr.get () not be more efficient than weak_ptr.lock (). Get (), or can the compiler optimize this to be the same?
The former is true, the latter is false - weak pointers are not magical, inexpensive, general pointers ... they are functionally different. You need to choose the one that suits your situation.
The main reason for using weak pointers is to keep track of some of the data that you might want to use if it still hangs around but can survive without pleasure. An establishment that is connected with the state of the race with users of shared pointers, so if you do not have insider information about the lifetime of the object, this means that you can be sure that your code can complete before the destruction of the object, an unprocessed pointer will be useless. If you have insider insight, you can get the original pointer initially - instead of a weak pointer, but the design of the weak pointer is designed to prevent you from accidentally getting it and creating unsafe code. In fact, any such understanding may be fragile in the face of the medium / long term evolution of the code, so it is probably best not to try to do such optimizations if you shouldn't.
Perhaps a good example of using a weak pointer will help ...
Say that the object represents something on the screen - if you want it to start, you added a weak pointer to the list of flashes with a timer, then you can forget about it. When the timer is triggered, if the Flasher code detects that the object was destroyed in advance (i.e., it is no longer on the screen), flasher only removes it from the list, but it does not want to share property and not support the object unnaturally. It might be easier than trying to track code when an object disappears from the screen to tear it out of the flasher list (and possibly block its lock for this).
source share