A strong reference keeps the referenced object alive (i.e., as long as there is at least one strong reference to the object, it is not deleted). boost::shared_ptr acts as a strong reference. In contrast, a weak reference does not keep the object alive, it merely references it as long as it lives.
Note that a raw C++ pointer in this sense is a weak reference. However, if you have just the pointer, you have no ability to detect whether the object still lives.
strong pointer免除 memory leaks的問題
理由如下:
Since the destruction of the last strong reference to an object will destruct the object, one cannot 'forget' to deallocate the memory.
weak pointer免除cycle reference問題
理由如下:
所以我們可以使用一個weak pointer和一個strong pointer指向一個物件,當strong pointer被釋放時,且當weak pointer被釋放了,該儲存物件的記憶體也會被釋放。
weak pointer 和strong pointer可免除dangling pointers
理由如下:
We have eliminated dangling pointers. If you have a strong pointer to an object, you can be sure it will not be destructed before your pointer is. If you have a weak pointer to an object, and the object is destructed, your weak pointer will be valued null, which is easily tested for.
reference:
http://www.codeproject.com/KB/stl/boostsmartptr.aspx
http://code.google.com/p/mist/wiki/SmartPointers
沒有留言:
張貼留言