简体   繁体   中英

C++ - returning a const vector of const vectors of const objects

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?

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 .

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)

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).

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM