开发者

STL vector deallocation

开发者 https://www.devze.com 2023-02-06 09:44 出处:网络
Given an STL vector of pointers, each element has to be deallocated before destroying the vector itself. Is there any technical implication that prevents the STL library for doing it automatica开发者_

Given an STL vector of pointers, each element has to be deallocated before destroying the vector itself. Is there any technical implication that prevents the STL library for doing it automatica开发者_StackOverflowlly?

Thanks


The reason the STL doesn't do it for you is that it can't know whether or not it's supposed to. You might have a vector of pointers to arrays (in which case it needs to do delete[]), of pointers to regular objects (in which case it would need to do delete), or possibly memory from some custom allocator. Those pointers could also be shared with some other objects, in which case deleting them would cause those other objects to point at garbage data, leading to undefined behavior. Those pointers could also be to stack-allocated memory, in which case no deallocation is necessary.


you can store there pointers that shouldn't be deleted when vector is destructed

use vector of smart pointer (e.g. boost::shared_ptr) to receive automatic deallocation


If a vector contains pointers, it does not mean that the pointers point to dynamic memory. And if they do, should delete or delete[] be applied to each pointer? And what if the pointers points to objects created using placement new? All these question should be answered by the programmer, not by the library.

0

精彩评论

暂无评论...
验证码 换一张
取 消