Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
669 views
in Technique[技术] by (71.8m points)

c++ - Why would multiple shared pointers pointing to the same memory cause memory leak?

I am reading about shared pointers and the book say that it is bad idea having multiple shared pointers point to the same memory because if one shared_ptr reference count decrease to 0, it will deallocate that memory, making the other shared_ptr pointing to garbage.

int *z = new int;
shared_ptr<int> bad1(z); 
shared_ptr<int> bad2(z);

However, when the reference count for z becomes 0, wouldn't both shared_ptr know this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That won't cause a leak. It's actually much worse, since you have two unrelated shared pointers pointing to the same memory. Which means both will think they have ownership of the memory, and each will try to free it on their own.

If you want two shared memory object pointing to the same memory, then use the std::shared_ptr initialization (or assignment):

shared_ptr<int> good1(new int);
shared_ptr<int> good2 = good1;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...