3 ms·
I believe std::vector traditionally was forced to copy or move-construct instead of realloc() because there was no concept of "trivially movable" or "trivially
by yazzku 2y ago
I believe std::vector traditionally was forced to copy or move-construct instead of realloc() because there was no concept of "trivially movable" or "trivially copyable". Has that changed in recent standards?
- funkychicken 2y agoIt is slowly making its way through the standards committee. https://github.com/cplusplus/papers/issues/43 https://github.com/cplusplus/papers/issues/43 The author has a fork of clang and gcc with some pretty impressive speedups, so I’m hopeful! https://lists.isocpp.org/sg14/2024/04/1127.php https://lists.isocpp.org/sg14/2024/04/1127.php
- MaxBarraclough 2y agoThe std::is_trivially_copyable type-trait can be used to determine if a type is trivially copyable. It's been in the standard since C++11. I imagine an implementation of std::vector could make use of it to determine if it's safe to use realloc. https://en.cppreference.com/w/cpp/types/is_trivially_copyable https://en.cppreference.com/w/cpp/types/is_trivially_copyabl...
- nly 2y agoThe C++ Allocator concept has no reallocate() function, which would also have to change in order to actually see a speedup: https://en.cppreference.com/w/cpp/named_req/Allocator https://en.cppreference.com/w/cpp/named_req/Allocator But regardless, realloc() can't be used to implement the optimisation efficiently because of this line from the C man page: > The realloc() function returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable *and may be different from ptr* Basically, if the implementation can't extend the memory allocation it can fallback to malloc(), memcpy() and free() - so by the time C++ gets control back, it's too late to call the appropriate C++ functions.