pi is not initialized to a pointer to variable allocated on heap. and it is even not initialized to 0. so either ....boost::shared_ptr spi(new int 1) or ... boost::shared_ptr spi // initialized to 0 Normally it is a bad form to write spi() since the pointer could be either (1) a pointer to local variable or (2) a pointer not "fresh" - shared_ptr's shared_count object exclusively wraps a raw pointer to heap. So the following code will terribly fail: int* myIntPtr = new int
【在 d****p 的大作中提到】 : pi is not initialized to a pointer to variable allocated on heap. and it is : even not initialized to 0. : so either : ....boost::shared_ptr spi(new int 1) : or : ... boost::shared_ptr spi // initialized to 0 : Normally it is a bad form to write spi() since the pointer : could be either (1) a pointer to local variable or (2) a pointer not "fresh" : - shared_ptr's shared_count object exclusively wraps a raw pointer to heap. : So the following code will terribly fail:
h*0
18 楼
UB…… 你直接试: int* p = new int(); int* q = p; delete p; delete q; 应该也没事
【在 d****p 的大作中提到】 : pi is not initialized to a pointer to variable allocated on heap. and it is : even not initialized to 0. : so either : ....boost::shared_ptr spi(new int 1) : or : ... boost::shared_ptr spi // initialized to 0 : Normally it is a bad form to write spi() since the pointer : could be either (1) a pointer to local variable or (2) a pointer not "fresh" : - shared_ptr's shared_count object exclusively wraps a raw pointer to heap. : So the following code will terribly fail:
d*p
22 楼
What you said is almost 100% true except one case: shared pointer can wrap pointer pointing to local variable in its scope if you explicitly provide a null deleter when constructing the shared pointer.
【在 d****p 的大作中提到】 : What you said is almost 100% true except one case: : shared pointer can wrap pointer pointing to local variable in its scope if : you explicitly provide a null deleter : when constructing the shared pointer.
h*8
24 楼
能否展开说说? 什么叫null deleter?
【在 d****p 的大作中提到】 : What you said is almost 100% true except one case: : shared pointer can wrap pointer pointing to local variable in its scope if : you explicitly provide a null deleter : when constructing the shared pointer.
if this code stays in main function, it is possible that compiler doesn't generate code destructing the two shared pointers and you won't see a crash. Otherwise, there will be a crash for sure.
【在 d****p 的大作中提到】 : if this code stays in main function, it is possible that compiler doesn't : generate code destructing the two shared pointers and you won't see a crash. : Otherwise, there will be a crash for sure.