Jump to content
  • Advertisement
Sign in to follow this  
Black Knight

how to return const vector+shared_ptr

This topic is 3615 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm storing this in a class :
std::vector<boost::shared_ptr<Item>> m_Inventory;


Now I want to return it from the class so I can print its contents from the interface drawing class. I tried this but it doesnt work
const std::vector<boost::shared_ptr<const Item>>& getItems()const {return m_Inventory;}


Is there a way to return the vector but not allow the caller to modify it? Or should I return items one by one with something like
boost::shared_ptr<const Item> getItem(unsigned int index)const{return m_Inventory[index];}


Share this post


Link to post
Share on other sites
Advertisement
Or you could provide a pair of constant iterators (possibly over the contents of the shared pointers, by constant reference).

template <typename T>
struct cst_iterator
{
std::vector< boost::shared_ptr<T> >::const_iterator iterator;

bool operator==(const cst_iterator &o) const
{ return o.iterator == iterator; }

bool operator!=(const cts_iterator &o) const
{ return o.iterator != iterator; }

cst_iterator &operator++(int)
{ ++iterator; return *this; }

cst_iterator operator++()
{ cst_iterator copy(*this); ++*this; return copy; }

typedef const T value_type;
typedef const T& reference_type;
typedef const T* pointer_type;
typedef std::size_t difference_type;
typedef std::forward_iterator_tag iterator_tag;

// And so on.
}

Share this post


Link to post
Share on other sites
The type std::vector<boost::shared_ptr<const Item> > is not related to std::vector<boost::shared_ptr<Item> >.

Quote:
Is there a way to return the vector but not allow the caller to modify it?


1. You could return a std::vector<boost::shared_ptr<const Item> > by value.


std::vector<boost::shared_ptr<const Item> > getItems()const {return std::vector<boost::shared_ptr<const Item> >(m_Inventory.begin(), m_Inventory.end());}




2. You could return an iterator/iterator-range:


MyConstIteratorRange getItems()const {return MyConstIteratorRange(m_Inventory.begin(), m_Inventory.end());}




I leave the implementation of MyConstIteratorRange to you... :)

3. You could return one element at a time, as your example:


boost::shared_ptr<const Item> getItem(unsigned int index)const {return m_Inventory[index];}


Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!