0

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?

10
  • You can use emplace_back. Commented Aug 26, 2016 at 0:05
  • @Ben emplace_back gives me the same compilation error. Why do you think emplace_back should work? Commented Aug 26, 2016 at 0:07
  • What compiler are you using? Commented Aug 26, 2016 at 0:07
  • 1
    Unfortunately the question was closed as a dupe, which it partially is. Answering the bit that isn't covered by the dupe: You can still create this vector because template code isn't instantiated unless it's used. The constructor of a vector does not contain any code that requires copy-assignability, and the code for push_back isn't generated for A * const if you don't use it. So when you don't use push_back, the compiler doesn't complain. Commented Aug 26, 2016 at 0:21
  • 1
    @macco Well, yes and no. You can't use it with const pointers. But that doesn't mean you can't use it with non-copyable things, because you can use it with moveable non-copyable things. So you could potentially wrap your const pointers in a moveable class and use that, I suppose. (I apologize, my last comment was a bit sloppy and I realize I implied copy-assignability was the criteria, but moveability works too.) Commented Aug 26, 2016 at 1:10

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.