[英]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.我正在解析一个文件并创建一个 Foo 对象向量的向量。
vector< vector<Foo*> > mFooVectors;
I have to allow access with the following getFoos function.我必须允许使用以下 getFoos function 进行访问。
const vector<const Foo*>& getFoos(int index);
So I created a const declaration of my vector:所以我为我的向量创建了一个 const 声明:
const vector< const vector<const Foo*> > mConstFooVectors;
Now how do I do mConstFooVectors = mFooVectors so I can return a reference to mConstFooVectors?现在我该如何做 mConstFooVectors = mFooVectors 以便我可以返回对 mConstFooVectors 的引用?
You cannot add const
at any given level that easy.在任何给定级别上添加
const
都不是那么容易。 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.模板的不同实例化是不同的不相关类型,
vector<T>
与vector<const T>
无关,并且无法从一个转换到另一个。
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.顺便说一句,如果您返回对外部向量的 const 引用,则 const 引用将表现为:
const std::vector< const std::vector< Foo * const > >&
,请注意,由于与C++ 中的类型,const-ness传播。问题是存储在内部向量中的值是一个指针,并且使该指针常量不会使指向的 object 常量。 Similarly, the behavior of your getFoos(int)
will be equivalent to const std::vector< Foo * const >&
.同样,您的
getFoos(int)
的行为将等效于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我不知道你想做什么,但我会看看 boost::ptr_vector
Specially, your vector member can potentially leak if you don't handle it correctly... (RAII)特别是,如果您处理不当,您的矢量成员可能会泄漏......(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. vector 的复制构造函数应该能够处理它
,但您必须在类的构造函数的初始化列表中执行此操作,因为它是 const 成员。
Edit: That was wrong... Vector's copy constructor can't handle it.编辑:那是错误的...... Vector 的复制构造函数无法处理它。 See David Rodriguez' post for an explanation (vector and vector are unrelated types).
有关解释,请参阅 David Rodriguez 的帖子(向量和向量是不相关的类型)。
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).你必须决定你想要哪一个 - 没有办法从一个转换到另一个(不制作副本)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.