共享指针和指向对象的连续性
Shared pointers and constness of pointed-to object
如果我有一个类,比如
class Car {
public:
void Drive();
void DisplayMileage() const;
};
我创建了一个基于这个类的共享指针
typedef boost::shared_ptr<Car> CarPtr;
然后填充一个CarPtrs向量,
std::vector<CarPtrs> cars...;
我现在想遍历向量并做一些事情:
for(auto const &car : cars) {
car->DisplayMileage(); // I want this to be okay
car->Drive(); // I want the compilation to fail here because Drive isn't const.
}
如果不将指向汽车的共享指针强制转换为指向const汽车的共享指针,这是否可能?
听起来像是Boost的一个很好的用例。范围"间接"适配器:
for(auto const& car : cars | boost::adaptors::indirected) {
car.DisplayMileage();
car.Drive(); // error: passing 'const Car' as 'this' argument of 'void Car::Drive()' discards qualifiers [-fpermissive]
}
如果不将指向汽车的共享指针强制转换为指向const car的共享指针,是否可能 ?
不,不可能。const
适用于共享指针,而不是它所引用的对象。
这是间接的一个基本事实,对于指针也是如此:
int main()
{
int x = 0;
int* p1 = &x;
auto const p2 = p1;
// p2 is `int* const`, not `int const*`
*p1 = 1;
}
不幸的是,在迭代中根本没有办法固有地获得不变性,但这是因为您使用了间接:您不是在Car
s上迭代。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 构造对象的歧义
- 共享指针和指向对象的连续性