3 ms·
But why it can't? Assume that such an operation (alocate new adjacent memory cell without worrying about other elements) could indeed be performed by the vector
by bluecalm 11y ago
But why it can't? Assume that such an operation (alocate new adjacent memory cell without worrying about other elements) could indeed be performed by the vector. How in that case does it know whether or not the next adjacent memory cell is free and was not just occupied by another processor long time ago? There is no way (or they are too way hard and unrealistic) for vector to do that properly. Thus no choice left, vector has to reallocate the place for all items it already has plus additional one.
Isn't it what realloc is for?
- usefulcat 11y agoFor std::vector<int>, realloc would be fine. But you wouldn't want std::vector<std::string> to use realloc.
- bluecalm 11y agoMy first reaction when I've read your comment was that it has to be because of sub-strings but as std::vector allocates memory again anyway that can't be too important. Can you elaborate a bit? I am not a C++ programmer but I am sometimes curious so maybe I am missing something obvious.
- animefan 11y agoI wad confused too but looking at the definition of realloc, it will sometimes allocate adjacent memory and sometimes allocate new memory and perform a move. In which case copying the std::string values might not be valid.
- bluecalm 11y agoWell, but std::vector always performs a move so any pointers to sub-strings won't be valid anyway from what I understand. I am probably just not getting something but it really seems like it should just use realloc. Maybe it has something to do with thread safety though as I don't think there are any guarantees for realloc.
- fiatmoney 11y agoIt is not advisable to mix malloc / free / realloc (C style) with new / delete (C++ style), and C++ doesn't have a "native" realloc because of trickiness with con/destructors.