Boost logo

Boost Users :

Subject: Re: [Boost-users] class API return a const&, optional, shared_ptr
From: Hicham Mouline (hicham_at_[hidden])
Date: 2008-11-25 09:17:22


I have realized I have an extra requirement:

class A and C derive from Base (// cannot be instantiated, it has pure
virtuals)
class Aelem and Celem derive from BaseElem (// cannot be instantiated, it
has pure virtuals)

class Base { // cannot be instantiated
... virtual const BaseElem& get() const =0;
};
Class A : Base {
... const Aelem & get() const;
private:
  map< int, shared_ptr< Aelem > > map_Aelem_s_;
};

Class C : Base {
... const Celem & get() const;
private:
  map< int, shared_ptr< Celem > > mapof Celem s_;
};

Class Aelem {
... const static Aelem notFound;
};

// even if f() below is supposed to use the above classes polymorphically,
// it would be useful to declare A and C's get() to return Aelem and Celem
directly
Void f( const Base& b ) {
   const BaseElem & bref = b.get();
  // here I can't test that bref is "NotFound" coz I
can't instantiate a NotFound BaseElem object (BaseElem is not instantiable)

I can't say that Base::get() returns a shared_ptr< const BaseEleme >
because then what about A.get() and D.get(),
if they return shared_ptr< const Aelem > and shared_ptr< const DElem >
the virtual function will not be overriden
   
Same problem with boost::optional<BaseElem> vs boost::optional<AElem>
boost::optional<CElem>

raw pointers seem to be the way to go,

-----Original Message-----
From: boost-users-bounces_at_[hidden]
[mailto:boost-users-bounces_at_[hidden]] On Behalf Of Alan M. Carroll
Sent: 25 November 2008 13:08
To: boost-users_at_[hidden]
Subject: Re: [Boost-users] class API return a const&, optional, shared_ptr

I prefer the static class member option. Note that it is *not* necessary for
clients to have access to that static if the type has a well defined invalid
value. This is true for shared_ptr. If the static member is null, then
clients need merely check the returned pointer in the normal fashion, as
they should any returned pointer.

On the other hand, one might ask why you would want to return a const ref to
a shared_ptr. That one can cheaply return copies is one of the big features
of shared_ptr.

At 07:15 AM 11/25/2008, 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_;
>};


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