Boost logo

Boost Users :

Subject: Re: [Boost-users] class API return a const&, optional, shared_ptr
From: Jeff Flinn (TriumphSprint2000_at_[hidden])
Date: 2008-11-25 08:17:30


Hicham Mouline wrote:
> hello,
>
> I have a class A that holds a container of objects of type B indexed by int
> for e.g.
>
> Typically, I have a function of A
>
> class A {
> public:
> const B& getB(int <index> ) const;
> private:
> std::map< int, shared_ptr<B> > listOfBs_;
> };
>
> The implementation of getB could be
>
> const B& A::getB(int <index> ) const
> {
> //what to do if index not found
> }
>
> A number of solutions I think of:
>
> 1.
> boost::optional<const B&> getB(int <index> ) const
> {
> }
>
>
> 2.
> change signature to
> const B* getB(int <index> ) const
>
>
> 3.
> Define a
> static const B notFoundB;
> const B& A::getB(int <index> ) const
> returns notFoundB when not found and have API users compare return value
> with notFoundB
>
>
> I suppose the cheapest in overhead/performance is 2... optional must have
> some time overhead?
>
> Are there advised solutions? Favourites in terms of style?
>
> Regards,

There's always:

boost::shared_ptr<const B> get(int i) const
{
    ... // find iterator at key i

    return (... != listOfBs.end())
         ? const_pointer_cast<const B>(*non_end_itr)
         : boost::shared_ptr<const B>();
}

or better yet, you can fully encapsulate the internals of A, while
simplifying the class interface:

void A::visit(int i, boost::function<void (const B&)> fnc) const
{
    ... // find iterator at key i

    if( ... != listOfBs.end()) f(*non_end_itr);
}

In Joel de Guzman's words: "Don't call us, we'll call you!"

By the way listOfBs is a misleading name.

Jeff


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net