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
323 views
in Technique[技术] by (71.8m points)

c++ - weak_ptr, make_shared and memory deallocation

A control block of a shared_ptr is kept alive while there is at least one weak_ptr present. If the shared pointer was created with make_shared that implies that the whole memory of the object is kept allocated. (The object itself is properly destructed, but since the control block and the memory for the object were allocated in one chunk, as make_shared does, they can only be deallocated together.)

Is my understanding correct?

It seems that this behaviour represents a problem, for example in the famous "cache example". The memory for the objects will be kept allocated forever.

It it a problem in any practical situations? Shall the shared_ptr be created using a constructor in such a situation (large object and intent to use weak_ptrs)?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Is my understanding correct?

Yes. If your weak_ptrs significantly outlive the (large) object and you are tight on memory, it may be beneficial to avoid make_shared.

However, "large" here is measured by sizeof, and many conceptually "large" objects (for example, most standard containers, except std::array) are quite small by that metric, because they allocate additional memory to store their contents, which will be freed as soon as the object is destroyed.


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

...