I'm trying to reproduce the std::vector container, and I saw that in one of the vector constructor prototype we can give an allocator.
explicit vector (size_type n, const value_type& val = value_type(),const allocator_type& alloc = allocator_type()); So two questions came to my mind first, why are we able to give an allocator knowing that we already have the allocator_type member type ? second, what happen if I give a different allocator to the constructor ?
So I've tried this code.
#include <vector> #include <iostream> #include <memory> int main() { std::allocator<bool> alloc; std::vector< std::string > ve(10, "hello", alloc); for (int i = 0; i < 10; i++) std::cout << ve[i] << " | "; std::cout << "\n"; return 0; } Giving a bool allocator to construct a std::string vector works fine and valgrind doesn't complain about it.
So I'm wondering if the bool allocator gived to the constructor is really used, and if he's not what's the point to be able to give an allocator that can be different from the allocator_type to the constructor ?
Thanks for reading me.
std::vectortemplate. (2) The passed allocator is copied and used by the container.allocator_typemember is set to whatever is specified in theAllocatortemplate argument. This is the type of the allocator. The constructor accepts an instance of that type. If you don't provide an instance, thevectorwill create one internally by default. So,std::vector<std::string>expects astd::allocator<std::string>, don't give it astd::allocator<bool>. I would not expect this code to compile, but it does, I do not know why. Feel free to step into the code with a debugger and find out why for yourself.