CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Threaded View

  1. #4
    Join Date
    May 2009
    Posts
    2,413

    Re: Returning a vector by value or by reference

    Quote Originally Posted by roddomi View Post
    But I've heard that I should avoid returning handles to object internals because of possible dangling handlers.
    Why not just return a couple of const iterators, like,
    Code:
    class A {
    public:
    	std::vector<int>::const_iterator begin() {return v.cbegin();}
    	std::vector<int>::const_iterator end() {return v.cend();}
    private:
    	std::vector<int> v;
    };
    You expose the internal data structure but at least users cannot change the data.

    The standard approach to better encapsulation is to offer a getter access method like,
    Code:
    class A {
    public:
    	int get(int i) {return v[i];}
    	int size() {v.size();}
    private:
    	std::vector<int> v;
    };
    Yet another approach is to pass in a functor object. A method (for example operator()) of the functor is called with all ints of the vector one by one. This offers good encapsulation because users never know how the ints are actually stored internally. This approach is sometimes called "inner iteration".
    Code:
    class A {
    public:
    	template <typename FUNCTOR>
    	void iterate(FUNCTOR& f) {
    		for (std::vector<int>::const_iterator p=v.cbegin(); p!=v.cend(); ++p) f(*p);
    	}
    private:
    	std::vector<int> v;
    };
    //
    class Sum_Functor {
    public:
    	Sum_Functor() : sum(0) {}
    	int sum;
    	void operator() (int i) {
    		sum += i;
    	}
    };
    //
    A a;
    Sum_Functor sf;
    a.iterate(sf);
    int s = sf.sum;
    Last edited by nuzzle; July 5th, 2010 at 02:38 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured