C++返回不可变指针向量的函数语法
C++ syntax for function that returns immutable vector of pointers
我在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_);
}
};
来做这个伎俩。
相关文章:
- C++使用 rand 定义函数语法
- QObject::连接不起作用 - 使用函数语法找不到信号
- C++ std::函数语法问题
- 如何在不更改现有函数语法的情况下将普通指针替换为共享指针
- 模板化函数语法错误中使用的模板化类中的嵌套类
- C 变化函数语法
- 返回语句中的构造函数语法
- 复制构造函数语法错误:myclass 没有成员 mymember
- C++.传递给函数.语法问题
- C++可视化工作室函数语法突出显示
- 在 c++ 中移动 2d 数组的构造函数(语法逻辑不清楚):
- c 通过值或指针函数语法
- 正确的朋友模板函数语法
- C++类构造函数语法的解释
- C++ 使用指针移动构造函数(*&&&语法)
- 复制构造函数语法并显示构造函数的值
- 回调函数语法
- 类模板专用化中的成员函数语法
- C++学习函数语法
- 使用模板 C++ 的友元函数语法错误