I have a problem here: I am again reading C++ primer 5 edition. Now I am at std::allocator
everything is Ok but I don't know why my code here doesn't copmile:
#include <iostream>
#include <initializer_list>
#include <memory>
#include <vector>
void print_vec(vector<int> v) {
for (const auto i : v)
std::cout << i << ", ";
std::cout << std::endl;
}
int main(int argc, char* argv[]) {
//print_vec(5); // fails. vector(size_t) is explicit
std::allocator<vector<int>> a;
auto p = a.allocate(10);
a.construct(p, 5);// works?!
//a.construct(p + 1, {7, 16, 23, 81, 77, 24, 10}); // doesn't work even vector(initilizer_list) is not explicit
a.construct(p + 1, vector<int>({7, 16, 23, 81, 77, 24, 10 })); // works
for (int i = 0; i != 2; ++i) {
for (const auto& e : *(p + i))
std::cout << e << ", ";
std::cout << std::endl;
}
a.destroy(p);
a.destroy(p + 1);
a.deallocate(p, 10);
std::cout << std::endl;
}
Why calling
print_vec
passing an integer doesn't compile -because I guess that the constructor ofvector(size_type)
isexplicit
then why callinga.construct(p, 5);
works? as long as this value5
is passed in to the constructor of vector to create 5 value-initialized integer elements.Second I can call
print_vec
passing in aninitializer_list<int>
(vector(initializer_list) is not explicit ctor) but why this statement doesn't compile:a.construct(p + 1, {7, 16, 23, 81, 77, 24, 10});
?