[英]Shared pointers and constness of pointed-to object
If I have a class, say, 如果我有课,比方说,
class Car {
public:
void Drive();
void DisplayMileage() const;
};
And I create a shared pointer based on this class, 我基于这个类创建了一个共享指针,
typedef boost::shared_ptr<Car> CarPtr;
And I then go on to populate a vector of CarPtrs, 然后我继续填充CarPtrs的载体,
std::vector<CarPtrs> cars...;
I now want to iterate over the vector and do some stuff: 我现在想迭代向量并做一些事情:
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.
}
Is this possible without casting the shared pointer to a car to a shared pointer to a const car? 这是否可以在不将汽车的共享指针转换为指向const汽车的共享指针的情况下实现?
Sounds like a good use case for the Boost.Range "indirected" adaptor : 听起来像是Boost.Range“间接”适配器的一个很好的用例:
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]
}
Is this possible without casting the shared pointer to a car to a shared pointer to a const car ?
这是否可以在不将汽车的共享指针转换为指向const汽车的共享指针的情况下实现 ?
No, it is not possible. 不,这是不可能的。 The
const
applies to the shared pointer, not to the thing it refers to. const
适用于共享指针,而不适用于它引用的东西。
This is a basic fact of indirection, and it is the same with pointers: 这是间接的基本事实,它与指针相同:
int main()
{
int x = 0;
int* p1 = &x;
auto const p2 = p1;
// p2 is `int* const`, not `int const*`
*p1 = 1;
}
It's arguably unfortunate that there's simply no way to inherently gain immutability in your iteration, but that's because you're employing indirection: you're not iterating over Car
s. 可以说遗憾的是,在你的迭代中根本没有办法固有地获得不变性,但那是因为你正在使用间接:你不是在迭代
Car
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.