Reputation:
I'm parsing a file and creating a vector of a vector of Foo objects.
vector< vector<Foo*> > mFooVectors;
I have to allow access with the following getFoos function.
const vector<const Foo*>& getFoos(int index);
So I created a const declaration of my vector:
const vector< const vector<const Foo*> > mConstFooVectors;
Now how do I do mConstFooVectors = mFooVectors so I can return a reference to mConstFooVectors?
Upvotes: 1
Views: 2457
Reputation: 5470
vector's copy constructor should be able to handle it, but you'll have to do it in the initializer list of your class's constructor since it's a const member.
Edit: That was wrong... Vector's copy constructor can't handle it. See David Rodriguez' post for an explanation (vector and vector are unrelated types).
Upvotes: 0
Reputation: 208353
You cannot add const
at any given level that easy. Different instantiations of a template are different unrelated types, a vector<T>
is unrelated to a vector<const T>
, and there is no way of casting from one to the other.
You can, on the other hand, create a different vector and just copy the contents, but that might be expensive, as you would have to copy all the different contained vectors.
By the way, if you return a const reference to the outer vector, the const reference will behave as: const std::vector< const std::vector< Foo * const > >&
, note that because of the value semantics associated to types in C++, const-ness propagates in. The problem is that the value stored in the inner vector is a pointer, and making that pointer constant does not make the pointed-to object constant. Similarly, the behavior of your getFoos(int)
will be equivalent to const std::vector< Foo * const >&
. Note, that is behavior not actual types.
Upvotes: 8
Reputation: 4574
You are mixing a
vector<const Foo *>
with
vector<Foo *>
You have to decide which one you want - there is no way to convert from one to another (without making a copy).
Upvotes: 0
Reputation: 5787
I don't know what you are trying to do, but I'd have a look at boost::ptr_vector
Specially, your vector member can potentially leak if you don't handle it correctly... (RAII)
Upvotes: 1