Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
659 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 Reply

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...