I have a class TileManager that manages the lifetime of objects and therefore holds a shared_ptr on them:
class TileManager {
private:
std::vector<std::shared_ptr<const Tile>> tiles;
}
Now I have another class Map which holds non-owning references to the objects managed by TileManager:
class Map {
private:
std::vector<std::weak_ptr<const Tile>> tiles;
}
My problem is: I don’t want the Map class to be able to manipulate the smart pointers to Tile. Therefore I would like to make the pointers inside the vector const:
class Map {
private:
std::vector<const std::weak_ptr<const Tile>> tiles;
}
Unfortunately it is not possible to put const objects into a STL container.
Anyone know a solution? Maybe a completely different design?
Elements stored in a
vectorcannot beconstbecause they must be assignable. The only way that thevectorcould “manipulate” the pointers in any observable way would be to destroy the lastweak_ptrto a given object which would cause the control block for the correspondingshared_ptrto be deallocated (assuming there are no othershared_ptr‘s that still reference it).In short, you can safely store non-
constweak_ptr‘s in a vector.