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?

macco
  • 469
  • 4
  • 12
  • You can use `emplace_back`. – Fantastic Mr Fox Aug 26 '16 at 00:05
  • @Ben emplace_back gives me the same compilation error. Why do you think emplace_back should work? – macco Aug 26 '16 at 00:07
  • What compiler are you using? – templatetypedef Aug 26 '16 at 00:07
  • @templatetypedef It says default compiler (Apple LLVM 6.1) in Xcode IDE. – macco Aug 26 '16 at 00:13
  • @gsamaras I'm edited the post. I'm using "class A{ };" as A. – macco Aug 26 '16 at 00:15
  • @gsamaras but I get the same error If I use int as A too. – macco Aug 26 '16 at 00:16
  • 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. – Jason C Aug 26 '16 at 00:21
  • @JasonC Thanks. So that means I can't use std::vector with const pointers. I will have to use a different data structure if I want that? I see that std::list works. – macco Aug 26 '16 at 00:34
  • 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](http://stackoverflow.com/questions/26906014/non-copyable-elements-in-vector). 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.) – Jason C Aug 26 '16 at 01:10
  • @macco there's no reason to have a vector or list of const objects anyway. Maybe `set` is better suited to what you want (set keys are immutable even though they are non-const). – M.M Aug 26 '16 at 01:47

0 Answers0