//Cat.h
class Cat {public: void const_meow() const{ ... }; void meow(){ ... }; }; class CatLibrary {public: std::vector<std::shared_ptr<Cat>>::iterator begin() { return m_cat_list.begin(); }
//main.cpp
CatLibrary cat_library; cat_library.add(std::make_shared<Cat>()); cat_library.add(std::make_shared<Cat>()); for(auto& cat: cat_library ) { cat->const_meow(); cat->meow(); } for(const auto& cat: cat_library) { cat->const_meow(); cat->meow();
I want my CatLibrary to show non-const begin() and non-const end() , in which the client can iterate a smart pointer that points to a mutable Cat. Both const begin() and const end() return an iterator that indicates immutable.
Then, when the client iterates through the const CatLibrary, I would not worry that he could modify the contents of Cat in the library.
But const , added to my begin() member function, only qualifies the pointer as a const pointer, not the Cat that it points to.
Without a pointer, a vector with a constant also makes the iterator a point with an element with a constant. But I want this effect to also apply the element indicated by the smart pointer.
I have an approach to solving my problem, but I'm not sure what problems will arise in the future.
Support two vectors in const and nonconst
#include <iostream> #include <memory> #include <vector> class Cat {public: void const_meow() const { std::cout << "meow" << std::endl;} void meow() { std::cout << "meow" << std::endl;} }; class CatLibrary {public: void add(std::shared_ptr<Cat> cat) { m_cat_list.push_back(cat); m_cat_const_list.push_back(cat); }; std::vector<std::shared_ptr<Cat>>::const_iterator begin() { return m_cat_list.begin(); } std::vector<std::shared_ptr<const Cat>>::const_iterator begin() const { return m_cat_const_list.begin(); } std::vector<std::shared_ptr<Cat>>::const_iterator end() { return m_cat_list.end(); } std::vector<std::shared_ptr<const Cat>>::const_iterator end() const { return m_cat_const_list.end(); } private: std::vector<std::shared_ptr<Cat>> m_cat_list; std::vector<std::shared_ptr<const Cat>> m_cat_const_list; }; int main() { CatLibrary cat_library; cat_library.add(std::make_shared<Cat>()); cat_library.add(std::make_shared<Cat>()); cat_library.add(std::make_shared<Cat>()); const CatLibrary& const_cat_library = cat_library; for(auto& cat: cat_library) { cat->meow(); } return 0; }
Or is there another solution to solve this problem with a constant on a smart pointer in a vector?
source share