共享指针和指向对象的连续性

Shared pointers and constness of pointed-to object

本文关键字:对象 连续性 指针 共享      更新时间:2023-10-16

如果我有一个类,比如

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上迭代。