C++返回不可变指针向量的函数语法

C++ syntax for function that returns immutable vector of pointers

本文关键字:函数 语法 向量 指针 返回 不可变 C++      更新时间:2023-10-16

我在MyClass上有以下c ++函数:

class MyClass {
public:
    std::vector<MyObject*> getVector();
};

我想确保抓取此集合的对象不会修改集合或内容。实现此目的的适当 c++ const用法是什么?

编辑:我所说的"内容"是指指针和它们指向的内容。

std::vector<const MyObject *> getVector();

const std::vector<const MyObject *> &getVector();

应该做这个伎俩。你不需要指针是常量,只需要它们指向的 MyObject 实例和 std::vector 对象(如果返回引用),因此向量不会改变其状态,任何引用的项都不会公开为非常量。

附带说明一下,std::vector<MyObject*> getVector()将返回该向量的副本,根据 OOP 原则(封装)而言,这是一个理想的行为:

调用此 getter 将不允许改变 MyClass 实例的状态。

当然,从

性能上讲,这是糟糕的设计,毫无疑问,您实际上需要返回一份副本(对于getter来说,这是相当奇怪的规格)。这就是为什么你应该返回对 const 对象的引用,它同时允许返回对象本身(不复制),同时不允许其突变。

不确定是否正确。我只是用

class MyClass {
  std::vector<MyObject*> my_objects_;
 public:
  const std::vector<const MyObject*> &getVector() {
    return *reinterpret_cast<const std::vector<const MyObject *> *>(&my_objects_);
  }
};

来做这个伎俩。