Redian新闻
>
CareerCup 13.9的solution有memory leak
avatar
CareerCup 13.9的solution有memory leak# JobHunting - 待字闺中
b*n
1
13.9 Write a smart pointer (smart_ptr) class.
代码在下面。象第16行这样直接赋值,ref_count原来指向的空间就丢了。如果有另一
个smart
pointer指向同一个空间,那么ref_count分配的空间还可以access,但是count并没有
减一,所以
最终还是无法释放指针。
13 SmartPointer & operator=(SmartPointer & sptr) {
14 if (this != &sptr) {
15 ref = sptr.ref;
16 ref_count = sptr.ref_count;
17 ++*ref_count;
18 }
19 return *this;
20 }
有兴趣可以试试下面的test case:
SmartPointer spt1(new int(10));
SmartPointer spt2(new int(20));
spt2 = spt1; // the original ref_count of spt2 now is a dangle
pointer.
avatar
g*k
2
It seems that is how c++0x does.
So it is a smart pointer, but it is not that smart.

【在 b*****n 的大作中提到】
: 13.9 Write a smart pointer (smart_ptr) class.
: 代码在下面。象第16行这样直接赋值,ref_count原来指向的空间就丢了。如果有另一
: 个smart
: pointer指向同一个空间,那么ref_count分配的空间还可以access,但是count并没有
: 减一,所以
: 最终还是无法释放指针。
: 13 SmartPointer & operator=(SmartPointer & sptr) {
: 14 if (this != &sptr) {
: 15 ref = sptr.ref;
: 16 ref_count = sptr.ref_count;

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。