I want to make a vector of const pointers. (the pointers being constant, not A being constant)
This code here gives me the error:
class A{}; std::vector<A * const> vec; //creates vector of const pointers to A A * const a = new A(); //creates a const pointer to new object A //a vector requires the type of the elements to be copy assignable //so this gives a me compilation error vec.push_back(a); Cannot initialize a parameter of type 'void *' with an lvalue of type 'A *const *'
However this code here compiles:
class A{}; std::vector<A * const> vec; //creates vector of const pointers to A So why can I create a vector of non-CopyAssignable elements? Why would I be able to create a vector of non-CopyAssignable elements if I can't use it? Is there any way that I can create and use a vector of const pointers?
emplace_back.vectorbecause template code isn't instantiated unless it's used. The constructor of avectordoes not contain any code that requires copy-assignability, and the code forpush_backisn't generated forA * constif you don't use it. So when you don't usepush_back, the compiler doesn't complain.