[英]C++ syntax for function that returns immutable vector of pointers
I have the following c++ function on MyClass: 我在MyClass上具有以下c ++函数:
class MyClass {
public:
std::vector<MyObject*> getVector();
};
I want to make sure objects that grab this collection don't modify the collection or the contents. 我想确保获取此集合的对象不会修改集合或内容。 What is the appropriate c++
const
usage to acheive this? 实现此目标的适当c ++
const
用法是什么?
Edit : by "contents" I mean both the pointers and what they point to. 编辑 :“内容”是指指针及其指向的内容。
std::vector<const MyObject *> getVector();
or 要么
const std::vector<const MyObject *> &getVector();
should do the trick. 应该可以。 You don't need the pointers to be constant, only the MyObject instances they are pointing to and the std::vector object (if returning a reference), so the vector won't alter its state and any referenced item won't be exposed as non-const.
您不需要指针是常数,只需它们指向的MyObject实例和std :: vector对象(如果返回引用)即可,因此vector不会更改其状态,并且任何引用的项也不会是常量。暴露为非常量。
On the side note, std::vector<MyObject*> getVector()
will return a copy of that vector, which in terms of OOP principles (encapsulation) is a desirable behaviour: 附带说明一下,
std::vector<MyObject*> getVector()
将返回该向量的副本 ,就OOP原理(封装)而言,这是一种理想的行为:
A call to this getter will not allow to mutate the state of MyClass instance. 对此吸气剂的调用将不允许更改MyClass实例的状态。
Of course perfomance-wise that is poor design, unsless you actually need to return a copy (rather strange specification for a getter). 当然,从性能角度来说,这是糟糕的设计,除非您实际上需要返回副本(对于吸气剂而言,这是很奇怪的规范)。 That is why you should return a reference to const object , which in the same time allows returning the object itself (no copying) while disallowing its mutation.
这就是为什么您应该返回对const object的引用 ,它同时允许返回对象本身(不进行复制),同时不允许其突变。
Not sure whether it's correct or not. 不确定是否正确。 I just use
我只是用
class MyClass {
std::vector<MyObject*> my_objects_;
public:
const std::vector<const MyObject*> &getVector() {
return *reinterpret_cast<const std::vector<const MyObject *> *>(&my_objects_);
}
};
to do the trick. 做到这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.